diff options
| author | Can Celik <ogulcancelik@gmail.com> | 2026-09-10 21:51:57 +0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-09-10 21:51:57 +0300 |
| commit | 425c86179791cd32e2d4ce0ae7f269940b4b0663 (patch) | |
| tree | e52c4383a6d69216cbe2a32638bf90841d7e2189 /vendor/libghostty-vt/src/terminal/c | |
| parent | 90e947a6e26e02f10ec7f1694c4eb5b78a86406b (diff) | |
chore: upgrade libghostty and preserve terminal behavior (#3906)
Diffstat (limited to 'vendor/libghostty-vt/src/terminal/c')
30 files changed, 9906 insertions, 1258 deletions
diff --git a/vendor/libghostty-vt/src/terminal/c/allocator.zig b/vendor/libghostty-vt/src/terminal/c/allocator.zig index ca698f3c..c6732375 100644 --- a/vendor/libghostty-vt/src/terminal/c/allocator.zig +++ b/vendor/libghostty-vt/src/terminal/c/allocator.zig @@ -7,11 +7,13 @@ const CAllocator = lib.alloc.Allocator; /// (or the default allocator if NULL). /// /// Returns a pointer to the allocated buffer, or NULL if the -/// allocation failed. +/// allocation failed or `len` is zero. pub fn alloc( alloc_: ?*const CAllocator, len: usize, ) callconv(lib.calling_conv) ?[*]u8 { + // Zig's empty allocation pointer is not safe to expose to foreign runtimes. + if (len == 0) return null; const allocator = lib.alloc.default(alloc_); const buf = allocator.alloc(u8, len) catch return null; return buf.ptr; @@ -47,6 +49,7 @@ test "alloc with null allocator" { test "alloc zero length" { const ptr = alloc(&lib.alloc.test_allocator, 0); defer free(&lib.alloc.test_allocator, ptr, 0); + try testing.expectEqual(null, ptr); } test "free null pointer" { diff --git a/vendor/libghostty-vt/src/terminal/c/build_info.zig b/vendor/libghostty-vt/src/terminal/c/build_info.zig index 8e0cd4d6..a186163a 100644 --- a/vendor/libghostty-vt/src/terminal/c/build_info.zig +++ b/vendor/libghostty-vt/src/terminal/c/build_info.zig @@ -45,7 +45,7 @@ pub fn get( out: ?*anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(BuildInfo, @intFromEnum(data)) catch { + _ = std.enums.fromInt(BuildInfo, @intFromEnum(data)) orelse { log.warn("build_info invalid data value={d}", .{@intFromEnum(data)}); return .invalid_value; }; diff --git a/vendor/libghostty-vt/src/terminal/c/cell.zig b/vendor/libghostty-vt/src/terminal/c/cell.zig index b59567df..8444cfd9 100644 --- a/vendor/libghostty-vt/src/terminal/c/cell.zig +++ b/vendor/libghostty-vt/src/terminal/c/cell.zig @@ -10,6 +10,12 @@ const Result = @import("result.zig").Result; /// C: GhosttyCell pub const CCell = u64; +/// C: GhosttyCellsView +pub const CellsView = extern struct { + ptr: ?[*]const CCell, + len: usize, +}; + /// C: GhosttyCellContentTag pub const ContentTag = enum(c_int) { codepoint = 0, @@ -105,7 +111,7 @@ pub fn get( out: ?*anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(CellData, @intFromEnum(data)) catch { + _ = std.enums.fromInt(CellData, @intFromEnum(data)) orelse { return .invalid_value; }; } @@ -158,7 +164,7 @@ fn getTyped( .has_hyperlink => out.* = cell.hyperlink, .protected => out.* = cell.protected, .semantic_content => out.* = @enumFromInt(@intFromEnum(cell.semantic_content)), - .color_palette => out.* = cell.content.color_palette, + .color_palette => out.* = cell.content.color_palette.data, .color_rgb => { const rgb = cell.content.color_rgb; out.* = .{ .r = rgb.r, .g = rgb.g, .b = rgb.b }; diff --git a/vendor/libghostty-vt/src/terminal/c/formatter.zig b/vendor/libghostty-vt/src/terminal/c/formatter.zig index 5b4504c8..4ab41cd4 100644 --- a/vendor/libghostty-vt/src/terminal/c/formatter.zig +++ b/vendor/libghostty-vt/src/terminal/c/formatter.zig @@ -2,6 +2,7 @@ const std = @import("std"); const testing = std.testing; const lib = @import("../lib.zig"); const CAllocator = lib.alloc.Allocator; +const io_c = @import("io.zig"); const terminal_c = @import("terminal.zig"); const grid_ref = @import("grid_ref.zig"); const selection_c = @import("selection.zig"); @@ -160,6 +161,32 @@ fn terminal_new_( return ptr; } +/// Format directly to a synchronous C writer callback. +pub fn format( + formatter_: Formatter, + writer: io_c.Writer, +) callconv(lib.calling_conv) Result { + const wrapper = formatter_ orelse return .invalid_value; + if (!writer.valid()) return .invalid_value; + + // Batch the formatter's many small writes into few callback calls. The + // trailing flush upholds the API contract that success means the + // callback has accepted every byte. + var buffer: [io_c.WriterAdapter.recommended_buffer_len]u8 = undefined; + var adapter: io_c.WriterAdapter = .initBuffered(writer, &buffer); + format_: { + switch (wrapper.kind) { + .terminal => |*t| t.format(adapter.writer()) catch break :format_, + } + adapter.writer().flush() catch break :format_; + return .success; + } + + if (adapter.invalid_write) return .limit_exceeded; + if (adapter.callback_failed) return .io_error; + return .io_error; +} + pub fn format_buf( formatter_: Formatter, out_: ?[*]u8, @@ -207,7 +234,9 @@ pub fn format_alloc( } const buf = aw.toOwnedSlice() catch return .out_of_memory; - out_ptr.* = buf.ptr; + // Empty Zig slices may contain sentinel pointers that foreign runtimes + // reject even when the length is zero (for example Go's stack scanner). + out_ptr.* = if (buf.len == 0) null else buf.ptr; out_len.* = buf.len; return .success; } @@ -223,7 +252,8 @@ test "terminal_new/free" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -253,12 +283,54 @@ test "free null" { free(null); } +test "format_alloc empty output" { + const failing: CAllocator = .fromZig(&std.mem.Allocator.failing); + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + 100, + 40, + )); + defer terminal_c.free(t); + + // Match a zero-initialized C options struct, including trim = false. + const opts: TerminalOptions = std.mem.zeroInit(TerminalOptions, .{}); + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + opts, + )); + defer free(f); + + for ([_]?*const CAllocator{ null, &failing }) |allocator| { + var sentinel: u8 = 0; + var ptr: ?[*]u8 = @ptrCast(&sentinel); + var len: usize = 123; + try testing.expectEqual(Result.success, format_alloc(f, allocator, &ptr, &len)); + defer @import("allocator.zig").free(allocator, ptr, len); + try testing.expectEqual(@as(usize, 0), len); + try testing.expectEqual(null, ptr); + } + + // Reusing the same formatter must still allocate and return real output. + terminal_c.vt_write(t, "hello", 5); + var ptr: ?[*]u8 = null; + var len: usize = 0; + try testing.expectEqual(Result.success, format_alloc(f, null, &ptr, &len)); + defer @import("allocator.zig").free(null, ptr, len); + try testing.expectEqualStrings("hello", ptr.?[0..len]); +} + test "format plain" { var t: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -279,12 +351,103 @@ test "format plain" { try testing.expectEqualStrings("Hello", buf[0..written]); } +test "format streams to writer" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Hello\r\nWorld", 12); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + const Context = struct { + destination: []u8, + offset: usize = 0, + calls: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + if (len > self.destination.len - self.offset) return false; + @memcpy(self.destination[self.offset..][0..len], data[0..len]); + self.offset += len; + self.calls += 1; + return true; + } + }; + + var buf: [1024]u8 = undefined; + var context: Context = .{ .destination = &buf }; + try testing.expectEqual(Result.success, format(f, .{ + .write = &Context.write, + .userdata = &context, + })); + try testing.expect(context.calls > 0); + try testing.expectEqualStrings("Hello\nWorld", buf[0..context.offset]); +} + +test "format writer errors" { + const FailWriter = struct { + fn write( + _: ?*anyopaque, + _: [*]const u8, + _: usize, + ) callconv(lib.calling_conv) bool { + return false; + } + }; + + try testing.expectEqual(Result.invalid_value, format(null, .{ + .write = &FailWriter.write, + })); + + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer terminal_c.free(t); + terminal_c.vt_write(t, "Hello", 5); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + try testing.expectEqual(Result.invalid_value, format(f, .{})); + try testing.expectEqual(Result.io_error, format(f, .{ + .write = &FailWriter.write, + })); +} + test "format reflects terminal changes" { var t: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -316,7 +479,8 @@ test "format null returns required size" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -348,7 +512,8 @@ test "format buffer too small" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -381,7 +546,8 @@ test "format vt" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -408,7 +574,8 @@ test "format plain with selection" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -452,7 +619,8 @@ test "format html" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); diff --git a/vendor/libghostty-vt/src/terminal/c/grid_ref.zig b/vendor/libghostty-vt/src/terminal/c/grid_ref.zig index 946ca8a1..20f49be9 100644 --- a/vendor/libghostty-vt/src/terminal/c/grid_ref.zig +++ b/vendor/libghostty-vt/src/terminal/c/grid_ref.zig @@ -205,7 +205,8 @@ test "grid_ref_hyperlink_uri no hyperlink" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -228,7 +229,8 @@ test "grid_ref_hyperlink_uri with hyperlink" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(terminal); diff --git a/vendor/libghostty-vt/src/terminal/c/grid_ref_tracked.zig b/vendor/libghostty-vt/src/terminal/c/grid_ref_tracked.zig index 60091715..475a8e43 100644 --- a/vendor/libghostty-vt/src/terminal/c/grid_ref_tracked.zig +++ b/vendor/libghostty-vt/src/terminal/c/grid_ref_tracked.zig @@ -96,7 +96,8 @@ test "tracked_grid_ref snapshots after terminal scroll" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -128,7 +129,8 @@ test "tracked_grid_ref reports no value after reset" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -154,7 +156,8 @@ test "tracked_grid_ref reports no value after alternate screen reset" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -194,7 +197,8 @@ test "tracked_grid_ref reports no value after terminal free" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); terminal_c.vt_write(terminal, "A", 1); diff --git a/vendor/libghostty-vt/src/terminal/c/io.zig b/vendor/libghostty-vt/src/terminal/c/io.zig new file mode 100644 index 00000000..76e7451d --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/io.zig @@ -0,0 +1,774 @@ +//! C byte-stream callbacks and adapters for `std.Io`. +//! +//! The public callbacks deliberately expose a smaller contract than Zig's I/O +//! interfaces: reads are synchronous progress/EOF/error, and writes accept an +//! entire slice or fail. These adapters translate that contract while keeping +//! enough state to map failures back to distinct C result codes. + +const std = @import("std"); +const assert = std.debug.assert; +const lib = @import("../lib.zig"); + +/// C: GhosttyReaderFn +pub const ReaderFn = *const fn ( + userdata: ?*anyopaque, + buffer: [*]u8, + capacity: usize, + out_read: *usize, +) callconv(lib.calling_conv) bool; + +/// C: GhosttyWriterFn +pub const WriterFn = *const fn ( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, +) callconv(lib.calling_conv) bool; + +/// C: GhosttyReader +pub const Reader = extern struct { + read: ?ReaderFn = null, + userdata: ?*anyopaque = null, + + pub fn valid(self: Reader) bool { + return self.read != null; + } +}; + +/// C: GhosttyWriter +pub const Writer = extern struct { + write: ?WriterFn = null, + userdata: ?*anyopaque = null, + + pub fn valid(self: Writer) bool { + return self.write != null; + } +}; + +/// C: GhosttyMimeReaderFn +pub const MimeReaderFn = *const fn ( + userdata: ?*anyopaque, + mime: lib.String, + writer: Writer, +) callconv(lib.calling_conv) bool; + +/// C: GhosttyMimeReader +pub const MimeReader = extern struct { + read: ?MimeReaderFn = null, + userdata: ?*anyopaque = null, + + pub fn valid(self: MimeReader) bool { + return self.read != null; + } +}; + +/// Adapts a `GhosttyReader` to `std.Io.Reader`. +/// +/// The adapter must have a stable address while `interface` is in use. Its +/// interface starts unbuffered so `init` can safely return it by value. A +/// one-byte buffer is attached lazily when an operation such as `peekByte` +/// requires buffering. This also prevents reads beyond a requested framing +/// boundary. +pub const ReaderAdapter = struct { + /// Copy of the C callback pair. The pointed-to userdata remains borrowed. + source: Reader, + + /// Zig-facing interface. Its vtable recovers this enclosing adapter with + /// `@fieldParentPtr`, which is why the adapter's address must remain stable. + interface: std.Io.Reader, + + /// Bytes successfully obtained from the callback. + offset: usize = 0, + + /// The callback returned false. This distinguishes an I/O failure from + /// the callback returning true with zero bytes at end-of-file. + callback_failed: bool = false, + + /// The callback was NULL, returned too many bytes, or overflowed offset. + invalid_read: bool = false, + + /// The callback returned true with zero bytes. EOF is permanent. + eof: bool = false, + + /// `std.Io.Reader` needs backing storage for `peekByte`. One byte is + /// intentional: it satisfies that operation without allowing the adapter + /// to pull a second byte across a snapshot checkpoint or FINISH boundary. + peek_buffer: [1]u8 = undefined, + + /// Scratch space used only when the destination writer has no writable + /// buffer of its own. 4 KiB amortizes callback overhead for streaming + /// operations while keeping every adapter's fixed allocation modest. The + /// caller's `limit` always truncates this slice, so the size cannot cause + /// framing read-ahead. + transfer_buffer: [4096]u8 = undefined, + + pub fn init(source: Reader) ReaderAdapter { + return .{ + .source = source, + .interface = .{ + .vtable = &.{ + .stream = stream, + .rebase = rebase, + }, + // `rebase` attaches peek_buffer after the adapter reaches its + // stable destination address. + .buffer = &.{}, + .seek = 0, + .end = 0, + }, + }; + } + + pub fn reader(self: *ReaderAdapter) *std.Io.Reader { + // Calling this only after the adapter reaches its final address makes + // the parent-pointer recovery in `stream` and `rebase` valid. + return &self.interface; + } + + /// Perform exactly one C callback invocation into caller-selected storage. + /// This is the single place that interprets the public callback contract. + fn readInto(self: *ReaderAdapter, destination: []u8) std.Io.Reader.Error!usize { + assert(destination.len > 0); + + // Failure and EOF are sticky. In particular, a callback that reports + // EOF is never polled again because the C API defines it as permanent. + if (self.callback_failed or self.invalid_read) return error.ReadFailed; + if (self.eof) return error.EndOfStream; + + // A missing callback is an invalid C value rather than external I/O + // failure, so record it separately for the public result mapper. + const read_fn = self.source.read orelse { + self.invalid_read = true; + return error.ReadFailed; + }; + + // Initialize this ourselves: a callback returning false is not + // required to initialize out_read. + var read_len: usize = 0; + if (!read_fn( + self.source.userdata, + destination.ptr, + destination.len, + &read_len, + )) { + self.callback_failed = true; + return error.ReadFailed; + } + + // Treat a callback that violates the capacity contract as an invalid + // reader without constructing an out-of-bounds slice. + if (read_len > destination.len) { + self.invalid_read = true; + return error.ReadFailed; + } + // Successful zero-length reads are the C representation of EOF. + if (read_len == 0) { + self.eof = true; + return error.EndOfStream; + } + + // Offset counts only bytes actually supplied by successful callbacks. + // Saturating or wrapping would make SOURCE_OFFSET untrustworthy. + self.offset = std.math.add(usize, self.offset, read_len) catch { + self.invalid_read = true; + return error.ReadFailed; + }; + return read_len; + } + + /// `stream` is the fundamental read primitive in `std.Io.Reader`'s + /// vtable. It moves at most `limit` bytes from the C source to the Zig + /// writer and reports the number transferred. Higher-level operations + /// such as `readSliceAll` and `peekByte` are implemented in terms of it. + fn stream( + reader_: *std.Io.Reader, + writer: *std.Io.Writer, + limit: std.Io.Limit, + ) std.Io.Reader.StreamError!usize { + // A zero limit is a successful no-op and must not invoke user code. + if (limit == .nothing) return 0; + + // The std.Io callback receives only the embedded interface pointer. + // Recover the adapter to reach the C callback and accounting flags. + const self: *ReaderAdapter = @alignCast(@fieldParentPtr( + "interface", + reader_, + )); + + // Use the destination's storage directly when possible. This is the + // normal path for readSlice operations and for filling peek_buffer. + const direct = limit.slice(writer.unusedCapacitySlice()); + if (direct.len > 0) { + const read_len = try self.readInto(direct); + // `readInto` initialized these bytes outside the Writer API, so + // explicitly publish them to the destination. + writer.advance(read_len); + return read_len; + } + + // An unbuffered Writer has no direct destination storage. Read into + // bounded adapter storage and then let its drain implementation take + // ownership of the complete slice. + const transfer = limit.slice(&self.transfer_buffer); + assert(transfer.len > 0); + const read_len = try self.readInto(transfer); + // writeAll either transfers this complete callback result or reports + // failure; returning a partial count would violate stream's contract. + try writer.writeAll(transfer[0..read_len]); + return read_len; + } + + /// Give buffered reader operations contiguous storage on first demand. + /// Initialization cannot point at `peek_buffer` because `init` returns the + /// adapter by value and its final address is not known until afterward. + fn rebase( + reader_: *std.Io.Reader, + capacity: usize, + ) std.Io.Reader.RebaseError!void { + const self: *ReaderAdapter = @alignCast(@fieldParentPtr( + "interface", + reader_, + )); + + if (reader_.buffer.len == 0) { + // No operation could have buffered bytes before storage existed. + assert(reader_.seek == 0); + assert(reader_.end == 0); + reader_.buffer = &self.peek_buffer; + } + + // Like other std.Io.Reader implementations, contiguous peek capacity + // is limited by the reader's declared buffer capacity. + assert(capacity <= reader_.buffer.len); + // Avoid the default memmove when the unread tail already has room. + if (reader_.buffer.len - reader_.seek >= capacity) return; + return std.Io.Reader.defaultRebase(reader_, capacity); + } +}; + +/// Adapts a `GhosttyWriter` to a `std.Io.Writer`. +/// +/// The adapter may be given a buffer via `initBuffered` so that the many +/// small writes typical of streaming producers (e.g. the formatter) are +/// batched into far fewer C callback invocations. A buffered adapter's owner +/// must call `flush` on the interface before reporting success so that the +/// public contract holds: success means the C callback has already accepted +/// every byte. +pub const WriterAdapter = struct { + /// Copy of the C callback pair. The pointed-to userdata remains borrowed. + destination: Writer, + + /// Zig-facing interface whose drain vtable points back to this adapter. + interface: std.Io.Writer, + + /// Bytes accepted by successful callback invocations. Buffered bytes are + /// counted only once a drain or flush hands them to the callback. + offset: usize = 0, + + /// The callback returned false. + callback_failed: bool = false, + + /// The callback was NULL or offset accounting overflowed. + invalid_write: bool = false, + + /// The buffer length used by the C API entry points that stream through + /// a callback. 4 KiB amortizes callback overhead while keeping every + /// adapter's stack footprint modest, mirroring ReaderAdapter's + /// transfer_buffer sizing. + pub const recommended_buffer_len = 4096; + + /// An unbuffered adapter: every Zig write reaches the callback + /// immediately and no flush is required before returning. + pub fn init(destination: Writer) WriterAdapter { + return initBuffered(destination, &.{}); + } + + /// A buffered adapter. The buffer must outlive the adapter and remain + /// at a stable address (it is referenced, not copied). The owner must + /// flush the interface before treating the operation as successful. + pub fn initBuffered(destination: Writer, buffer: []u8) WriterAdapter { + return .{ + .destination = destination, + .interface = .{ + .vtable = &.{ .drain = drain }, + .buffer = buffer, + .end = 0, + }, + }; + } + + pub fn writer(self: *WriterAdapter) *std.Io.Writer { + // As with ReaderAdapter, the returned interface borrows this stable + // enclosing address for parent-pointer recovery in the vtable. + return &self.interface; + } + + /// Submit one ordinary slice through the all-or-nothing C write callback. + fn writeAll(self: *WriterAdapter, data: []const u8) std.Io.Writer.Error!void { + // Empty writes carry no information and should not call foreign code. + if (data.len == 0) return; + + // Make failures sticky so a higher-level Zig retry cannot produce a + // misleading second callback after the output is already partial. + if (self.callback_failed or self.invalid_write) return error.WriteFailed; + + // Missing callbacks are invalid arguments; false callback returns are + // external I/O errors. Preserve that distinction for the C wrapper. + const write_fn = self.destination.write orelse { + self.invalid_write = true; + return error.WriteFailed; + }; + if (!write_fn(self.destination.userdata, data.ptr, data.len)) { + self.callback_failed = true; + return error.WriteFailed; + } + + // Count bytes only after the callback accepts the complete slice. + self.offset = std.math.add(usize, self.offset, data.len) catch { + self.invalid_write = true; + return error.WriteFailed; + }; + } + + /// Write one slice, batching through the interface buffer when one is + /// attached. Slices that fit are parked in the buffer (a later drain or + /// flush hands them to the callback); anything larger goes to the + /// callback directly after the buffer is emptied to preserve ordering. + fn writeSlice( + self: *WriterAdapter, + writer_: *std.Io.Writer, + slice: []const u8, + ) std.Io.Writer.Error!void { + const buffer = writer_.buffer; + if (slice.len <= buffer.len - writer_.end) { + @memcpy(buffer[writer_.end..][0..slice.len], slice); + writer_.end += slice.len; + return; + } + + if (writer_.end > 0) { + try self.writeAll(buffer[0..writer_.end]); + writer_.end = 0; + } + + if (slice.len <= buffer.len) { + @memcpy(buffer[0..slice.len], slice); + writer_.end = slice.len; + } else { + try self.writeAll(slice); + } + } + + /// Implement the sole primitive required by a std.Io.Writer. + /// + /// Zig represents a vector write as ordinary slices followed by the last + /// slice repeated `splat` times. The C callback has no vector form, so + /// this method expands that representation, batching through the + /// interface buffer when one is attached, and returns the total logical + /// byte count consumed from `data`. Bytes parked in the buffer count as + /// consumed; `std.Io.Writer.flush` drains them via this same method. + fn drain( + writer_: *std.Io.Writer, + data: []const []const u8, + splat: usize, + ) std.Io.Writer.Error!usize { + assert(data.len > 0); // The final element is always the splat pattern. + + // The vtable receives the embedded Writer rather than our adapter. + const self: *WriterAdapter = @alignCast(@fieldParentPtr( + "interface", + writer_, + )); + + // Buffered bytes must reach the destination before any of `data`. + if (writer_.end > 0) { + try self.writeAll(writer_.buffer[0..writer_.end]); + writer_.end = 0; + } + + var consumed: usize = 0; + // Every element except the last is written exactly once. + for (data[0 .. data.len - 1]) |slice| { + try self.writeSlice(writer_, slice); + consumed = std.math.add(usize, consumed, slice.len) catch { + self.invalid_write = true; + return error.WriteFailed; + }; + } + + // std.Io uses the final element as a compact repeated pattern. A + // splat of zero means the final element is not part of this write. + const pattern = data[data.len - 1]; + if (pattern.len == 1 and writer_.buffer.len > 0) { + // Single-byte splats (e.g. runs of blank cells) are memset + // into the buffer in bulk rather than repeated one write at + // a time. + const buffer = writer_.buffer; + var remaining = splat; + while (remaining > 0) { + if (writer_.end == buffer.len) { + try self.writeAll(buffer); + writer_.end = 0; + } + const n = @min(remaining, buffer.len - writer_.end); + @memset(buffer[writer_.end..][0..n], pattern[0]); + writer_.end += n; + remaining -= n; + } + consumed = std.math.add(usize, consumed, splat) catch { + self.invalid_write = true; + return error.WriteFailed; + }; + } else for (0..splat) |_| { + try self.writeSlice(writer_, pattern); + consumed = std.math.add(usize, consumed, pattern.len) catch { + self.invalid_write = true; + return error.WriteFailed; + }; + } + return consumed; + } +}; + +test "C reader and writer layouts keep callback first" { + try std.testing.expectEqual(@as(usize, 0), @offsetOf(Reader, "read")); + try std.testing.expectEqual(@sizeOf(?ReaderFn), @offsetOf(Reader, "userdata")); + try std.testing.expectEqual(@sizeOf(?ReaderFn) + @sizeOf(?*anyopaque), @sizeOf(Reader)); + + try std.testing.expectEqual(@as(usize, 0), @offsetOf(Writer, "write")); + try std.testing.expectEqual(@as(usize, 0), @offsetOf(MimeReader, "read")); + try std.testing.expectEqual(@sizeOf(?MimeReaderFn), @offsetOf(MimeReader, "userdata")); + try std.testing.expectEqual(@sizeOf(?WriterFn), @offsetOf(Writer, "userdata")); + try std.testing.expectEqual(@sizeOf(?WriterFn) + @sizeOf(?*anyopaque), @sizeOf(Writer)); +} + +test "ReaderAdapter supports short reads and permanent EOF" { + const Context = struct { + data: []const u8, + offset: usize = 0, + calls: usize = 0, + + fn read( + userdata: ?*anyopaque, + buffer: [*]u8, + capacity: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + self.calls += 1; + const remaining = self.data[self.offset..]; + const len = @min(remaining.len, capacity, 2); + @memcpy(buffer[0..len], remaining[0..len]); + self.offset += len; + out_read.* = len; + return true; + } + }; + + var context: Context = .{ .data = "abcdef" }; + var adapter: ReaderAdapter = .init(.{ + .read = &Context.read, + .userdata = &context, + }); + + var actual: [6]u8 = undefined; + try adapter.interface.readSliceAll(&actual); + try std.testing.expectEqualStrings("abcdef", &actual); + try std.testing.expectEqual(@as(usize, 6), adapter.offset); + try std.testing.expect(!adapter.eof); + + try std.testing.expectError(error.EndOfStream, adapter.interface.takeByte()); + try std.testing.expect(adapter.eof); + try std.testing.expect(!adapter.callback_failed); + + const calls_at_eof = context.calls; + try std.testing.expectError(error.EndOfStream, adapter.interface.takeByte()); + try std.testing.expectEqual(calls_at_eof, context.calls); +} + +test "ReaderAdapter peek reads only the requested byte" { + const Context = struct { + data: []const u8, + offset: usize = 0, + last_capacity: usize = 0, + + fn read( + userdata: ?*anyopaque, + buffer: [*]u8, + capacity: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + self.last_capacity = capacity; + const remaining = self.data[self.offset..]; + const len = @min(remaining.len, capacity); + @memcpy(buffer[0..len], remaining[0..len]); + self.offset += len; + out_read.* = len; + return true; + } + }; + + var context: Context = .{ .data = "ab" }; + var adapter: ReaderAdapter = .init(.{ + .read = &Context.read, + .userdata = &context, + }); + + try std.testing.expectEqual(@as(u8, 'a'), try adapter.interface.peekByte()); + try std.testing.expectEqual(@as(usize, 1), context.last_capacity); + try std.testing.expectEqual(@as(usize, 1), adapter.offset); + try std.testing.expectEqual(@as(u8, 'a'), try adapter.interface.takeByte()); + try std.testing.expectEqual(@as(usize, 1), adapter.offset); +} + +test "ReaderAdapter distinguishes callback failure and invalid length" { + const Failing = struct { + fn read( + _: ?*anyopaque, + _: [*]u8, + _: usize, + _: *usize, + ) callconv(lib.calling_conv) bool { + return false; + } + }; + var failing: ReaderAdapter = .init(.{ .read = &Failing.read }); + try std.testing.expectError(error.ReadFailed, failing.interface.takeByte()); + try std.testing.expect(failing.callback_failed); + try std.testing.expect(!failing.eof); + try std.testing.expect(!failing.invalid_read); + + const Oversized = struct { + fn read( + _: ?*anyopaque, + _: [*]u8, + capacity: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + out_read.* = capacity + 1; + return true; + } + }; + var oversized: ReaderAdapter = .init(.{ .read = &Oversized.read }); + try std.testing.expectError(error.ReadFailed, oversized.interface.takeByte()); + try std.testing.expect(!oversized.callback_failed); + try std.testing.expect(!oversized.eof); + try std.testing.expect(oversized.invalid_read); +} + +test "ReaderAdapter rejects a null callback" { + var adapter: ReaderAdapter = .init(.{}); + try std.testing.expectError(error.ReadFailed, adapter.interface.takeByte()); + try std.testing.expect(adapter.invalid_read); + try std.testing.expect(!adapter.callback_failed); +} + +test "WriterAdapter writes vectors and splats" { + const Context = struct { + data: [32]u8 = undefined, + len: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + @memcpy(self.data[self.len..][0..len], data[0..len]); + self.len += len; + return true; + } + }; + + var context: Context = .{}; + var adapter: WriterAdapter = .init(.{ + .write = &Context.write, + .userdata = &context, + }); + + var vectors: [2][]const u8 = .{ "ab", "cd" }; + try adapter.interface.writeVecAll(&vectors); + var repeated: [1][]const u8 = .{"!"}; + try adapter.interface.writeSplatAll(&repeated, 2); + + try std.testing.expectEqualStrings("abcd!!", context.data[0..context.len]); + try std.testing.expectEqual(@as(usize, 6), adapter.offset); + try std.testing.expect(!adapter.callback_failed); +} + +test "WriterAdapter buffered batches small writes" { + const Context = struct { + data: [256]u8 = undefined, + len: usize = 0, + calls: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + @memcpy(self.data[self.len..][0..len], data[0..len]); + self.len += len; + self.calls += 1; + return true; + } + }; + + var context: Context = .{}; + var buffer: [64]u8 = undefined; + var adapter: WriterAdapter = .initBuffered(.{ + .write = &Context.write, + .userdata = &context, + }, &buffer); + + // Many small writes fit in the buffer: no callback yet. + for (0..16) |_| try adapter.interface.writeAll("ab"); + try std.testing.expectEqual(@as(usize, 0), context.calls); + + // Flush delivers everything in a single call. + try adapter.interface.flush(); + try std.testing.expectEqual(@as(usize, 1), context.calls); + try std.testing.expectEqualStrings( + "ab" ** 16, + context.data[0..context.len], + ); + try std.testing.expectEqual(@as(usize, 32), adapter.offset); +} + +test "WriterAdapter buffered splats and large writes" { + const Context = struct { + data: [256]u8 = undefined, + len: usize = 0, + calls: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + @memcpy(self.data[self.len..][0..len], data[0..len]); + self.len += len; + self.calls += 1; + return true; + } + }; + + var context: Context = .{}; + var buffer: [16]u8 = undefined; + var adapter: WriterAdapter = .initBuffered(.{ + .write = &Context.write, + .userdata = &context, + }, &buffer); + + // A splat larger than the buffer is chunked, not one call per byte. + try adapter.interface.splatByteAll(' ', 40); + // A write larger than the buffer flushes and goes to the callback + // directly. + try adapter.interface.writeAll("0123456789abcdef0"); // 17 > 16 + try adapter.interface.writeAll("xy"); + try adapter.interface.flush(); + + try std.testing.expectEqualStrings( + " " ** 40 ++ "0123456789abcdef0" ++ "xy", + context.data[0..context.len], + ); + try std.testing.expectEqual( + @as(usize, context.len), + adapter.offset, + ); + // Chunked delivery: far fewer calls than bytes. + try std.testing.expect(context.calls <= 6); +} + +test "WriterAdapter makes callback failure sticky" { + const Context = struct { + calls: usize = 0, + + fn write( + userdata: ?*anyopaque, + _: [*]const u8, + _: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + self.calls += 1; + return false; + } + }; + + var context: Context = .{}; + var adapter: WriterAdapter = .init(.{ + .write = &Context.write, + .userdata = &context, + }); + try std.testing.expectError(error.WriteFailed, adapter.interface.writeAll("x")); + try std.testing.expect(adapter.callback_failed); + try std.testing.expectEqual(@as(usize, 0), adapter.offset); + + try std.testing.expectError(error.WriteFailed, adapter.interface.writeAll("y")); + try std.testing.expectEqual(@as(usize, 1), context.calls); +} + +test "WriterAdapter rejects a null callback" { + var adapter: WriterAdapter = .init(.{}); + try std.testing.expectError(error.WriteFailed, adapter.interface.writeAll("x")); + try std.testing.expect(adapter.invalid_write); + try std.testing.expect(!adapter.callback_failed); +} + +test "ReaderAdapter streams into an unbuffered WriterAdapter" { + const ReadContext = struct { + data: []const u8, + offset: usize = 0, + + fn read( + userdata: ?*anyopaque, + buffer: [*]u8, + capacity: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + const remaining = self.data[self.offset..]; + const len = @min(remaining.len, capacity); + @memcpy(buffer[0..len], remaining[0..len]); + self.offset += len; + out_read.* = len; + return true; + } + }; + const WriteContext = struct { + data: [8]u8 = undefined, + len: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + @memcpy(self.data[self.len..][0..len], data[0..len]); + self.len += len; + return true; + } + }; + + var read_context: ReadContext = .{ .data = "stream" }; + var reader: ReaderAdapter = .init(.{ + .read = &ReadContext.read, + .userdata = &read_context, + }); + var write_context: WriteContext = .{}; + var writer: WriterAdapter = .init(.{ + .write = &WriteContext.write, + .userdata = &write_context, + }); + + try reader.interface.streamExact(&writer.interface, "stream".len); + try std.testing.expectEqualStrings( + "stream", + write_context.data[0..write_context.len], + ); + try std.testing.expectEqual(@as(usize, "stream".len), reader.offset); + try std.testing.expectEqual(@as(usize, "stream".len), writer.offset); +} diff --git a/vendor/libghostty-vt/src/terminal/c/key_encode.zig b/vendor/libghostty-vt/src/terminal/c/key_encode.zig index f5d459f0..f0aec36e 100644 --- a/vendor/libghostty-vt/src/terminal/c/key_encode.zig +++ b/vendor/libghostty-vt/src/terminal/c/key_encode.zig @@ -80,7 +80,7 @@ pub fn setopt( value: ?*const anyopaque, ) callconv(lib.calling_conv) void { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + _ = std.enums.fromInt(Option, @intFromEnum(option)) orelse { log.warn("setopt invalid option value={d}", .{@intFromEnum(option)}); return; }; @@ -113,7 +113,7 @@ fn setoptTyped( }, .macos_option_as_alt => { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(OptionAsAlt, @intFromEnum(value.*)) catch { + _ = std.enums.fromInt(OptionAsAlt, @intFromEnum(value.*)) orelse { log.warn("setopt invalid OptionAsAlt value={d}", .{@intFromEnum(value.*)}); return; }; @@ -257,7 +257,8 @@ test "setopt_from_terminal" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -283,7 +284,8 @@ test "setopt_from_terminal null" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); setopt_from_terminal(null, t); diff --git a/vendor/libghostty-vt/src/terminal/c/key_event.zig b/vendor/libghostty-vt/src/terminal/c/key_event.zig index 1feac9ac..b9deecc6 100644 --- a/vendor/libghostty-vt/src/terminal/c/key_event.zig +++ b/vendor/libghostty-vt/src/terminal/c/key_event.zig @@ -38,7 +38,7 @@ pub fn free(event_: Event) callconv(lib.calling_conv) void { pub fn set_action(event_: Event, action: key.Action) callconv(lib.calling_conv) void { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(key.Action, @intFromEnum(action)) catch { + _ = std.enums.fromInt(key.Action, @intFromEnum(action)) orelse { log.warn("set_action invalid action value={d}", .{@intFromEnum(action)}); return; }; @@ -55,7 +55,7 @@ pub fn get_action(event_: Event) callconv(lib.calling_conv) key.Action { pub fn set_key(event_: Event, k: key.Key) callconv(lib.calling_conv) void { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(key.Key, @intFromEnum(k)) catch { + _ = std.enums.fromInt(key.Key, @intFromEnum(k)) orelse { log.warn("set_key invalid key value={d}", .{@intFromEnum(k)}); return; }; diff --git a/vendor/libghostty-vt/src/terminal/c/kitty_graphics.zig b/vendor/libghostty-vt/src/terminal/c/kitty_graphics.zig index 13a675cc..2bd5e862 100644 --- a/vendor/libghostty-vt/src/terminal/c/kitty_graphics.zig +++ b/vendor/libghostty-vt/src/terminal/c/kitty_graphics.zig @@ -10,6 +10,7 @@ const grid_ref = @import("grid_ref.zig"); const selection_c = @import("selection.zig"); const terminal_c = @import("terminal.zig"); const Terminal = @import("../Terminal.zig"); +const PageList = @import("../PageList.zig"); const Result = @import("result.zig").Result; /// C: GhosttyKittyGraphics @@ -261,8 +262,11 @@ fn imageGetTyped( .height => out.* = image.height, .format => out.* = image.format, .compression => out.* = image.compression, - .data_ptr => out.* = image.data.ptr, - .data_len => out.* = image.data.len, + // For animated images this is the current animation frame's + // data; the image generation changes whenever the current + // frame does, so generation-keyed caches stay coherent. + .data_ptr => out.* = (image.renderData().bytes() orelse return .no_value).ptr, + .data_len => out.* = image.renderData().len(), .generation => out.* = image.generation, } @@ -301,7 +305,7 @@ pub fn placement_iterator_set( if (comptime !build_options.kitty_graphics) return .no_value; if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(PlacementIteratorOption, @intFromEnum(option)) catch { + _ = std.enums.fromInt(PlacementIteratorOption, @intFromEnum(option)) orelse { return .invalid_value; }; } @@ -516,16 +520,12 @@ pub fn placement_source_rect( const entry = iter.entry orelse return .invalid_value; const p = entry.value_ptr; - // Apply "0 = full image dimension" convention, then clamp to image bounds. - const x = @min(p.source_x, image.width); - const y = @min(p.source_y, image.height); - const w = @min(if (p.source_width > 0) p.source_width else image.width, image.width - x); - const h = @min(if (p.source_height > 0) p.source_height else image.height, image.height - y); + const source = p.sourceRect(image.*); - out_x.* = x; - out_y.* = y; - out_width.* = w; - out_height.* = h; + out_x.* = source.x; + out_y.* = source.y; + out_width.* = source.width; + out_height.* = source.height; return .success; } @@ -576,12 +576,11 @@ pub fn placement_render_info( out.viewport_row = vp.row; out.viewport_visible = vp.visible; - const x = @min(p.source_x, image.width); - const y = @min(p.source_y, image.height); - out.source_x = x; - out.source_y = y; - out.source_width = @min(if (p.source_width > 0) p.source_width else image.width, image.width - x); - out.source_height = @min(if (p.source_height > 0) p.source_height else image.height, image.height - y); + const source = p.sourceRect(image.*); + out.source_x = source.x; + out.source_y = source.y; + out.source_width = source.width; + out.source_height = source.height; return .success; } @@ -595,9 +594,9 @@ pub fn placement_render_info( /// the placement's origin has scrolled above the top of the viewport. /// /// A placement is considered not visible if it is a virtual (unicode -/// placeholder) placement, or if it is fully off-screen (its bottom -/// edge is above the viewport or its top edge is at or below the -/// viewport's last row). +/// placeholder) placement, its tracked content has been pruned, or it is +/// fully off-screen (its bottom edge is above the viewport or its top edge is +/// at or below the viewport's last row). fn computeViewportPos( p: *const kitty_storage.ImageStorage.Placement, image: *const Image, @@ -605,11 +604,37 @@ fn computeViewportPos( ) struct { col: i32, row: i32, visible: bool } { // Virtual placements use unicode placeholders and don't have a // screen position — they are rendered inline by the text layout. - const pin = switch (p.location) { - .pin => |pin| pin, + // Relative placements are anchored at the root of their parent + // chain, offset by the accumulated chain offsets. A chain rooted + // at a virtual placement has no resolvable position here: its + // origin is the parent's placeholder cells, which only a renderer + // scanning the screen can locate. + const origin: struct { + pin: *const PageList.Pin, + col_offset: i32 = 0, + row_offset: i32 = 0, + } = switch (p.location) { + .pin => |pin| .{ .pin = pin }, .virtual => return .{ .col = 0, .row = 0, .visible = false }, + .relative => |rel| origin: { + const storage = &t.screens.active.kitty_images; + const chain = storage.resolveChain(rel) orelse + return .{ .col = 0, .row = 0, .visible = false }; + switch (chain.root.location) { + .pin => |root_pin| break :origin .{ + .pin = root_pin, + .col_offset = chain.horizontal_offset, + .row_offset = chain.vertical_offset, + }, + .virtual => return .{ .col = 0, .row = 0, .visible = false }, + .relative => unreachable, // resolveChain roots are never relative + } + }, }; + const pin = origin.pin; + if (pin.garbage) return .{ .col = 0, .row = 0, .visible = false }; + // Convert both the placement's pin and the viewport's top-left // corner to screen-absolute coordinates so we can subtract them // to get viewport-relative coordinates. @@ -622,23 +647,30 @@ fn computeViewportPos( // Subtracting viewport origin from the pin gives us viewport- // relative coordinates. The row can be negative when the - // placement has partially scrolled above the viewport. - const vp_row: i32 = @as(i32, @intCast(pin_screen.screen.y)) - - @as(i32, @intCast(vp_screen.screen.y)); - const vp_col: i32 = @intCast(pin_screen.screen.x); - - // A placement is invisible if its bottom edge (row + height) - // is above the viewport, or its top edge is at or below the - // viewport's last row. + // placement has partially scrolled above the viewport, and both + // can be negative for relative placements with negative offsets. + const vp_row: i32 = (@as(i32, @intCast(pin_screen.screen.y)) - + @as(i32, @intCast(vp_screen.screen.y))) +| origin.row_offset; + const vp_col: i32 = @as(i32, @intCast(pin_screen.screen.x)) +| + origin.col_offset; + + // A placement is invisible if its bottom edge (row + height) is + // above the viewport, or its top edge is at or below the viewport's + // last row. The same applies horizontally: a pin's column is always + // in bounds, but a relative placement's offsets can push it fully + // off either side. const grid_size = p.gridSize(image.*, t); - const rows_i32: i32 = @intCast(grid_size.rows); - const term_rows: i32 = @intCast(t.rows); - const visible = vp_row + rows_i32 > 0 and vp_row < term_rows; + const bottom_row = @as(i64, vp_row) + @as(i64, grid_size.rows); + const right_col = @as(i64, vp_col) + @as(i64, grid_size.cols); + const visible = bottom_row > 0 and vp_row < @as(i32, t.rows) and + right_col > 0 and vp_col < @as(i32, t.cols); return .{ .col = vp_col, .row = vp_row, .visible = visible }; } test "placement_iterator new/free" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + var iter: PlacementIterator = null; try testing.expectEqual(Result.success, placement_iterator_new( &lib.alloc.test_allocator, @@ -659,7 +691,8 @@ test "placement_iterator next on empty storage" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -688,7 +721,8 @@ test "placement_iterator get before next returns invalid" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -719,7 +753,8 @@ test "placement_iterator with transmit and display" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -772,7 +807,8 @@ test "placement_iterator with multiple placements" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -829,7 +865,8 @@ test "placement_iterator_set layer filter" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -919,7 +956,8 @@ test "image_get_handle returns null for missing id" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -940,7 +978,8 @@ test "image_get_handle and image_get with transmitted image" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -983,6 +1022,57 @@ test "image_get_handle and image_get with transmitted image" { try testing.expect(data_len > 0); } +test "image_get exposes pending metadata without a data pointer" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer terminal_c.free(t); + + var graphics: KittyGraphics = undefined; + try testing.expectEqual(Result.success, terminal_c.get( + t, + .kitty_graphics, + @ptrCast(&graphics), + )); + + const alloc = lib.alloc.default(&lib.alloc.test_allocator); + const pending = try graphics.addPendingImage(testing.io, alloc, terminal_c.zigTerminal(t).?.screens.active, .{ + .id = 42, + .number = 7, + .width = 1, + .height = 4, + .format = .rgb, + .data = .{ .pending = 12 }, + }); + + const img = image_get_handle(graphics, 42); + try testing.expect(img != null); + + var number: u32 = 0; + try testing.expectEqual(Result.success, image_get(img, .number, @ptrCast(&number))); + try testing.expectEqual(@as(u32, 7), number); + + var data_len: usize = 0; + try testing.expectEqual(Result.success, image_get(img, .data_len, @ptrCast(&data_len))); + try testing.expectEqual(@as(usize, 12), data_len); + + var data_ptr: [*]const u8 = undefined; + try testing.expectEqual(Result.no_value, image_get(img, .data_ptr, @ptrCast(&data_ptr))); + + const pixels = try alloc.dupe(u8, "*" ** 12); + try testing.expect(pending.complete(graphics, testing.io, pixels)); + const completed_img = image_get_handle(graphics, 42); + try testing.expect(completed_img != null); + try testing.expectEqual(Result.success, image_get(completed_img, .data_ptr, @ptrCast(&data_ptr))); + try testing.expectEqualSlices(u8, pixels, data_ptr[0..data_len]); +} + test "placement_rect with transmit and display" { if (comptime !build_options.kitty_graphics) return error.SkipZigTest; @@ -990,7 +1080,8 @@ test "placement_rect with transmit and display" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1051,7 +1142,8 @@ test "placement_pixel_size with transmit and display" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1106,7 +1198,8 @@ test "placement_grid_size with transmit and display" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1160,7 +1253,8 @@ test "placement_viewport_pos with transmit and display" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1205,7 +1299,8 @@ test "placement_viewport_pos fully off-screen above" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 5, .max_scrollback = 100 }, + 80, + 5, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 5, 10, 20)); @@ -1244,7 +1339,8 @@ test "placement_viewport_pos top off-screen" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 5, .max_scrollback = 100 }, + 80, + 5, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 5, 10, 20)); @@ -1287,7 +1383,8 @@ test "placement_viewport_pos bottom off-screen" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 5, .max_scrollback = 0 }, + 80, + 5, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 5, 10, 20)); @@ -1327,7 +1424,8 @@ test "placement_viewport_pos top and bottom off-screen" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 5, .max_scrollback = 100 }, + 80, + 5, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 5, 10, 20)); @@ -1378,7 +1476,8 @@ test "placement_source_rect defaults to full image" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); @@ -1417,7 +1516,8 @@ test "placement_source_rect with explicit source rect" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); @@ -1461,7 +1561,8 @@ test "placement_source_rect clamps to image bounds" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); @@ -1496,6 +1597,15 @@ test "placement_source_rect clamps to image bounds" { try testing.expectEqual(3, y); try testing.expectEqual(1, w); try testing.expectEqual(1, h); + + var pixel_width: u32 = undefined; + var pixel_height: u32 = undefined; + try testing.expectEqual( + Result.success, + placement_pixel_size(iter, img, t, &pixel_width, &pixel_height), + ); + try testing.expectEqual(1, pixel_width); + try testing.expectEqual(1, pixel_height); } test "placement_source_rect null args return invalid_value" { @@ -1522,7 +1632,8 @@ test "placement_render_info returns all fields" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); @@ -1552,6 +1663,53 @@ test "placement_render_info returns all fields" { try testing.expectEqual(0, ri.source_y); try testing.expectEqual(1, ri.source_width); try testing.expectEqual(2, ri.source_height); + + const entry = iter.?.entry.?; + const pin = switch (entry.value_ptr.location) { + .pin => |pin| pin, + .virtual, .relative => unreachable, + }; + pin.garbage = true; + + ri = .{}; + try testing.expectEqual(Result.success, placement_render_info(iter, img, t, &ri)); + try testing.expect(!ri.viewport_visible); + + var rect: selection_c.CSelection = undefined; + try testing.expectEqual(Result.no_value, placement_rect(iter, img, t, &rect)); +} + +test "placement_render_info handles maximum grid dimensions" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer terminal_c.free(t); + try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); + + const cmd = "\x1b_Ga=T,t=d,f=24,i=1,p=1,s=1,v=2,c=1,r=4294967295,C=1;////////\x1b\\"; + terminal_c.vt_write(t, cmd.ptr, cmd.len); + + var graphics: KittyGraphics = undefined; + try testing.expectEqual(Result.success, terminal_c.get(t, .kitty_graphics, @ptrCast(&graphics))); + const img = image_get_handle(graphics, 1); + try testing.expect(img != null); + + var iter: PlacementIterator = null; + try testing.expectEqual(Result.success, placement_iterator_new(&lib.alloc.test_allocator, &iter)); + defer placement_iterator_free(iter); + try testing.expectEqual(Result.success, get(graphics, .placement_iterator, @ptrCast(&iter))); + try testing.expect(placement_iterator_next(iter)); + + var ri: PlacementRenderInfo = .{}; + try testing.expectEqual(Result.success, placement_render_info(iter, img, t, &ri)); + try testing.expect(ri.viewport_visible); + try testing.expectEqual(std.math.maxInt(u32), ri.grid_rows); } test "placement_render_info off-screen sets viewport_visible false" { @@ -1561,7 +1719,8 @@ test "placement_render_info off-screen sets viewport_visible false" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 5, .max_scrollback = 100 }, + 80, + 5, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 5, 10, 20)); @@ -1610,7 +1769,8 @@ test "image_get_multi success" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); @@ -1664,7 +1824,8 @@ test "placement_get_multi success" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); try testing.expectEqual(Result.success, terminal_c.resize(t, 80, 24, 10, 20)); @@ -1722,7 +1883,8 @@ test "storage generation via get" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1774,7 +1936,8 @@ test "image generation detects same-sized retransmission" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1835,7 +1998,8 @@ test "image generation via image_get_multi" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1871,7 +2035,8 @@ test "image compression and format always report decoded data" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -1917,7 +2082,8 @@ test "generation never recurs across resets and screen switches" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); diff --git a/vendor/libghostty-vt/src/terminal/c/main.zig b/vendor/libghostty-vt/src/terminal/c/main.zig index 37dc5768..45b4dc47 100644 --- a/vendor/libghostty-vt/src/terminal/c/main.zig +++ b/vendor/libghostty-vt/src/terminal/c/main.zig @@ -10,6 +10,7 @@ pub const focus = @import("focus.zig"); pub const formatter = @import("formatter.zig"); pub const grid_ref = @import("grid_ref.zig"); pub const grid_ref_tracked = @import("grid_ref_tracked.zig"); +pub const io = @import("io.zig"); pub const kitty_graphics = @import("kitty_graphics.zig"); pub const kitty_graphics_get = kitty_graphics.get; pub const kitty_graphics_image = kitty_graphics.image_get_handle; @@ -39,8 +40,10 @@ pub const mouse_event = @import("mouse_event.zig"); pub const mouse_encode = @import("mouse_encode.zig"); pub const paste = @import("paste.zig"); pub const row = @import("row.zig"); +pub const search = @import("search.zig"); pub const sgr = @import("sgr.zig"); pub const size_report = @import("size_report.zig"); +pub const snapshot = @import("snapshot.zig"); pub const style = @import("style.zig"); pub const sys = @import("sys.zig"); pub const terminal = @import("terminal.zig"); @@ -76,6 +79,7 @@ pub const focus_encode = focus.encode; pub const mode_report_encode = modes.report_encode; pub const formatter_terminal_new = formatter.terminal_new; +pub const formatter_format = formatter.format; pub const formatter_format_buf = formatter.format_buf; pub const formatter_format_alloc = formatter.format_alloc; pub const formatter_free = formatter.free; @@ -85,12 +89,13 @@ pub const render_state_free = render.free; pub const render_state_update = render.update; pub const render_state_begin_update = render.begin_update; pub const render_state_end_update = render.end_update; +pub const render_state_clean = render.clean; pub const render_state_get = render.get; pub const render_state_get_multi = render.get_multi; pub const render_state_set = render.set; -pub const render_state_colors_get = render.colors_get; pub const render_state_row_iterator_new = render.row_iterator_new; pub const render_state_row_iterator_next = render.row_iterator_next; +pub const render_state_row_iterator_next_dirty = render.row_iterator_next_dirty; pub const render_state_row_get = render.row_get; pub const render_state_row_get_multi = render.row_get_multi; pub const render_state_row_set = render.row_set; @@ -111,8 +116,6 @@ pub const sgr_unknown_full = sgr.unknown_full; pub const sgr_unknown_partial = sgr.unknown_partial; pub const sgr_attribute_tag = sgr.attribute_tag; pub const sgr_attribute_value = sgr.attribute_value; -pub const wasm_alloc_sgr_attribute = sgr.wasm_alloc_attribute; -pub const wasm_free_sgr_attribute = sgr.wasm_free_attribute; pub const key_event_new = key_event.new; pub const key_event_free = key_event.free; @@ -158,6 +161,7 @@ pub const mouse_encoder_encode = mouse_encode.encode; pub const paste_is_safe = paste.is_safe; pub const paste_encode = paste.encode; +pub const terminal_paste = paste.terminal_paste; pub const alloc_alloc = allocator.alloc; pub const alloc_free = allocator.free; @@ -182,13 +186,15 @@ pub const terminal_reset = terminal.reset; pub const terminal_resize = terminal.resize; pub const terminal_set = terminal.set; pub const terminal_vt_write = terminal.vt_write; +pub const terminal_vt_write_until_ground = terminal.vt_write_until_ground; pub const terminal_scroll_viewport = terminal.scroll_viewport; pub const terminal_compression_activity = terminal.compression_activity; pub const terminal_compress = terminal.compress; -pub const terminal_mode_get = terminal.mode_get; -pub const terminal_mode_set = terminal.mode_set; pub const terminal_get = terminal.get; pub const terminal_get_multi = terminal.get_multi; +pub const terminal_continuation_write = terminal.continuation_write; +pub const terminal_continuation_buf = terminal.continuation_buf; +pub const terminal_continuation_alloc = terminal.continuation_alloc; pub const terminal_select_word = selection.word; pub const terminal_select_word_between = selection.word_between; pub const terminal_select_line = selection.line; @@ -210,10 +216,31 @@ pub const selection_gesture_get_multi = selection_gesture.get_multi; pub const selection_gesture_event_new = selection_gesture.event_new; pub const selection_gesture_event_free = selection_gesture.event_free; pub const selection_gesture_event_set = selection_gesture.event_set; +pub const search_new = search.new; +pub const search_free = search.free; +pub const search_tick = search.tick; +pub const search_feed = search.feed; +pub const search_run = search.run; +pub const search_set = search.set; +pub const search_get = search.get; +pub const search_get_multi = search.get_multi; pub const terminal_grid_ref = terminal.grid_ref; pub const terminal_grid_ref_track = terminal.grid_ref_track; pub const terminal_point_from_grid_ref = terminal.point_from_grid_ref; +pub const snapshot_encode = snapshot.encode; +pub const snapshot_encode_buf = snapshot.encode_buf; +pub const snapshot_encode_alloc = snapshot.encode_alloc; +pub const snapshot_decoder_new = snapshot.decoder_new; +pub const snapshot_decoder_new_buf = snapshot.decoder_new_buf; +pub const snapshot_decoder_free = snapshot.decoder_free; +pub const snapshot_decoder_set = snapshot.decoder_set; +pub const snapshot_decoder_get = snapshot.decoder_get; +pub const snapshot_decoder_get_multi = snapshot.decoder_get_multi; +pub const snapshot_decoder_ready = snapshot.decoder_ready; +pub const snapshot_decoder_next = snapshot.decoder_next; +pub const snapshot_decoder_decode = snapshot.decoder_decode; + pub const type_json = types.get_json; pub const unicode_codepoint_width = unicode.codepoint_width; @@ -238,6 +265,7 @@ test { _ = color_scheme; _ = grid_ref; _ = grid_ref_tracked; + _ = io; _ = kitty_graphics; _ = row; _ = focus; @@ -252,8 +280,10 @@ test { _ = mouse_event; _ = mouse_encode; _ = paste; + _ = search; _ = sgr; _ = size_report; + _ = snapshot; _ = style; _ = sys; _ = terminal; diff --git a/vendor/libghostty-vt/src/terminal/c/modes.zig b/vendor/libghostty-vt/src/terminal/c/modes.zig index 449ce63e..b249b2a5 100644 --- a/vendor/libghostty-vt/src/terminal/c/modes.zig +++ b/vendor/libghostty-vt/src/terminal/c/modes.zig @@ -8,10 +8,10 @@ pub const ReportState = enum(c_int) { _, fn toZig(self: ReportState) ?modes.Report.State { - return std.meta.intToEnum( + return std.enums.fromInt( modes.Report.State, @intFromEnum(self), - ) catch null; + ); } }; diff --git a/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig b/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig index 331dd606..2586a57a 100644 --- a/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig +++ b/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig @@ -113,7 +113,7 @@ pub fn setopt( value: ?*const anyopaque, ) callconv(lib.calling_conv) void { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + _ = std.enums.fromInt(Option, @intFromEnum(option)) orelse { log.warn("setopt invalid option value={d}", .{@intFromEnum(option)}); return; }; @@ -137,7 +137,7 @@ fn setoptTyped( switch (option) { .event => { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(TrackingMode, @intFromEnum(value.*)) catch { + _ = std.enums.fromInt(TrackingMode, @intFromEnum(value.*)) orelse { log.warn("setopt invalid TrackingMode value={d}", .{@intFromEnum(value.*)}); return; }; @@ -149,7 +149,7 @@ fn setoptTyped( .format => { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Format, @intFromEnum(value.*)) catch { + _ = std.enums.fromInt(Format, @intFromEnum(value.*)) orelse { log.warn("setopt invalid Format value={d}", .{@intFromEnum(value.*)}); return; }; @@ -324,7 +324,8 @@ test "setopt_from_terminal" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); @@ -346,7 +347,8 @@ test "setopt_from_terminal null" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer terminal_c.free(t); setopt_from_terminal(null, t); diff --git a/vendor/libghostty-vt/src/terminal/c/mouse_event.zig b/vendor/libghostty-vt/src/terminal/c/mouse_event.zig index b3c19dd3..b97b4661 100644 --- a/vendor/libghostty-vt/src/terminal/c/mouse_event.zig +++ b/vendor/libghostty-vt/src/terminal/c/mouse_event.zig @@ -51,7 +51,7 @@ pub fn free(event_: Event) callconv(lib.calling_conv) void { pub fn set_action(event_: Event, action: Action) callconv(lib.calling_conv) void { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Action, @intFromEnum(action)) catch { + _ = std.enums.fromInt(Action, @intFromEnum(action)) orelse { log.warn("set_action invalid action value={d}", .{@intFromEnum(action)}); return; }; @@ -66,7 +66,7 @@ pub fn get_action(event_: Event) callconv(lib.calling_conv) Action { pub fn set_button(event_: Event, button: Button) callconv(lib.calling_conv) void { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Button, @intFromEnum(button)) catch { + _ = std.enums.fromInt(Button, @intFromEnum(button)) orelse { log.warn("set_button invalid button value={d}", .{@intFromEnum(button)}); return; }; diff --git a/vendor/libghostty-vt/src/terminal/c/osc.zig b/vendor/libghostty-vt/src/terminal/c/osc.zig index 7ba32300..2ecc9c97 100644 --- a/vendor/libghostty-vt/src/terminal/c/osc.zig +++ b/vendor/libghostty-vt/src/terminal/c/osc.zig @@ -12,6 +12,9 @@ pub const Parser = ?*osc.Parser; /// C: GhosttyOscCommand pub const Command = ?*osc.Command; +/// C: GhosttyOscCommandType +pub const CommandType = osc.Command.Key; + pub fn new( alloc_: ?*const CAllocator, result: *Parser, @@ -44,7 +47,7 @@ pub fn end(parser_: Parser, terminator: u8) callconv(lib.calling_conv) Command { return parser_.?.end(terminator); } -pub fn commandType(command_: Command) callconv(lib.calling_conv) osc.Command.Key { +pub fn commandType(command_: Command) callconv(lib.calling_conv) CommandType { const command = command_ orelse return .invalid; return command.*; } @@ -69,7 +72,7 @@ pub fn commandData( out: ?*anyopaque, ) callconv(lib.calling_conv) bool { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(CommandData, @intFromEnum(data)) catch { + _ = std.enums.fromInt(CommandData, @intFromEnum(data)) orelse { log.warn("commandData invalid data value={d}", .{@intFromEnum(data)}); return false; }; diff --git a/vendor/libghostty-vt/src/terminal/c/paste.zig b/vendor/libghostty-vt/src/terminal/c/paste.zig index bce6a565..8dfa649c 100644 --- a/vendor/libghostty-vt/src/terminal/c/paste.zig +++ b/vendor/libghostty-vt/src/terminal/c/paste.zig @@ -1,8 +1,130 @@ const std = @import("std"); const lib = @import("../lib.zig"); const paste = @import("../../input/paste.zig"); +const terminal_paste_pkg = @import("../paste.zig"); +const clipboard = @import("../clipboard.zig"); +const io = @import("io.zig"); +const terminal_c = @import("terminal.zig"); +const Terminal = terminal_c.Terminal; +const ClipboardContent = terminal_c.ClipboardContent; +const ClipboardRead = terminal_c.ClipboardRead; +const ClipboardReadReply = terminal_c.ClipboardReadReply; const Result = @import("result.zig").Result; +/// Why a paste happened. The flat C form of the Zig tagged union +/// (terminal.paste.Source); the location rides alongside in +/// GhosttyPaste and only applies to a clipboard paste. +/// +/// C: GhosttyPasteSource +pub const Source = lib.Enum(lib.target, &.{ + "clipboard", + "text", +}); + +/// A paste of clipboard contents into the terminal. Sized struct. +/// +/// C: GhosttyPaste +pub const Request = extern struct { + size: usize = @sizeOf(Request), + location: clipboard.Location, + source: Source, + mimes: ?[*]const lib.String, + mimes_len: usize, + reader: io.MimeReader, + allow_unsafe: bool, +}; + +pub fn terminal_paste( + terminal_: Terminal, + req_: ?*const Request, + out_written: ?*bool, +) callconv(lib.calling_conv) Result { + const wrapper = terminal_ orelse return .invalid_value; + const req = req_ orelse return .invalid_value; + + // Every field is required; a smaller size is a caller from a + // different ABI version than any this struct has had. + if (req.size < @sizeOf(Request)) return .invalid_value; + + // The handler always has a write_pty trampoline that no-ops without + // a C callback, so the "nothing can be written" check is ours. + if (wrapper.effects.write_pty == null) return .invalid_value; + + const c_mimes: []const lib.String = if (req.mimes) |ptr| + ptr[0..req.mimes_len] + else + &.{}; + + // Only a paste with something to read needs a reader. + if (c_mimes.len > 0 and !req.reader.valid()) return .invalid_value; + + // A paste carries a handful of representations, so keep the common + // case allocation-free. + var sfa = std.heap.stackFallback(256, wrapper.terminal.gpa()); + const alloc = sfa.get(); + const mimes = alloc.alloc([]const u8, c_mimes.len) catch return .out_of_memory; + defer alloc.free(mimes); + for (mimes, c_mimes) |*mime, c_mime| mime.* = c_mime.ptr[0..c_mime.len]; + + const written = wrapper.stream.handler.paste(.{ + .source = switch (req.source) { + .clipboard => .{ .clipboard = req.location }, + .text => .text, + }, + .contents = .{ .reader = .{ + .mimes = mimes, + .read = .{ .ctx = @constCast(req), .read_fn = &readTrampoline }, + } }, + .allow_unsafe = req.allow_unsafe, + }) catch |err| return switch (err) { + error.UnsafePaste => .rejected, + error.NoWritePty => .invalid_value, + error.OutOfMemory => .out_of_memory, + error.ReadFailed, + error.EntropyUnavailable, + error.Canceled, + => .io_error, + }; + if (out_written) |ptr| ptr.* = written; + return .success; +} + +/// The sink handed to the C read callback: a GhosttyWriter over the +/// Zig sink, remembering whether the sink itself failed so that can be +/// told apart from the callback failing to read. +const Sink = struct { + writer: *std.Io.Writer, + write_failed: bool = false, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *Sink = @ptrCast(@alignCast(userdata.?)); + self.writer.writeAll(data[0..len]) catch { + self.write_failed = true; + return false; + }; + return true; + } +}; + +fn readTrampoline( + ctx: ?*anyopaque, + mime: []const u8, + writer: *std.Io.Writer, +) clipboard.MimeReader.Error!void { + const req: *const Request = @ptrCast(@alignCast(ctx.?)); + var sink: Sink = .{ .writer = writer }; + if (!req.reader.read.?(req.reader.userdata, .init(mime), .{ + .write = &Sink.write, + .userdata = &sink, + })) { + return if (sink.write_failed) error.WriteFailed else error.ReadFailed; + } +} + pub fn is_safe(data: ?[*]const u8, len: usize) callconv(lib.calling_conv) bool { const slice: []const u8 = if (data) |v| v[0..len] else &.{}; return paste.isSafe(slice); @@ -127,3 +249,273 @@ test "is_safe with null empty data" { const testing = std.testing; try testing.expect(is_safe(null, 0)); } + +/// Capture state for the terminal_paste tests: every pty write and the +/// clipboard reads that follow a paste event. +const TerminalPasteCapture = struct { + var written: [1024]u8 = undefined; + var written_len: usize = 0; + var write_count: usize = 0; + var read_count: usize = 0; + var last_read_granted: bool = false; + + fn reset() void { + written_len = 0; + write_count = 0; + read_count = 0; + last_read_granted = false; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + @memcpy(written[written_len..][0..len], ptr[0..len]); + written_len += len; + write_count += 1; + } + + fn clipboardRead(_: Terminal, _: ?*anyopaque, request: *const ClipboardRead) callconv(lib.calling_conv) void { + read_count += 1; + last_read_granted = request.granted; + const contents = [_]ClipboardContent{.{ + .mime = .init(@as([]const u8, "text/plain")), + .data = .init(@as([]const u8, "Ghostty")), + }}; + request.reply(request, &.{ + .size = @sizeOf(ClipboardReadReply), + .result = .success, + .contents = &contents, + .contents_len = contents.len, + .available = null, + .available_len = 0, + .remember = false, + }); + } + + fn writtenSlice() []const u8 { + return written[0..written_len]; + } + + /// The representations a test paste serves: the MIME list for the + /// request and the data the read callback streams, in pieces. + const Contents = struct { + mimes: [2]lib.String = undefined, + data: [2][]const u8 = undefined, + len: usize = 0, + reads: [2]usize = @splat(0), + fail: bool = false, + + fn init(entries: []const struct { []const u8, []const u8 }) Contents { + var self: Contents = .{}; + for (entries) |entry| { + self.mimes[self.len] = .init(entry[0]); + self.data[self.len] = entry[1]; + self.len += 1; + } + return self; + } + + fn request(self: *Contents) Request { + return .{ + .location = .standard, + .source = .clipboard, + .mimes = &self.mimes, + .mimes_len = self.len, + .reader = .{ .read = &read, .userdata = self }, + .allow_unsafe = false, + }; + } + + fn read(userdata: ?*anyopaque, mime: lib.String, writer: io.Writer) callconv(lib.calling_conv) bool { + const self: *Contents = @ptrCast(@alignCast(userdata.?)); + // The mime is the exact string from the request's list, so + // identifying it by pointer works. + const index: usize = for (self.mimes[0..self.len], 0..) |m, i| { + if (m.ptr == mime.ptr and m.len == mime.len) break i; + } else return false; + self.reads[index] += 1; + if (self.fail) return false; + const data = self.data[index]; + var offset: usize = 0; + while (offset < data.len) { + const n = @min(3, data.len - offset); + if (!writer.write.?(writer.userdata, data[offset..].ptr, n)) return false; + offset += n; + } + return true; + } + }; +}; + +test "terminal_paste null handling" { + const testing = std.testing; + const S = TerminalPasteCapture; + + var t: Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new(&lib.alloc.test_allocator, &t, 80, 24)); + defer terminal_c.free(t); + try testing.expectEqual(Result.success, terminal_c.set(t, .write_pty, @ptrCast(&S.writePty))); + + var written: bool = true; + var contents: S.Contents = .init(&.{.{ "text/plain", "hello" }}); + const req = contents.request(); + try testing.expectEqual(Result.invalid_value, terminal_paste(null, &req, &written)); + try testing.expectEqual(Result.invalid_value, terminal_paste(t, null, &written)); + try testing.expect(written); + + // A size smaller than the struct is rejected. + var small = req; + small.size = @sizeOf(usize); + try testing.expectEqual(Result.invalid_value, terminal_paste(t, &small, &written)); + + // MIME types without a reader are rejected; none at all is fine. + var unreadable = req; + unreadable.reader.read = null; + try testing.expectEqual(Result.invalid_value, terminal_paste(t, &unreadable, &written)); + unreadable.mimes = null; + unreadable.mimes_len = 0; + try testing.expectEqual(Result.success, terminal_paste(t, &unreadable, &written)); + try testing.expect(!written); +} + +test "terminal_paste without write_pty is invalid" { + const testing = std.testing; + const S = TerminalPasteCapture; + S.reset(); + + var t: Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new(&lib.alloc.test_allocator, &t, 80, 24)); + defer terminal_c.free(t); + + var contents: S.Contents = .init(&.{.{ "text/plain", "hello" }}); + const req = contents.request(); + try testing.expectEqual(Result.invalid_value, terminal_paste(t, &req, null)); +} + +test "terminal_paste text and unsafe" { + const testing = std.testing; + const S = TerminalPasteCapture; + S.reset(); + + var t: Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new(&lib.alloc.test_allocator, &t, 80, 24)); + defer terminal_c.free(t); + try testing.expectEqual(Result.success, terminal_c.set(t, .write_pty, @ptrCast(&S.writePty))); + + // Plain text, NULL out_written pointer is fine. The text is read + // once, the image never. + var contents: S.Contents = .init(&.{ + .{ "image/png", "\x89PNG" }, + .{ "text/plain", "hel\x1blo" }, + }); + const req = contents.request(); + try testing.expectEqual(Result.success, terminal_paste(t, &req, null)); + try testing.expectEqualStrings("hel lo", S.writtenSlice()); + try testing.expectEqual(@as(usize, 1), S.write_count); + try testing.expectEqual(@as(usize, 0), contents.reads[0]); + try testing.expectEqual(@as(usize, 1), contents.reads[1]); + + // Unsafe is refused with nothing written, then allowed. + S.reset(); + var written: bool = false; + var unsafe_contents: S.Contents = .init(&.{.{ "text/plain", "rm -rf /\n" }}); + var unsafe = unsafe_contents.request(); + try testing.expectEqual(Result.rejected, terminal_paste(t, &unsafe, &written)); + try testing.expectEqual(@as(usize, 0), S.write_count); + try testing.expect(!written); + try testing.expectEqual(@as(usize, 1), unsafe_contents.reads[0]); + + unsafe.allow_unsafe = true; + try testing.expectEqual(Result.success, terminal_paste(t, &unsafe, &written)); + try testing.expect(written); + try testing.expectEqualStrings("rm -rf /\r", S.writtenSlice()); + try testing.expectEqual(@as(usize, 2), unsafe_contents.reads[0]); + + // Bracketed paste mode frames the text through the real mode path. + S.reset(); + const decset = "\x1b[?2004h"; + terminal_c.vt_write(t, decset, decset.len); + try testing.expectEqual(Result.success, terminal_paste(t, &req, &written)); + try testing.expect(written); + try testing.expectEqualStrings("\x1b[200~hel lo\x1b[201~", S.writtenSlice()); + + // No text representation writes nothing and reads nothing. + S.reset(); + var image: S.Contents = .init(&.{.{ "image/png", "\x89PNG" }}); + const image_req = image.request(); + try testing.expectEqual(Result.success, terminal_paste(t, &image_req, &written)); + try testing.expect(!written); + try testing.expectEqual(@as(usize, 0), S.write_count); + try testing.expectEqual(@as(usize, 0), image.reads[0]); + + // A failing reader is an I/O error. + S.reset(); + contents.fail = true; + try testing.expectEqual(Result.io_error, terminal_paste(t, &req, &written)); + try testing.expectEqual(@as(usize, 0), S.write_count); +} + +test "terminal_paste event" { + const testing = std.testing; + const S = TerminalPasteCapture; + S.reset(); + + var t: Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new(&lib.alloc.test_allocator, &t, 80, 24)); + defer terminal_c.free(t); + try testing.expectEqual(Result.success, terminal_c.set(t, .write_pty, @ptrCast(&S.writePty))); + t.?.terminal.modes.set(.kitty_paste_events, true); + + // Without a clipboard_read callback the paste stays text. + var written: bool = false; + var contents: S.Contents = .init(&.{ + .{ "text/plain", "secret" }, + .{ "image/png", "\x89PNG" }, + }); + var req = contents.request(); + req.location = .primary; + try testing.expectEqual(Result.success, terminal_paste(t, &req, &written)); + try testing.expect(written); + try testing.expectEqualStrings("secret", S.writtenSlice()); + + // With one, an event is sent listing every MIME type and no data + // is read, let alone written. + S.reset(); + contents.reads = @splat(0); + try testing.expectEqual(Result.success, terminal_c.set(t, .clipboard_read, @ptrCast(&S.clipboardRead))); + try testing.expectEqual(Result.success, terminal_paste(t, &req, &written)); + try testing.expect(written); + try testing.expectEqual(@as(usize, 1), S.write_count); + try testing.expectEqual(@as(usize, 3), std.mem.count(u8, S.writtenSlice(), "\x1b]5522;")); + try testing.expect(std.mem.startsWith(u8, S.writtenSlice(), "\x1b]5522;type=read:status=OK:loc=primary:pw=")); + try testing.expect(std.mem.indexOf(u8, S.writtenSlice(), "secret") == null); + try testing.expect(std.mem.indexOf(u8, S.writtenSlice(), ";dGV4dC9wbGFpbiBpbWFnZS9wbmcK\x1b\\") != null); + try testing.expectEqual(@as(usize, 0), contents.reads[0]); + try testing.expectEqual(@as(usize, 0), contents.reads[1]); + + // The program's read with the event password is granted once. + const ok_prefix = "\x1b]5522;type=read:status=OK:loc=primary:pw="; + const pw_end = std.mem.indexOfPos(u8, S.writtenSlice(), ok_prefix.len, "\x1b\\").?; + var read_buf: [256]u8 = undefined; + const read = try std.fmt.bufPrint( + &read_buf, + "\x1b]5522;type=read:pw={s}:name=UGFzdGUgZXZlbnQ=;dGV4dC9wbGFpbg==\x1b\\", + .{S.writtenSlice()[ok_prefix.len..pw_end]}, + ); + S.reset(); + terminal_c.vt_write(t, read.ptr, read.len); + try testing.expectEqual(@as(usize, 1), S.read_count); + try testing.expect(S.last_read_granted); + try testing.expect(std.mem.indexOf(u8, S.writtenSlice(), ";R2hvc3R0eQ==\x1b\\") != null); + + S.reset(); + terminal_c.vt_write(t, read.ptr, read.len); + try testing.expectEqual(@as(usize, 1), S.read_count); + try testing.expect(!S.last_read_granted); + + // Text sources never become events. + S.reset(); + var ime = req; + ime.source = .text; + try testing.expectEqual(Result.success, terminal_paste(t, &ime, &written)); + try testing.expect(written); + try testing.expectEqualStrings("secret", S.writtenSlice()); +} diff --git a/vendor/libghostty-vt/src/terminal/c/render.zig b/vendor/libghostty-vt/src/terminal/c/render.zig index 6cf78ec5..c108456f 100644 --- a/vendor/libghostty-vt/src/terminal/c/render.zig +++ b/vendor/libghostty-vt/src/terminal/c/render.zig @@ -12,6 +12,7 @@ const terminal_c = @import("terminal.zig"); const ZigTerminal = @import("../Terminal.zig"); const renderpkg = @import("../render.zig"); const Result = @import("result.zig").Result; +const cell_c = @import("cell.zig"); const row = @import("row.zig"); const style_c = @import("style.zig"); @@ -22,11 +23,18 @@ const RenderStateWrapper = struct { state: renderpkg.RenderState = .empty, }; +/// The "before the first element" position for the iterator wrappers +/// below. Represented as a sentinel index rather than an optional because +/// optional codegens into something that is less efficient than this. +const position_none = std.math.maxInt(usize); + const RowIteratorWrapper = struct { alloc: std.mem.Allocator, - /// The current index (also y value) into the row list. - y: ?size.CellCountInt, + /// The current index (also y value) into the row list, or + /// `position_none` if iteration hasn't started. Always validate + /// against `raws.len` before use. + y: usize, /// These are the raw pointers into the render state data. raws: []const page.Row, @@ -34,6 +42,10 @@ const RowIteratorWrapper = struct { selection: []const ?[2]size.CellCountInt, dirty: []bool, + /// The global dirty state from the render state that populated this + /// iterator. This has the same borrowed lifetime as the row slices. + state_dirty: *const Dirty, + /// The color palette from the render state, needed to resolve /// palette-indexed background colors on cells. palette: *const colorpkg.Palette, @@ -41,7 +53,12 @@ const RowIteratorWrapper = struct { const RowCellsWrapper = struct { alloc: std.mem.Allocator, - x: ?size.CellCountInt, + + /// The current index (also x value) into the cell list, or + /// `position_none` if iteration hasn't started. Always validate + /// against `raws.len` before use. + x: usize, + raws: []const page.Cell, graphemes: []const []const u21, styles: []const Style, @@ -87,6 +104,19 @@ pub const CursorVisualStyle = enum(c_int) { } }; +/// C: GhosttyRenderStateCursor +pub const Cursor = extern struct { + size: usize = @sizeOf(Cursor), + viewport_has_value: bool, + viewport_x: u16, + viewport_y: u16, + wide_tail: bool, + visible: bool, + blinking: bool, + password_input: bool, + visual_style: CursorVisualStyle, +}; + /// C: GhosttyRenderStateData pub const Data = enum(c_int) { invalid = 0, @@ -107,6 +137,8 @@ pub const Data = enum(c_int) { cursor_viewport_x = 15, cursor_viewport_y = 16, cursor_viewport_wide_tail = 17, + cursor = 18, + colors = 19, /// Output type expected for querying the data of the given kind. pub fn OutType(comptime self: Data) type { @@ -122,6 +154,8 @@ pub const Data = enum(c_int) { .cursor_visible, .cursor_blinking, .cursor_password_input => bool, .cursor_viewport_has_value, .cursor_viewport_wide_tail => bool, .cursor_viewport_x, .cursor_viewport_y => size.CellCountInt, + .cursor => Cursor, + .colors => Colors, }; } }; @@ -207,26 +241,21 @@ pub fn end_update( return .success; } +pub fn clean( + state_: RenderState, +) callconv(lib.calling_conv) Result { + const state = state_ orelse return .invalid_value; + state.state.clean(); + return .success; +} + pub fn get( state_: RenderState, data: Data, out: ?*anyopaque, ) callconv(lib.calling_conv) Result { - if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Data, @intFromEnum(data)) catch { - log.warn("render_state_get invalid data value={d}", .{@intFromEnum(data)}); - return .invalid_value; - }; - } - - return switch (data) { - .invalid => .invalid_value, - inline else => |comptime_data| getTyped( - state_, - comptime_data, - @ptrCast(@alignCast(out)), - ), - }; + const state = state_ orelse return .invalid_value; + return getDispatch(state, data, out); } pub fn get_multi( @@ -239,8 +268,16 @@ pub fn get_multi( const k = keys orelse return .invalid_value; const v = values orelse return .invalid_value; + // Unwrap the handle once for the whole batch rather than per key. + // A null handle fails on the first key, matching the per-call + // behavior. + const state: ?*RenderStateWrapper = state_; + for (0..count) |i| { - const result = get(state_, k[i], v[i]); + const result = if (state) |s| + getDispatch(s, k[i], v[i]) + else + Result.invalid_value; if (result != .success) { if (out_written) |w| w.* = i; return result; @@ -250,12 +287,34 @@ pub fn get_multi( return .success; } +inline fn getDispatch( + state: *RenderStateWrapper, + data: Data, + out: ?*anyopaque, +) Result { + if (comptime std.debug.runtime_safety) { + _ = std.enums.fromInt(Data, @intFromEnum(data)) orelse { + log.warn("render_state_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + const out_ptr = out orelse return .invalid_value; + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| getTyped( + state, + comptime_data, + @ptrCast(@alignCast(out_ptr)), + ), + }; +} + fn getTyped( - state_: RenderState, + state: *RenderStateWrapper, comptime data: Data, out: *data.OutType(), ) Result { - const state = state_ orelse return .invalid_value; switch (data) { .invalid => return .invalid_value, .cols => out.* = state.state.cols, @@ -266,11 +325,12 @@ fn getTyped( const row_data = state.state.row_data.slice(); it.* = .{ .alloc = it.alloc, - .y = null, + .y = position_none, .raws = row_data.items(.raw), .cells = row_data.items(.cells), .selection = row_data.items(.selection), .dirty = row_data.items(.dirty), + .state_dirty = &state.state.dirty, .palette = &state.state.colors.palette, }; }, @@ -299,6 +359,8 @@ fn getTyped( const vp = state.state.cursor.viewport orelse return .invalid_value; out.* = vp.wide_tail; }, + .cursor => return writeCursor(state, out), + .colors => return writeColors(state, out), } return .success; @@ -310,7 +372,7 @@ pub fn set( value: ?*const anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(SetOption, @intFromEnum(option)) catch { + _ = std.enums.fromInt(SetOption, @intFromEnum(option)) orelse { log.warn("render_state_set invalid option value={d}", .{@intFromEnum(option)}); return .invalid_value; }; @@ -338,16 +400,91 @@ fn setTyped( return .success; } -pub fn colors_get( - state_: RenderState, - out_colors_: ?*Colors, -) callconv(lib.calling_conv) Result { - const state = state_ orelse return .invalid_value; - const out_colors = out_colors_ orelse return .invalid_value; +fn writeCursor( + state: *RenderStateWrapper, + out_cursor: *Cursor, +) Result { + const out_size = out_cursor.size; + if (out_size < @sizeOf(usize)) return .invalid_value; + + const cursor = &state.state.cursor; + if (lib.structSizedFieldFits( + Cursor, + out_size, + "viewport_has_value", + )) { + out_cursor.viewport_has_value = cursor.viewport != null; + } + + if (cursor.viewport) |viewport| { + if (lib.structSizedFieldFits( + Cursor, + out_size, + "viewport_x", + )) { + out_cursor.viewport_x = viewport.x; + } + + if (lib.structSizedFieldFits( + Cursor, + out_size, + "viewport_y", + )) { + out_cursor.viewport_y = viewport.y; + } + + if (lib.structSizedFieldFits( + Cursor, + out_size, + "wide_tail", + )) { + out_cursor.wide_tail = viewport.wide_tail; + } + } + + if (lib.structSizedFieldFits( + Cursor, + out_size, + "visible", + )) { + out_cursor.visible = cursor.visible; + } + + if (lib.structSizedFieldFits( + Cursor, + out_size, + "blinking", + )) { + out_cursor.blinking = cursor.blinking; + } + + if (lib.structSizedFieldFits( + Cursor, + out_size, + "password_input", + )) { + out_cursor.password_input = cursor.password_input; + } + + if (lib.structSizedFieldFits( + Cursor, + out_size, + "visual_style", + )) { + out_cursor.visual_style = CursorVisualStyle.fromCursorStyle(cursor.visual_style); + } + + return .success; +} + +fn writeColors( + state: *RenderStateWrapper, + out_colors: *Colors, +) Result { const out_size = out_colors.size; if (out_size < @sizeOf(usize)) return .invalid_value; - const colors = state.state.colors; + const colors = &state.state.colors; if (lib.structSizedFieldFits( Colors, out_size, @@ -387,9 +524,10 @@ pub fn colors_get( if (out_size > palette_offset) { const available = out_size - palette_offset; const max_entries = @min(colors.palette.len, available / @sizeOf(colorpkg.RGB.C)); - for (0..max_entries) |i| { - out_colors.palette[i] = colors.palette[i].cval(); - } + colorpkg.paletteCvalSlice( + colors.palette[0..max_entries], + out_colors.palette[0..max_entries], + ); } } @@ -412,6 +550,7 @@ pub fn row_iterator_new( .cells = undefined, .selection = undefined, .dirty = undefined, + .state_dirty = undefined, .palette = undefined, }; result.* = ptr; @@ -426,12 +565,43 @@ pub fn row_iterator_free(iterator_: RowIterator) callconv(lib.calling_conv) void pub fn row_iterator_next(iterator_: RowIterator) callconv(lib.calling_conv) bool { const it = iterator_ orelse return false; - const next_y: size.CellCountInt = if (it.y) |y| y + 1 else 0; + // The none sentinel wraps to zero. + const next_y = it.y +% 1; if (next_y >= it.raws.len) return false; it.y = next_y; return true; } +pub fn row_iterator_next_dirty( + iterator_: RowIterator, + out_y: ?*size.CellCountInt, +) callconv(lib.calling_conv) bool { + const it = iterator_ orelse return false; + const y_out = out_y orelse return false; + + switch (it.state_dirty.*) { + .false => return false, + .full => { + // The none sentinel wraps to zero. + const next_y = it.y +% 1; + if (next_y >= it.raws.len) return false; + it.y = next_y; + y_out.* = @intCast(next_y); + return true; + }, + .partial => { + var next_y = it.y +% 1; + while (next_y < it.raws.len) : (next_y += 1) { + if (!it.dirty[next_y]) continue; + it.y = next_y; + y_out.* = @intCast(next_y); + return true; + } + return false; + }, + } +} + pub fn row_cells_new( alloc_: ?*const CAllocator, result: *RowCells, @@ -456,7 +626,8 @@ pub fn row_cells_new( pub fn row_cells_next(cells_: RowCells) callconv(lib.calling_conv) bool { const cells = cells_ orelse return false; - const next_x: size.CellCountInt = if (cells.x) |x| x + 1 else 0; + // The none sentinel wraps to zero. + const next_x = cells.x +% 1; if (next_x >= cells.raws.len) return false; cells.x = next_x; return true; @@ -508,22 +679,10 @@ pub fn row_cells_get( data: RowCellsData, out: ?*anyopaque, ) callconv(lib.calling_conv) Result { - if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(RowCellsData, @intFromEnum(data)) catch { - log.warn("render_state_row_cells_get invalid data value={d}", .{@intFromEnum(data)}); - return .invalid_value; - }; - } - if (out == null) return .invalid_value; - - return switch (data) { - .invalid => .invalid_value, - inline else => |comptime_data| rowCellsGetTyped( - cells_, - comptime_data, - @ptrCast(@alignCast(out)), - ), - }; + const cells = cells_ orelse return .invalid_value; + const x = cells.x; + if (x >= cells.raws.len) return .invalid_value; + return rowCellsGetDispatch(cells, x, data, out); } pub fn row_cells_get_multi( @@ -536,8 +695,21 @@ pub fn row_cells_get_multi( const k = keys orelse return .invalid_value; const v = values orelse return .invalid_value; + // Unwrap the handle and position once for the whole batch rather + // than per key. An invalid handle/position fails on the first + // key, matching the per-call behavior. + const unwrapped: ?struct { *RowCellsWrapper, usize } = valid: { + const cells = cells_ orelse break :valid null; + const x = cells.x; + if (x >= cells.raws.len) break :valid null; + break :valid .{ cells, x }; + }; + for (0..count) |i| { - const result = row_cells_get(cells_, k[i], v[i]); + const result = if (unwrapped) |u| + rowCellsGetDispatch(u[0], u[1], k[i], v[i]) + else + Result.invalid_value; if (result != .success) { if (out_written) |w| w.* = i; return result; @@ -547,21 +719,46 @@ pub fn row_cells_get_multi( return .success; } -fn rowCellsGetTyped( - cells_: RowCells, +inline fn rowCellsGetDispatch( + cells: *const RowCellsWrapper, + x: usize, + data: RowCellsData, + out: ?*anyopaque, +) Result { + if (comptime std.debug.runtime_safety) { + _ = std.enums.fromInt(RowCellsData, @intFromEnum(data)) orelse { + log.warn("render_state_row_cells_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + if (out == null) return .invalid_value; + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| rowCellsGetTypedInner( + cells, + x, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn rowCellsGetTypedInner( + cells: *const RowCellsWrapper, + x: usize, comptime data: RowCellsData, out: *data.OutType(), ) Result { - const cells = cells_ orelse return .invalid_value; - const x = cells.x orelse return .invalid_value; const cell = cells.raws[x]; switch (data) { .invalid => return .invalid_value, .raw => out.* = cell.cval(), - .style => out.* = if (cell.hasStyling()) - style_c.Style.fromStyle(cells.styles[x]) - else - style_c.Style.fromStyle(.{}), + .style => if (cell.hasStyling()) { + style_c.Style.write(cells.styles[x], out); + } else { + out.* = style_c.Style.default; + }, .graphemes_len => { if (!cell.hasText()) { out.* = 0; @@ -580,15 +777,37 @@ fn rowCellsGetTyped( } }, .bg_color => { - const s: Style = if (cell.hasStyling()) cells.styles[x] else .{}; - const bg = s.bg(&cell, cells.palette) orelse return .invalid_value; - out.* = bg.cval(); + // Avoid copying the full struct when only partial changes happen. + switch (cell.content_tag) { + .bg_color_palette => { + out.* = cells.palette[cell.content.color_palette.data].cval(); + }, + + .bg_color_rgb => { + const rgb = cell.content.color_rgb; + out.* = .{ .r = rgb.r, .g = rgb.g, .b = rgb.b }; + }, + + .codepoint, + .codepoint_grapheme, + => { + // The default style has no background. + if (!cell.hasStyling()) return .invalid_value; + switch (cells.styles[x].bg_color) { + .none => return .invalid_value, + .palette => |idx| out.* = cells.palette[idx].cval(), + .rgb => |rgb| out.* = rgb.cval(), + } + }, + } }, .fg_color => { - const s: Style = if (cell.hasStyling()) cells.styles[x] else .{}; - if (s.fg_color == .none) return .invalid_value; - const fg = s.fg(.{ .default = .{}, .palette = cells.palette }); - out.* = fg.cval(); + if (!cell.hasStyling()) return .invalid_value; + switch (cells.styles[x].fg_color) { + .none => return .invalid_value, + .palette => |idx| out.* = cells.palette[idx].cval(), + .rgb => |rgb| out.* = rgb.cval(), + } }, .selected => out.* = if (cells.selection) |sel| x >= sel[0] and x <= sel[1] @@ -606,11 +825,32 @@ fn rowCellsGetGraphemesUtf8( extra: []const u21, out: *lib.Buffer, ) Result { - out.len = 0; + if (!cell.hasText()) { + out.len = 0; + return .success; + } + + const first = cell.codepoint(); + + // Fast path: a single ASCII codepoint written to an adequately + // sized buffer. This is the overwhelmingly common case for + // terminal content. + if (first < 0x80 and extra.len == 0) { + @branchHint(.likely); + if (out.ptr) |ptr| { + if (out.cap >= 1) { + ptr[0] = @intCast(first); + out.len = 1; + return .success; + } + } + out.len = 1; + return .out_of_space; + } - if (!cell.hasText()) return .success; + out.len = 0; - var needed: usize = std.unicode.utf8CodepointSequenceLength(cell.codepoint()) catch + var needed: usize = std.unicode.utf8CodepointSequenceLength(first) catch return .invalid_value; for (extra) |cp| { needed += std.unicode.utf8CodepointSequenceLength(cp) catch @@ -622,7 +862,7 @@ fn rowCellsGetGraphemesUtf8( const buf = out.ptr.?[0..out.cap]; var i: usize = 0; - i += std.unicode.utf8Encode(cell.codepoint(), buf[i..]) catch + i += std.unicode.utf8Encode(first, buf[i..]) catch return .invalid_value; for (extra) |cp| { i += std.unicode.utf8Encode(cp, buf[i..]) catch @@ -640,6 +880,7 @@ pub const RowData = enum(c_int) { raw = 2, cells = 3, selection = 4, + cells_raw = 5, /// Output type expected for querying the data of the given kind. pub fn OutType(comptime self: RowData) type { @@ -649,6 +890,7 @@ pub const RowData = enum(c_int) { .raw => row.CRow, .cells => RowCells, .selection => RowSelection, + .cells_raw => cell_c.CellsView, }; } }; @@ -670,21 +912,10 @@ pub fn row_get( data: RowData, out: ?*anyopaque, ) callconv(lib.calling_conv) Result { - if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(RowData, @intFromEnum(data)) catch { - log.warn("render_state_row_get invalid data value={d}", .{@intFromEnum(data)}); - return .invalid_value; - }; - } - - return switch (data) { - .invalid => .invalid_value, - inline else => |comptime_data| rowGetTyped( - iterator_, - comptime_data, - @ptrCast(@alignCast(out)), - ), - }; + const it = iterator_ orelse return .invalid_value; + const y = it.y; + if (y >= it.raws.len) return .invalid_value; + return rowGetDispatch(it, y, data, out); } pub fn row_get_multi( @@ -697,8 +928,21 @@ pub fn row_get_multi( const k = keys orelse return .invalid_value; const v = values orelse return .invalid_value; + // Unwrap the handle and position once for the whole batch rather + // than per key. An invalid handle/position fails on the first + // key, matching the per-call behavior. + const unwrapped: ?struct { *RowIteratorWrapper, usize } = valid: { + const it = iterator_ orelse break :valid null; + const y = it.y; + if (y >= it.raws.len) break :valid null; + break :valid .{ it, y }; + }; + for (0..count) |i| { - const result = row_get(iterator_, k[i], v[i]); + const result = if (unwrapped) |u| + rowGetDispatch(u[0], u[1], k[i], v[i]) + else + Result.invalid_value; if (result != .success) { if (out_written) |w| w.* = i; return result; @@ -708,13 +952,36 @@ pub fn row_get_multi( return .success; } +inline fn rowGetDispatch( + it: *RowIteratorWrapper, + y: usize, + data: RowData, + out: ?*anyopaque, +) Result { + if (comptime std.debug.runtime_safety) { + _ = std.enums.fromInt(RowData, @intFromEnum(data)) orelse { + log.warn("render_state_row_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| rowGetTyped( + it, + y, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + fn rowGetTyped( - iterator_: RowIterator, + it: *RowIteratorWrapper, + y: usize, comptime data: RowData, out: *data.OutType(), ) Result { - const it = iterator_ orelse return .invalid_value; - const y = it.y orelse return .invalid_value; switch (data) { .invalid => return .invalid_value, .dirty => out.* = it.dirty[y], @@ -724,7 +991,7 @@ fn rowGetTyped( const cell_data = it.cells[y].slice(); cells.* = .{ .alloc = cells.alloc, - .x = null, + .x = position_none, .raws = cell_data.items(.raw), .graphemes = cell_data.items(.grapheme), .styles = cell_data.items(.style), @@ -740,6 +1007,13 @@ fn rowGetTyped( out.start_x = sel[0]; out.end_x = sel[1]; }, + .cells_raw => { + const raws: []const page.Cell = it.cells[y].items(.raw); + out.* = .{ + .ptr = @ptrCast(raws.ptr), + .len = raws.len, + }; + }, } return .success; @@ -751,7 +1025,7 @@ pub fn row_set( value: ?*const anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(RowOption, @intFromEnum(option)) catch { + _ = std.enums.fromInt(RowOption, @intFromEnum(option)) orelse { log.warn("render_state_row_set invalid option value={d}", .{@intFromEnum(option)}); return .invalid_value; }; @@ -772,7 +1046,8 @@ fn rowSetTyped( value: *const option.InType(), ) Result { const it = iterator_ orelse return .invalid_value; - const y = it.y orelse return .invalid_value; + const y = it.y; + if (y >= it.raws.len) return .invalid_value; switch (option) { .dirty => it.dirty[y] = value.*, } @@ -827,11 +1102,8 @@ test "render: begin/end update" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 10, - .rows = 3, - .max_scrollback = 10_000, - }, + 10, + 3, )); defer terminal_c.free(terminal); @@ -864,6 +1136,14 @@ test "render: begin/end update" { test "render: get invalid value" { var cols: size.CellCountInt = 0; try testing.expectEqual(Result.invalid_value, get(null, .cols, @ptrCast(&cols))); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + try testing.expectEqual(Result.invalid_value, get(state, .cols, null)); } test "render: get invalid data" { @@ -877,7 +1157,7 @@ test "render: get invalid data" { try testing.expectEqual(Result.invalid_value, get(state, .invalid, null)); } -test "render: colors get invalid value" { +test "render: aggregate get invalid value" { var state: RenderState = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, @@ -888,11 +1168,20 @@ test "render: colors get invalid value" { var colors: Colors = std.mem.zeroes(Colors); colors.size = @sizeOf(Colors); - try testing.expectEqual(Result.invalid_value, colors_get(null, &colors)); - try testing.expectEqual(Result.invalid_value, colors_get(state, null)); + try testing.expectEqual(Result.invalid_value, get(null, .colors, &colors)); + try testing.expectEqual(Result.invalid_value, get(state, .colors, null)); colors.size = @sizeOf(usize) - 1; - try testing.expectEqual(Result.invalid_value, colors_get(state, &colors)); + try testing.expectEqual(Result.invalid_value, get(state, .colors, &colors)); + + var cursor: Cursor = std.mem.zeroes(Cursor); + cursor.size = @sizeOf(Cursor); + + try testing.expectEqual(Result.invalid_value, get(null, .cursor, &cursor)); + try testing.expectEqual(Result.invalid_value, get(state, .cursor, null)); + + cursor.size = @sizeOf(usize) - 1; + try testing.expectEqual(Result.invalid_value, get(state, .cursor, &cursor)); } test "render: get/set dirty invalid value" { @@ -925,6 +1214,42 @@ test "render: get/set dirty" { try testing.expectEqual(Dirty.full, dirty); } +test "render: clean" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 3, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.invalid_value, clean(null)); + try testing.expectEqual(Result.success, update(state, terminal)); + try testing.expectEqual(Dirty.full, state.?.state.dirty); + + try testing.expectEqual(Result.success, clean(state)); + try testing.expectEqual(Dirty.false, state.?.state.dirty); + for (state.?.state.row_data.items(.dirty)) |dirty| { + try testing.expect(!dirty); + } + + // Cleaning is idempotent, and an unchanged update remains clean. + try testing.expectEqual(Result.success, clean(state)); + try testing.expectEqual(Result.success, update(state, terminal)); + try testing.expectEqual(Dirty.false, state.?.state.dirty); + for (state.?.state.row_data.items(.dirty)) |dirty| { + try testing.expect(!dirty); + } +} + test "render: set null value" { var state: RenderState = null; try testing.expectEqual(Result.success, new( @@ -952,11 +1277,8 @@ test "render: row iterator new/free" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -983,7 +1305,7 @@ test "render: row iterator new/free" { const iterator_ptr = iterator.?; const row_data = state.?.state.row_data.slice(); - try testing.expectEqual(@as(?size.CellCountInt, null), iterator_ptr.y); + try testing.expectEqual(position_none, iterator_ptr.y); try testing.expectEqual(row_data.items(.raw).len, iterator_ptr.raws.len); try testing.expectEqual(row_data.items(.cells).len, iterator_ptr.cells.len); try testing.expectEqual(row_data.items(.selection).len, iterator_ptr.selection.len); @@ -1008,11 +1330,8 @@ test "render: row get invalid data" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1047,11 +1366,8 @@ test "render: row set before iteration" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1081,11 +1397,8 @@ test "render: row get before iteration" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1115,11 +1428,8 @@ test "render: row get/set dirty" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1173,11 +1483,8 @@ test "render: row get selection" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 10, - .rows = 3, - .max_scrollback = 10_000, - }, + 10, + 3, )); defer terminal_c.free(terminal); @@ -1222,16 +1529,75 @@ test "render: row get selection" { try testing.expectEqual(Result.no_value, row_get(it, .selection, @ptrCast(&sel))); } +test "render: row get cells_raw" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 3, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "AB", 2); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + + // Not positioned on a row yet. + var view: cell_c.CellsView = undefined; + try testing.expectEqual(Result.invalid_value, row_get(it, .cells_raw, @ptrCast(&view))); + + try testing.expect(row_iterator_next(it)); + try testing.expectEqual(Result.success, row_get(it, .cells_raw, @ptrCast(&view))); + try testing.expectEqual(@as(usize, 10), view.len); + + // The view must match the per-cell raw reads. + var cells: RowCells = null; + try testing.expectEqual(Result.success, row_cells_new( + &lib.alloc.test_allocator, + &cells, + )); + defer row_cells_free(cells); + try testing.expectEqual(Result.success, row_get(it, .cells, @ptrCast(&cells))); + const ptr = view.ptr.?; + var x: u16 = 0; + while (x < view.len) : (x += 1) { + var raw: page.Cell.C = undefined; + try testing.expectEqual(Result.success, row_cells_select(cells, x)); + try testing.expectEqual(Result.success, row_cells_get(cells, .raw, @ptrCast(&raw))); + try testing.expectEqual(raw, ptr[x]); + } + + // Contents sanity: first two cells hold our text. + const first: page.Cell = @bitCast(ptr[0]); + const second: page.Cell = @bitCast(ptr[1]); + try testing.expectEqual(@as(u21, 'A'), first.codepoint()); + try testing.expectEqual(@as(u21, 'B'), second.codepoint()); +} + test "render: row cells get selected" { var terminal: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 10, - .rows = 3, - .max_scrollback = 10_000, - }, + 10, + 3, )); defer terminal_c.free(terminal); @@ -1310,11 +1676,8 @@ test "render: row cells get has_styling" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 10, - .rows = 3, - .max_scrollback = 10_000, - }, + 10, + 3, )); defer terminal_c.free(terminal); @@ -1390,7 +1753,8 @@ test "render: row cells get graphemes utf8" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 10, .rows = 3, .max_scrollback = 10_000 }, + 10, + 3, )); defer terminal_c.free(terminal); @@ -1447,7 +1811,8 @@ test "render: row cells get graphemes utf8" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 10, .rows = 3, .max_scrollback = 10_000 }, + 10, + 3, )); defer terminal_c.free(terminal); @@ -1493,11 +1858,8 @@ test "render: row iterator next" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1526,16 +1888,89 @@ test "render: row iterator next" { } try testing.expect(row_iterator_next(iterator)); - try testing.expectEqual(@as(?size.CellCountInt, 0), iterator.?.y); + try testing.expectEqual(@as(usize, 0), iterator.?.y); var i: size.CellCountInt = 1; while (i < rows) : (i += 1) { try testing.expect(row_iterator_next(iterator)); - try testing.expectEqual(@as(?size.CellCountInt, i), iterator.?.y); + try testing.expectEqual(i, iterator.?.y); } try testing.expect(!row_iterator_next(iterator)); - try testing.expectEqual(@as(?size.CellCountInt, rows - 1), iterator.?.y); + try testing.expectEqual(@as(usize, rows - 1), iterator.?.y); +} + +test "render: row iterator next dirty" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + try testing.expectEqual(Result.success, update(state, terminal)); + + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + // Invalid arguments neither write the output nor advance the iterator. + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + var out_y: size.CellCountInt = 0xCAFE; + try testing.expect(!row_iterator_next_dirty(null, &out_y)); + try testing.expectEqual(@as(size.CellCountInt, 0xCAFE), out_y); + try testing.expect(!row_iterator_next_dirty(iterator, null)); + try testing.expectEqual(position_none, iterator.?.y); + + // A full redraw returns every row, even if its row flag was cleared. + @memset(state.?.state.row_data.items(.dirty), false); + var expected_y: size.CellCountInt = 0; + while (row_iterator_next_dirty(iterator, &out_y)) : (expected_y += 1) { + try testing.expectEqual(expected_y, out_y); + } + try testing.expectEqual(@as(size.CellCountInt, 4), expected_y); + try testing.expectEqual(@as(size.CellCountInt, 3), out_y); + + // A partial redraw skips clean rows without consuming dirty flags. + const dirty = state.?.state.row_data.items(.dirty); + state.?.state.dirty = .partial; + @memset(dirty, false); + dirty[1] = true; + dirty[3] = true; + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + try testing.expect(row_iterator_next_dirty(iterator, &out_y)); + try testing.expectEqual(@as(size.CellCountInt, 1), out_y); + try testing.expect(row_iterator_next_dirty(iterator, &out_y)); + try testing.expectEqual(@as(size.CellCountInt, 3), out_y); + try testing.expect(!row_iterator_next_dirty(iterator, &out_y)); + try testing.expectEqual(@as(size.CellCountInt, 3), out_y); + try testing.expect(dirty[1]); + try testing.expect(dirty[3]); + + // The global clean state is authoritative, even if stale row flags exist. + state.?.state.dirty = .false; + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + out_y = 0xCAFE; + try testing.expect(!row_iterator_next_dirty(iterator, &out_y)); + try testing.expectEqual(@as(size.CellCountInt, 0xCAFE), out_y); + + // Existing iterators observe cleaning through their borrowed state. + state.?.state.dirty = .partial; + dirty[1] = true; + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + try testing.expectEqual(Result.success, clean(state)); + try testing.expect(!row_iterator_next_dirty(iterator, &out_y)); } test "render: update" { @@ -1543,11 +1978,8 @@ test "render: update" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1571,16 +2003,13 @@ test "render: update" { try testing.expectEqual(@as(size.CellCountInt, 24), rows_val); } -test "render: colors get" { +test "render: colors data get" { var terminal: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1595,7 +2024,7 @@ test "render: colors get" { var colors: Colors = std.mem.zeroes(Colors); colors.size = @sizeOf(Colors); - try testing.expectEqual(Result.success, colors_get(state, &colors)); + try testing.expectEqual(Result.success, get(state, .colors, &colors)); const state_colors = &state.?.state.colors; try testing.expectEqual(state_colors.background.cval(), colors.background); @@ -1613,16 +2042,128 @@ test "render: colors get" { } } +test "render: cursor data get matches scalar getters" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 80, + 24, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var cursor: Cursor = std.mem.zeroes(Cursor); + cursor.size = @sizeOf(Cursor); + try testing.expectEqual(Result.success, get(state, .cursor, &cursor)); + + var viewport_has_value: bool = undefined; + var viewport_x: u16 = undefined; + var viewport_y: u16 = undefined; + var wide_tail: bool = undefined; + var visible: bool = undefined; + var blinking: bool = undefined; + var password_input: bool = undefined; + var visual_style: CursorVisualStyle = undefined; + try testing.expectEqual(Result.success, get(state, .cursor_viewport_has_value, &viewport_has_value)); + try testing.expectEqual(Result.success, get(state, .cursor_viewport_x, &viewport_x)); + try testing.expectEqual(Result.success, get(state, .cursor_viewport_y, &viewport_y)); + try testing.expectEqual(Result.success, get(state, .cursor_viewport_wide_tail, &wide_tail)); + try testing.expectEqual(Result.success, get(state, .cursor_visible, &visible)); + try testing.expectEqual(Result.success, get(state, .cursor_blinking, &blinking)); + try testing.expectEqual(Result.success, get(state, .cursor_password_input, &password_input)); + try testing.expectEqual(Result.success, get(state, .cursor_visual_style, &visual_style)); + + try testing.expectEqual(viewport_has_value, cursor.viewport_has_value); + try testing.expectEqual(viewport_x, cursor.viewport_x); + try testing.expectEqual(viewport_y, cursor.viewport_y); + try testing.expectEqual(wide_tail, cursor.wide_tail); + try testing.expectEqual(visible, cursor.visible); + try testing.expectEqual(blinking, cursor.blinking); + try testing.expectEqual(password_input, cursor.password_input); + try testing.expectEqual(visual_style, cursor.visual_style); +} + +test "render: cursor data get without viewport" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + state.?.state.cursor.viewport = null; + state.?.state.cursor.visible = true; + state.?.state.cursor.blinking = true; + state.?.state.cursor.password_input = true; + state.?.state.cursor.visual_style = .underline; + + var cursor: Cursor = std.mem.zeroes(Cursor); + cursor.size = @sizeOf(Cursor); + cursor.viewport_x = 0xAAAA; + cursor.viewport_y = 0xBBBB; + cursor.wide_tail = true; + try testing.expectEqual(Result.success, get(state, .cursor, &cursor)); + + try testing.expect(!cursor.viewport_has_value); + try testing.expectEqual(@as(u16, 0xAAAA), cursor.viewport_x); + try testing.expectEqual(@as(u16, 0xBBBB), cursor.viewport_y); + try testing.expect(cursor.wide_tail); + try testing.expect(cursor.visible); + try testing.expect(cursor.blinking); + try testing.expect(cursor.password_input); + try testing.expectEqual(CursorVisualStyle.underline, cursor.visual_style); +} + +test "render: cursor data get supports truncated sized struct" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 80, + 24, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + const expected = state.?.state.cursor; + const viewport = expected.viewport.?; + + var cursor: Cursor = std.mem.zeroes(Cursor); + cursor.size = @offsetOf(Cursor, "viewport_y") + @sizeOf(u16); + cursor.wide_tail = !viewport.wide_tail; + cursor.visible = !expected.visible; + try testing.expectEqual(Result.success, get(state, .cursor, &cursor)); + + try testing.expect(cursor.viewport_has_value); + try testing.expectEqual(viewport.x, cursor.viewport_x); + try testing.expectEqual(viewport.y, cursor.viewport_y); + try testing.expectEqual(!viewport.wide_tail, cursor.wide_tail); + try testing.expectEqual(!expected.visible, cursor.visible); +} + test "render: row cells bg_color no background" { var terminal: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1668,11 +2209,8 @@ test "render: row cells bg_color from style" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1720,11 +2258,8 @@ test "render: row cells bg_color from content tag" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1774,11 +2309,8 @@ test "render: row cells fg_color no foreground" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1824,11 +2356,8 @@ test "render: row cells fg_color from style" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1871,16 +2400,13 @@ test "render: row cells fg_color from style" { try testing.expectEqual(@as(u8, 30), fg.b); } -test "render: colors get supports truncated sized struct" { +test "render: colors data get supports truncated sized struct" { var terminal: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1898,7 +2424,7 @@ test "render: colors get supports truncated sized struct" { for (&colors.palette) |*entry| entry.* = sentinel; colors.size = @offsetOf(Colors, "palette") + @sizeOf(colorpkg.RGB.C) * 2; - try testing.expectEqual(Result.success, colors_get(state, &colors)); + try testing.expectEqual(Result.success, get(state, .colors, &colors)); const state_colors = &state.?.state.colors; try testing.expectEqual(state_colors.palette[0].cval(), colors.palette[0]); @@ -1911,7 +2437,8 @@ test "render: get_multi success" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1947,7 +2474,8 @@ test "render: row_get_multi success" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(terminal); @@ -1990,7 +2518,8 @@ test "render: row_cells_get_multi success" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(terminal); diff --git a/vendor/libghostty-vt/src/terminal/c/result.zig b/vendor/libghostty-vt/src/terminal/c/result.zig index 32866328..174e973b 100644 --- a/vendor/libghostty-vt/src/terminal/c/result.zig +++ b/vendor/libghostty-vt/src/terminal/c/result.zig @@ -5,4 +5,7 @@ pub const Result = enum(c_int) { invalid_value = -2, out_of_space = -3, no_value = -4, + io_error = -5, + limit_exceeded = -6, + rejected = -7, }; diff --git a/vendor/libghostty-vt/src/terminal/c/row.zig b/vendor/libghostty-vt/src/terminal/c/row.zig index 66c398c8..136d6835 100644 --- a/vendor/libghostty-vt/src/terminal/c/row.zig +++ b/vendor/libghostty-vt/src/terminal/c/row.zig @@ -68,7 +68,7 @@ pub fn get( out: ?*anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(RowData, @intFromEnum(data)) catch { + _ = std.enums.fromInt(RowData, @intFromEnum(data)) orelse { return .invalid_value; }; } diff --git a/vendor/libghostty-vt/src/terminal/c/search.zig b/vendor/libghostty-vt/src/terminal/c/search.zig new file mode 100644 index 00000000..c5137891 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/search.zig @@ -0,0 +1,1009 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const searchpkg = @import("../search.zig"); +const TerminalSearch = searchpkg.Terminal; +const FlattenedHighlight = @import("../highlight.zig").Flattened; +const selection_c = @import("selection.zig"); +const terminal_c = @import("terminal.zig"); +const Result = @import("result.zig").Result; + +const log = std.log.scoped(.search_c); + +/// C: GhosttySearch +pub const Search = ?*SearchWrapper; + +pub const SearchWrapper = struct { + alloc: std.mem.Allocator, + + /// The terminal this search is bound to. This is borrowed, so the + /// search never frees it. If the terminal is freed first, it sets + /// this to null to detach the search: calls that need the terminal + /// then fail cleanly and free releases only search-owned memory. + terminal: terminal_c.Terminal, + + /// The search state. Null when no needle is set: the search + /// starts idle and returns to idle when the needle is cleared. + search: ?TerminalSearch = null, + + /// The scroll policy applied by the select options. Persistent + /// across selects, set via the select_scroll option. + select_scroll: TerminalSearch.SelectScroll = .if_needed, + + /// The Zig terminal this search is bound to, or null if the + /// terminal was freed before the search. + fn zigTerminal(self: *const SearchWrapper) ?*terminal_c.ZigTerminal { + const terminal_wrapper = self.terminal orelse return null; + return terminal_wrapper.terminal; + } + + /// The status of the search. A search with no needle reports + /// complete since there is nothing to look for. + fn status(self: *SearchWrapper) Status { + const s = if (self.search) |*s| s else return .complete; + return .fromZig(s.status()); + } +}; + +/// C: GhosttySearchStatus +pub const Status = enum(c_int) { + running = 0, + feed_required = 1, + complete = 2, + + fn fromZig(status: TerminalSearch.Status) Status { + return switch (status) { + .running => .running, + .feed_required => .feed_required, + .complete => .complete, + }; + } +}; + +/// C: GhosttySearchScroll +pub const Scroll = enum(c_int) { + if_needed = 0, + none = 1, + + fn toZig(self: Scroll) TerminalSearch.SelectScroll { + return switch (self) { + .if_needed => .if_needed, + .none => .none, + }; + } + + fn fromZig(scroll: TerminalSearch.SelectScroll) Scroll { + return switch (scroll) { + .if_needed => .if_needed, + .none => .none, + }; + } +}; + +/// C: GhosttySearchData +pub const Data = enum(c_int) { + status = 0, + needle = 1, + total_matches = 2, + selected_index = 3, + selected_match = 4, + matches = 5, + viewport_matches = 6, + select_scroll = 7, + + pub fn OutType(comptime self: Data) type { + return switch (self) { + .status => Status, + .needle => lib.String, + .total_matches => usize, + .selected_index => usize, + .selected_match => selection_c.CSelection, + .matches, .viewport_matches => selection_c.CSelectionBuffer, + .select_scroll => Scroll, + }; + } +}; + +/// C: GhosttySearchOption +pub const Option = enum(c_int) { + needle = 0, + select_next = 1, + select_prev = 2, + select_scroll = 3, + + pub fn Type(comptime self: Option) type { + return switch (self) { + .needle => lib.String, + // The value must be NULL. Reserved for future use. + .select_next, .select_prev => void, + .select_scroll => Scroll, + }; + } +}; + +pub fn new( + alloc_: ?*const CAllocator, + out_search: ?*Search, + terminal: terminal_c.Terminal, +) callconv(lib.calling_conv) Result { + const out = out_search orelse return .invalid_value; + out.* = null; + + const terminal_wrapper = terminal orelse return .invalid_value; + const alloc = lib.alloc.default(alloc_); + const wrapper = alloc.create(SearchWrapper) catch return .out_of_memory; + wrapper.* = .{ + .alloc = alloc, + .terminal = terminal_wrapper, + }; + + // Store the search in the terminal so that when the terminal is + // freed the search can be detached safely. + terminal_wrapper.searches.putNoClobber( + terminal_wrapper.terminal.gpa(), + wrapper, + {}, + ) catch { + alloc.destroy(wrapper); + return .out_of_memory; + }; + + out.* = wrapper; + return .success; +} + +pub fn free(search_: Search) callconv(lib.calling_conv) void { + const wrapper = search_ orelse return; + if (wrapper.terminal) |terminal_wrapper| { + _ = terminal_wrapper.searches.swapRemove(wrapper); + if (wrapper.search) |*s| s.deinit(terminal_wrapper.terminal); + } else { + // The terminal was freed first. Tracked state died with it, + // so only search-owned memory is freed. + if (wrapper.search) |*s| s.deinit(null); + } + const alloc = wrapper.alloc; + alloc.destroy(wrapper); +} + +pub fn tick( + search_: Search, + out_status: ?*Status, +) callconv(lib.calling_conv) Result { + const wrapper = search_ orelse return .invalid_value; + if (wrapper.search) |*s| _ = s.tick(); + if (out_status) |out| out.* = wrapper.status(); + return .success; +} + +pub fn feed(search_: Search) callconv(lib.calling_conv) Result { + const wrapper = search_ orelse return .invalid_value; + const t = wrapper.zigTerminal() orelse return .invalid_value; + const s = if (wrapper.search) |*s| s else return .success; + + // The C API has no renderer cooperation to know whether the active + // area changed, so it is always re-scanned. This is correct without + // any dirty tracking and cheap because the active area search was + // built for exactly this. + s.feed(t, true); + return .success; +} + +pub fn run(search_: Search) callconv(lib.calling_conv) Result { + const wrapper = search_ orelse return .invalid_value; + const t = wrapper.zigTerminal() orelse return .invalid_value; + const s = if (wrapper.search) |*s| s else return .success; + + // Always start with a feed: complete only means caught up as of + // the last feed, so run doubles as the "terminal changed, catch + // up" convenience for one-shot embedders. + s.feed(t, true); + while (true) { + switch (s.status()) { + .complete => return .success, + .feed_required => s.feed(t, true), + .running => _ = s.tick(), + } + } +} + +pub fn set( + search_: Search, + option: Option, + value: ?*const anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.enums.fromInt(Option, @intFromEnum(option)) orelse { + log.warn("search_set invalid option value={d}", .{@intFromEnum(option)}); + return .invalid_value; + }; + } + + return switch (option) { + inline else => |comptime_option| setTyped( + search_, + comptime_option, + if (value) |ptr| @ptrCast(@alignCast(ptr)) else null, + ), + }; +} + +fn setTyped( + search_: Search, + comptime option: Option, + value: ?*const option.Type(), +) Result { + const wrapper = search_ orelse return .invalid_value; + switch (option) { + .needle => { + // The needle touches the terminal (replacing or clearing + // an active search releases tracked pins through it), so + // it requires the terminal to still be alive. + const t = wrapper.zigTerminal() orelse return .invalid_value; + + // NULL and empty both clear the needle, returning the + // search to idle. This matches the internal engine, where + // an empty needle stops the search. + const v = value orelse return clearNeedle(wrapper, t); + if (v.len == 0) return clearNeedle(wrapper, t); + if (@intFromPtr(v.ptr) == 0) return .invalid_value; + const bytes = v.ptr[0..v.len]; + + // Setting the current needle again keeps existing results, + // using the same ASCII case-insensitive comparison as + // matching. This is what a find bar wants on resubmit. + if (wrapper.search) |*s| { + if (std.ascii.eqlIgnoreCase(s.needle(), bytes)) { + return .success; + } + } + + // Create the replacement before dropping the current + // search so an allocation failure keeps existing state. + const replacement = TerminalSearch.init( + wrapper.alloc, + bytes, + ) catch return .out_of_memory; + if (wrapper.search) |*s| s.deinit(t); + wrapper.search = replacement; + }, + + .select_next, .select_prev => { + // The value is reserved for future use and must be NULL. + if (value != null) return .invalid_value; + + const t = wrapper.zigTerminal() orelse return .invalid_value; + const s = if (wrapper.search) |*s| s else return .no_value; + const selected = s.select( + t, + switch (option) { + .select_next => .next, + .select_prev => .prev, + else => comptime unreachable, + }, + wrapper.select_scroll, + ) catch return .out_of_memory; + if (!selected) return .no_value; + }, + + .select_scroll => { + const v = value orelse { + wrapper.select_scroll = .if_needed; + return .success; + }; + const scroll = std.enums.fromInt(Scroll, @intFromEnum(v.*)) orelse + return .invalid_value; + wrapper.select_scroll = scroll.toZig(); + }, + } + + return .success; +} + +fn clearNeedle(wrapper: *SearchWrapper, t: *terminal_c.ZigTerminal) Result { + if (wrapper.search) |*s| { + s.deinit(t); + wrapper.search = null; + } + return .success; +} + +pub fn get( + search_: Search, + data: Data, + value: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.enums.fromInt(Data, @intFromEnum(data)) orelse { + log.warn("search_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + const out_ptr = value orelse return .invalid_value; + return switch (data) { + inline else => |comptime_data| getTyped( + search_, + comptime_data, + @ptrCast(@alignCast(out_ptr)), + ), + }; +} + +pub fn get_multi( + search_: Search, + count: usize, + keys: ?[*]const Data, + values: ?[*]?*anyopaque, + out_written: ?*usize, +) callconv(lib.calling_conv) Result { + const k = keys orelse return .invalid_value; + const v = values orelse return .invalid_value; + + for (0..count) |i| { + const result = get(search_, k[i], v[i]); + if (result != .success) { + if (out_written) |w| w.* = i; + return result; + } + } + if (out_written) |w| w.* = count; + return .success; +} + +fn getTyped( + search_: Search, + comptime data: Data, + out: *data.OutType(), +) Result { + const wrapper = search_ orelse return .invalid_value; + + switch (data) { + .status => out.* = wrapper.status(), + + .needle => { + const s = if (wrapper.search) |*s| s else return .no_value; + out.* = .init(s.needle()); + }, + + .total_matches => out.* = total: { + const s = if (wrapper.search) |*s| s else break :total 0; + const ss = s.activeScreenSearch() orelse break :total 0; + break :total ss.matchesLen(); + }, + + .selected_index => { + const s = if (wrapper.search) |*s| s else return .no_value; + const ss = s.activeScreenSearch() orelse return .no_value; + const selected = ss.selected orelse return .no_value; + out.* = selected.idx; + }, + + .selected_match => { + const s = if (wrapper.search) |*s| s else return .no_value; + const ss = s.activeScreenSearch() orelse return .no_value; + const hl = ss.selectedMatch() orelse return .no_value; + out.* = selectionFromHighlight(hl); + }, + + .matches => { + const ss = if (wrapper.search) |*s| + s.activeScreenSearch() + else + null; + const total = if (ss) |v| v.matchesLen() else 0; + if (out.cap < total) { + out.len = total; + return .out_of_space; + } + if (total > 0) { + const dst = (out.ptr orelse return .invalid_value)[0..total]; + for (dst, 0..) |*d, i| { + d.* = selectionFromHighlight(ss.?.matchAt(i).?); + } + } + out.len = total; + }, + + .viewport_matches => { + const matches: []const FlattenedHighlight = if (wrapper.search) |*s| + s.viewportMatches() catch return .out_of_memory + else + &.{}; + if (out.cap < matches.len) { + out.len = matches.len; + return .out_of_space; + } + if (matches.len > 0) { + const dst = (out.ptr orelse return .invalid_value)[0..matches.len]; + for (dst, matches) |*d, hl| d.* = selectionFromHighlight(hl); + } + out.len = matches.len; + }, + + .select_scroll => out.* = .fromZig(wrapper.select_scroll), + } + + return .success; +} + +fn selectionFromHighlight(hl: FlattenedHighlight) selection_c.CSelection { + const untracked = hl.untracked(); + return .{ + .start = .fromPin(untracked.start), + .end = .fromPin(untracked.end), + .rectangle = false, + }; +} + +fn testString(str: []const u8) lib.String { + return .init(str); +} + +fn testNewSearch(terminal: terminal_c.Terminal, needle_str: []const u8) !Search { + var search: Search = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &search, + terminal, + )); + errdefer free(search); + const needle_value = testString(needle_str); + try testing.expectEqual(Result.success, set(search, .needle, &needle_value)); + return search; +} + +test "search lifecycle and run to complete" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz\r\nBuzz\r\nFizz\r\nBang", 22); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + // Right after the needle is set the search must report + // feed_required, not complete. The internal completion check is + // trivially true before the search has seen the terminal. + var status: Status = .complete; + try testing.expectEqual(Result.success, get(search, .status, &status)); + try testing.expectEqual(Status.feed_required, status); + + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, get(search, .status, &status)); + try testing.expectEqual(Status.complete, status); + + var total: usize = 0; + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 2), total); + + // The needle is borrowed and matches what we searched for. + var needle: lib.String = undefined; + try testing.expectEqual(Result.success, get(search, .needle, &needle)); + try testing.expectEqualStrings("Fizz", needle.ptr[0..needle.len]); +} + +test "search tick reports feed required before first feed" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + var status: Status = .complete; + try testing.expectEqual(Result.success, tick(search, &status)); + try testing.expectEqual(Status.feed_required, status); + + // NULL status out is allowed. + try testing.expectEqual(Result.success, tick(search, null)); +} + +test "search feed after write updates results" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz", 4); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + try testing.expectEqual(Result.success, run(search)); + var total: usize = 0; + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 1), total); + + // Write another match: the caller-driven feed is the "terminal + // changed" signal. + terminal_c.vt_write(terminal, "\r\nFizz", 6); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 2), total); +} + +test "search alt screen flip and return retains results" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz\r\nFizz", 10); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + try testing.expectEqual(Result.success, run(search)); + var total: usize = 0; + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 2), total); + + // Flip to the alternate screen: reads now reflect that screen. + terminal_c.vt_write(terminal, "\x1b[?1049h", 8); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 0), total); + + terminal_c.vt_write(terminal, "Fizz", 4); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 1), total); + + // Return to the primary screen: results are retained and restored. + terminal_c.vt_write(terminal, "\x1b[?1049l", 8); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 2), total); +} + +test "search select wraps in both directions" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz\r\nBuzz\r\nFizz", 16); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + try testing.expectEqual(Result.success, run(search)); + + // No selection yet. + var idx: usize = 999; + try testing.expectEqual(Result.no_value, get(search, .selected_index, &idx)); + + // Next: newest match first (index 0), then older (1), then wrap + // back to 0. + try testing.expectEqual(Result.success, set(search, .select_next, null)); + try testing.expectEqual(Result.success, get(search, .selected_index, &idx)); + try testing.expectEqual(@as(usize, 0), idx); + + var match: selection_c.CSelection = undefined; + try testing.expectEqual(Result.success, get(search, .selected_match, &match)); + try testing.expect(match.start.toPin() != null); + + try testing.expectEqual(Result.success, set(search, .select_next, null)); + try testing.expectEqual(Result.success, get(search, .selected_index, &idx)); + try testing.expectEqual(@as(usize, 1), idx); + + try testing.expectEqual(Result.success, set(search, .select_next, null)); + try testing.expectEqual(Result.success, get(search, .selected_index, &idx)); + try testing.expectEqual(@as(usize, 0), idx); + + // Prev: wrap backward to the oldest match. + try testing.expectEqual(Result.success, set(search, .select_prev, null)); + try testing.expectEqual(Result.success, get(search, .selected_index, &idx)); + try testing.expectEqual(@as(usize, 1), idx); +} + +test "search select with no matches returns no value" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + try testing.expectEqual(Result.no_value, set(search, .select_next, null)); + try testing.expectEqual(Result.no_value, set(search, .select_prev, null)); +} + +test "search select rejects a non-null reserved value" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + const bogus: c_int = 0; + try testing.expectEqual(Result.invalid_value, set(search, .select_next, &bogus)); + try testing.expectEqual(Result.invalid_value, set(search, .select_prev, &bogus)); +} + +test "search select scroll option" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + + var scroll: Scroll = .none; + try testing.expectEqual(Result.success, get(search, .select_scroll, &scroll)); + try testing.expectEqual(Scroll.if_needed, scroll); + + const none: Scroll = .none; + try testing.expectEqual(Result.success, set(search, .select_scroll, &none)); + try testing.expectEqual(Result.success, get(search, .select_scroll, &scroll)); + try testing.expectEqual(Scroll.none, scroll); + + // NULL resets to the default. + try testing.expectEqual(Result.success, set(search, .select_scroll, null)); + try testing.expectEqual(Result.success, get(search, .select_scroll, &scroll)); + try testing.expectEqual(Scroll.if_needed, scroll); + + // Invalid enum values are rejected. + const bogus: c_int = 42; + try testing.expectEqual(Result.invalid_value, set(search, .select_scroll, @ptrCast(&bogus))); +} + +test "search selection dropped when reset prunes results" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz\r\nBuzz", 10); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, set(search, .select_next, null)); + + // A selection survives unrelated writes... + terminal_c.vt_write(terminal, "\r\nBang", 6); + try testing.expectEqual(Result.success, run(search)); + var match: selection_c.CSelection = undefined; + try testing.expectEqual(Result.success, get(search, .selected_match, &match)); + + // ...but a full reset prunes every result, dropping the selection. + terminal_c.vt_write(terminal, "\x1bc", 2); + try testing.expectEqual(Result.success, run(search)); + var total: usize = 999; + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 0), total); + try testing.expectEqual(Result.no_value, get(search, .selected_match, &match)); +} + +test "search matches buffer semantics" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz\r\nBuzz\r\nFizz", 16); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + try testing.expectEqual(Result.success, run(search)); + + // NULL ptr with cap 0 queries the required capacity. + var buf: selection_c.CSelectionBuffer = .{}; + try testing.expectEqual(Result.out_of_space, get(search, .matches, &buf)); + try testing.expectEqual(@as(usize, 2), buf.len); + + // Too-small buffers report the required capacity. + var one: [1]selection_c.CSelection = undefined; + buf = .{ .ptr = &one, .cap = one.len }; + try testing.expectEqual(Result.out_of_space, get(search, .matches, &buf)); + try testing.expectEqual(@as(usize, 2), buf.len); + + // A large-enough buffer is filled newest to oldest. + var storage: [4]selection_c.CSelection = undefined; + buf = .{ .ptr = &storage, .cap = storage.len }; + try testing.expectEqual(Result.success, get(search, .matches, &buf)); + try testing.expectEqual(@as(usize, 2), buf.len); + const first = storage[0].start.toPin().?; + const second = storage[1].start.toPin().?; + try testing.expect(first.y != second.y or first.node != second.node); + + // Viewport matches use the same conventions and are cached across + // reads. + buf = .{}; + try testing.expectEqual(Result.out_of_space, get(search, .viewport_matches, &buf)); + try testing.expectEqual(@as(usize, 2), buf.len); + buf = .{ .ptr = &storage, .cap = storage.len }; + try testing.expectEqual(Result.success, get(search, .viewport_matches, &buf)); + try testing.expectEqual(@as(usize, 2), buf.len); + buf = .{ .ptr = &storage, .cap = storage.len }; + try testing.expectEqual(Result.success, get(search, .viewport_matches, &buf)); + try testing.expectEqual(@as(usize, 2), buf.len); +} + +test "search get_multi returns first failing index" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz", 4); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + try testing.expectEqual(Result.success, run(search)); + + // No selection: selected_index fails at index 1. + const keys = [_]Data{ .total_matches, .selected_index, .status }; + var total: usize = 0; + var idx: usize = 0; + var status: Status = .running; + var values = [_]?*anyopaque{ &total, &idx, &status }; + var written: usize = 999; + try testing.expectEqual(Result.no_value, get_multi( + search, + keys.len, + &keys, + &values, + &written, + )); + try testing.expectEqual(@as(usize, 1), written); + try testing.expectEqual(@as(usize, 1), total); + + // After selecting, the whole batch succeeds. + try testing.expectEqual(Result.success, set(search, .select_next, null)); + try testing.expectEqual(Result.success, get_multi( + search, + keys.len, + &keys, + &values, + &written, + )); + try testing.expectEqual(keys.len, written); + try testing.expectEqual(@as(usize, 0), idx); +} + +test "search new validates options" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + var search: Search = null; + + // NULL out and NULL terminal are invalid. + try testing.expectEqual(Result.invalid_value, new( + &lib.alloc.test_allocator, + null, + terminal, + )); + try testing.expectEqual(Result.invalid_value, new( + &lib.alloc.test_allocator, + &search, + null, + )); + try testing.expect(search == null); +} + +test "search without a needle is idle" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz", 4); + + var search: Search = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &search, + terminal, + )); + defer free(search); + + // With nothing to look for, the search is complete and empty, and + // driving it is a harmless no-op. + var status: Status = .running; + try testing.expectEqual(Result.success, get(search, .status, &status)); + try testing.expectEqual(Status.complete, status); + try testing.expectEqual(Result.success, feed(search)); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, tick(search, &status)); + try testing.expectEqual(Status.complete, status); + + var needle_out: lib.String = undefined; + try testing.expectEqual(Result.no_value, get(search, .needle, &needle_out)); + var total: usize = 999; + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 0), total); + try testing.expectEqual(Result.no_value, set(search, .select_next, null)); + + var buf: selection_c.CSelectionBuffer = .{}; + try testing.expectEqual(Result.success, get(search, .matches, &buf)); + try testing.expectEqual(@as(usize, 0), buf.len); + buf = .{}; + try testing.expectEqual(Result.success, get(search, .viewport_matches, &buf)); + try testing.expectEqual(@as(usize, 0), buf.len); + + // Clearing an already-clear needle is fine. + try testing.expectEqual(Result.success, set(search, .needle, null)); +} + +test "search needle change and clear" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + terminal_c.vt_write(terminal, "Fizz\r\nBuzz", 10); + + const search: Search = try testNewSearch(terminal, "Fizz"); + defer free(search); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, set(search, .select_next, null)); + + var total: usize = 0; + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 1), total); + + // Setting the same needle again (any ASCII case) keeps existing + // results and the selection. + const same = testString("fIZZ"); + try testing.expectEqual(Result.success, set(search, .needle, &same)); + var needle_out: lib.String = undefined; + try testing.expectEqual(Result.success, get(search, .needle, &needle_out)); + try testing.expectEqualStrings("Fizz", needle_out.ptr[0..needle_out.len]); + var idx: usize = 999; + try testing.expectEqual(Result.success, get(search, .selected_index, &idx)); + try testing.expectEqual(@as(usize, 0), idx); + + // Changing the needle restarts the search from scratch. + const changed = testString("Buzz"); + try testing.expectEqual(Result.success, set(search, .needle, &changed)); + var status: Status = .complete; + try testing.expectEqual(Result.success, get(search, .status, &status)); + try testing.expectEqual(Status.feed_required, status); + try testing.expectEqual(Result.no_value, get(search, .selected_index, &idx)); + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 1), total); + try testing.expectEqual(Result.success, get(search, .needle, &needle_out)); + try testing.expectEqualStrings("Buzz", needle_out.ptr[0..needle_out.len]); + + // An empty needle clears the search, same as NULL. + const empty = testString(""); + try testing.expectEqual(Result.success, set(search, .needle, &empty)); + try testing.expectEqual(Result.no_value, get(search, .needle, &needle_out)); + try testing.expectEqual(Result.success, get(search, .status, &status)); + try testing.expectEqual(Status.complete, status); + try testing.expectEqual(Result.success, get(search, .total_matches, &total)); + try testing.expectEqual(@as(usize, 0), total); +} + +test "search free after terminal free" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + + terminal_c.vt_write(terminal, "Fizz\r\nFizz", 10); + + const search: Search = try testNewSearch(terminal, "Fizz"); + + // Run and select so the search holds tracked pins within the + // terminal's page storage. + try testing.expectEqual(Result.success, run(search)); + try testing.expectEqual(Result.success, set(search, .select_next, null)); + + // Free the terminal first. The search detaches: calls that need + // the terminal fail cleanly instead of touching freed memory. + terminal_c.free(terminal); + try testing.expectEqual(Result.invalid_value, feed(search)); + try testing.expectEqual(Result.invalid_value, run(search)); + try testing.expectEqual(Result.invalid_value, set(search, .select_next, null)); + const needle_value = testString("Buzz"); + try testing.expectEqual(Result.invalid_value, set(search, .needle, &needle_value)); + + // Reads that only touch search-owned state still answer. + var needle_out: lib.String = undefined; + try testing.expectEqual(Result.success, get(search, .needle, &needle_out)); + try testing.expectEqualStrings("Fizz", needle_out.ptr[0..needle_out.len]); + const scroll: Scroll = .none; + try testing.expectEqual(Result.success, set(search, .select_scroll, &scroll)); + + // The search can still be freed, releasing only its own memory. + free(search); +} + +test "search freed before terminal detaches from the registry" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + 10, + 4, + )); + defer terminal_c.free(terminal); + + // Create two searches and free one while the terminal is alive. + // The freed search must be unregistered so the later terminal free + // only detaches the survivor. + const a: Search = try testNewSearch(terminal, "Fizz"); + const b: Search = try testNewSearch(terminal, "Fizz"); + defer free(b); + + try testing.expectEqual(Result.success, run(a)); + free(a); + try testing.expectEqual(Result.success, run(b)); +} + +test "search free null" { + free(null); +} diff --git a/vendor/libghostty-vt/src/terminal/c/selection.zig b/vendor/libghostty-vt/src/terminal/c/selection.zig index cb574ecc..2830149f 100644 --- a/vendor/libghostty-vt/src/terminal/c/selection.zig +++ b/vendor/libghostty-vt/src/terminal/c/selection.zig @@ -38,6 +38,18 @@ pub const CSelection = extern struct { } }; +/// C: GhosttySelectionBuffer +/// +/// A caller-provided buffer of selections. This follows the same +/// conventions as GhosttyBuffer: ptr may be NULL with cap 0 to query +/// the required capacity, and len is set to the entries written on +/// success or to the required capacity on GHOSTTY_OUT_OF_SPACE. +pub const CSelectionBuffer = extern struct { + ptr: ?[*]CSelection = null, + cap: usize = 0, + len: usize = 0, +}; + /// C: GhosttyTerminalSelectWordOptions pub const SelectWordOptions = extern struct { size: usize = @sizeOf(SelectWordOptions), @@ -234,7 +246,8 @@ pub fn format_alloc( }; const buf = aw.toOwnedSlice() catch return .out_of_memory; - out_ptr.* = buf.ptr; + // Do not expose Zig's empty slice sentinel through the C ABI. + out_ptr.* = if (buf.len == 0) null else buf.ptr; out_len.* = buf.len; return .success; } @@ -253,7 +266,7 @@ fn selectionFormatter( opts: FormatOptions, ) error{ InvalidValue, NoValue }!formatterpkg.TerminalFormatter { if (opts.size < @sizeOf(FormatOptions)) return error.InvalidValue; - _ = std.meta.intToEnum(Format, @intFromEnum(opts.emit)) catch + _ = std.enums.fromInt(Format, @intFromEnum(opts.emit)) orelse return error.InvalidValue; const sel = if (opts.selection) |sel| @@ -308,7 +321,7 @@ pub fn adjust( adjustment: Selection.Adjustment, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Selection.Adjustment, @intFromEnum(adjustment)) catch { + _ = std.enums.fromInt(Selection.Adjustment, @intFromEnum(adjustment)) orelse { log.warn("terminal_selection_adjust invalid adjustment value={d}", .{@intFromEnum(adjustment)}); return .invalid_value; }; @@ -343,7 +356,7 @@ pub fn ordered( out_selection: ?*CSelection, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Selection.Order, @intFromEnum(desired)) catch { + _ = std.enums.fromInt(Selection.Order, @intFromEnum(desired)) orelse { log.warn("terminal_selection_ordered invalid desired value={d}", .{@intFromEnum(desired)}); return .invalid_value; }; @@ -392,12 +405,44 @@ pub fn equal( return .success; } +test "selection_format_alloc empty output" { + const failing: CAllocator = .fromZig(&std.mem.Allocator.failing); + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer terminal_c.free(t); + + var ref: grid_ref.CGridRef = .{}; + try testing.expectEqual(Result.success, terminal_c.grid_ref(t, .{ + .tag = .active, + .value = .{ .active = .{ .x = 0, .y = 0 } }, + }, &ref)); + const sel: CSelection = .{ .start = ref, .end = ref }; + try testing.expectEqual(Result.success, terminal_c.set(t, .selection, &sel)); + + var ptr: ?[*]u8 = null; + var len: usize = 123; + try testing.expectEqual(Result.success, format_alloc(t, &failing, .{ + .emit = .plain, + .unwrap = true, + .trim = true, + }, &ptr, &len)); + defer @import("allocator.zig").free(&failing, ptr, len); + try testing.expectEqual(@as(usize, 0), len); + try testing.expectEqual(null, ptr); +} + test "selection_format_alloc uses active selection" { var t: terminal_c.Terminal = null; try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -457,7 +502,8 @@ test "selection_format_buf uses provided selection" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); @@ -513,7 +559,8 @@ test "selection_format_alloc returns no_value without active selection" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer terminal_c.free(t); diff --git a/vendor/libghostty-vt/src/terminal/c/selection_gesture.zig b/vendor/libghostty-vt/src/terminal/c/selection_gesture.zig index cc56da3c..46253057 100644 --- a/vendor/libghostty-vt/src/terminal/c/selection_gesture.zig +++ b/vendor/libghostty-vt/src/terminal/c/selection_gesture.zig @@ -241,7 +241,7 @@ pub fn event_new( event_type: EventType, ) callconv(lib.calling_conv) Result { const out = out_event orelse return .invalid_value; - _ = std.meta.intToEnum(EventType, @intFromEnum(event_type)) catch + _ = std.enums.fromInt(EventType, @intFromEnum(event_type)) orelse return .invalid_value; const alloc = lib.alloc.default(alloc_); @@ -343,7 +343,7 @@ pub fn event_set( value: ?*const anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(EventOption, @intFromEnum(option)) catch { + _ = std.enums.fromInt(EventOption, @intFromEnum(option)) orelse { log.warn("selection_gesture_event_set invalid option value={d}", .{@intFromEnum(option)}); return .invalid_value; }; @@ -365,7 +365,7 @@ pub fn get( out: ?*anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Data, @intFromEnum(data)) catch { + _ = std.enums.fromInt(Data, @intFromEnum(data)) orelse { log.warn("selection_gesture_get invalid data value={d}", .{@intFromEnum(data)}); return .invalid_value; }; @@ -738,24 +738,12 @@ fn clearWordBoundaryCodepoints(event: *EventWrapper, target: *[]const u21) void target.* = &selection_codepoints.default_word_boundaries; } -fn instantFromNs(ns: u64) SelectionGesture.Time { - if (comptime builtin.target.cpu.arch == .wasm32 and - builtin.target.os.tag == .freestanding) - { - return ns; - } - - return switch (builtin.os.tag) { - .windows, .uefi, .wasi => .{ .timestamp = ns }, - else => .{ .timestamp = .{ - .sec = @intCast(ns / std.time.ns_per_s), - .nsec = @intCast(ns % std.time.ns_per_s), - } }, - }; +fn instantFromNs(ns: u64) std.Io.Timestamp { + return .fromNanoseconds(ns); } fn validBehavior(behavior: Behavior) bool { - _ = std.meta.intToEnum(Behavior, @intFromEnum(behavior)) catch return false; + _ = std.enums.fromInt(Behavior, @intFromEnum(behavior)) orelse return false; return true; } @@ -764,7 +752,8 @@ test "selection gesture lifecycle and get" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -800,7 +789,8 @@ test "selection gesture get_multi" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -844,7 +834,8 @@ test "selection gesture get_multi returns first failing index" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -956,7 +947,8 @@ test "selection gesture event applies press" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1003,7 +995,8 @@ test "selection gesture event press requires ref" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1031,7 +1024,8 @@ test "selection gesture event null output still reports no selection" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1065,7 +1059,8 @@ test "selection gesture event applies release" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1116,7 +1111,8 @@ test "selection gesture release without ref marks dragged" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1163,7 +1159,8 @@ test "selection gesture event applies drag" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1235,7 +1232,8 @@ test "selection gesture drag requires ref and geometry" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1279,7 +1277,8 @@ test "selection gesture event applies autoscroll tick" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1362,7 +1361,8 @@ test "selection gesture autoscroll tick requires viewport and geometry" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1401,7 +1401,8 @@ test "selection gesture event applies deep press" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); @@ -1456,7 +1457,8 @@ test "selection gesture deep press without active anchor returns no value" { try testing.expectEqual(Result.success, terminal_c.new( &lib.alloc.test_allocator, &terminal, - .{ .cols = 5, .rows = 2, .max_scrollback = 10_000 }, + 5, + 2, )); defer terminal_c.free(terminal); diff --git a/vendor/libghostty-vt/src/terminal/c/sgr.zig b/vendor/libghostty-vt/src/terminal/c/sgr.zig index b0ef23d0..bb8830cb 100644 --- a/vendor/libghostty-vt/src/terminal/c/sgr.zig +++ b/vendor/libghostty-vt/src/terminal/c/sgr.zig @@ -126,17 +126,6 @@ pub fn attribute_value( return &attr.value; } -pub fn wasm_alloc_attribute() callconv(lib.calling_conv) *sgr.Attribute.C { - const alloc = std.heap.wasm_allocator; - const ptr = alloc.create(sgr.Attribute.C) catch @panic("out of memory"); - return ptr; -} - -pub fn wasm_free_attribute(attr: *sgr.Attribute.C) callconv(lib.calling_conv) void { - const alloc = std.heap.wasm_allocator; - alloc.destroy(attr); -} - test "alloc" { var p: Parser = undefined; try testing.expectEqual(Result.success, new( diff --git a/vendor/libghostty-vt/src/terminal/c/snapshot.zig b/vendor/libghostty-vt/src/terminal/c/snapshot.zig new file mode 100644 index 00000000..13d5f2b9 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/snapshot.zig @@ -0,0 +1,1527 @@ +//! C ABI wrappers for snapshot encoding and incremental restoration. + +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const io_c = @import("io.zig"); +const Result = @import("result.zig").Result; +const snapshot_core = @import("../snapshot/main.zig"); +const apc = @import("../apc.zig"); + +/// Snapshot readers accept the largest default APC payload. Deriving this from +/// the APC protocols keeps snapshot validation in sync as protocols change. +/// Opt-in decoded-terminal retention reuses this configured validation bound +/// as its runtime tracking limit. +const default_max_continuation_bytes = apc.Protocol.maxDefaultBytes(); +const terminal_c = @import("terminal.zig"); + +/// C: GhosttySnapshotDecoderOption. +/// +/// Options configure validation and returned-terminal policy before snapshot +/// decoding begins. +pub const DecoderOption = enum(c_int) { + max_continuation_bytes = 0, + retain_continuation = 1, + _, +}; + +/// C: GhosttySnapshotDecoderData. +/// +/// Data keys select typed values exposed by the decoder getter APIs. +pub const DecoderData = enum(c_int) { + invalid = 0, + max_continuation_bytes = 1, + source_offset = 2, + history_rows_primary = 3, + history_rows_alternate = 4, + progress_screen = 5, + progress_rows = 6, + progress_remaining = 7, + retain_continuation = 8, + _, + + /// Return the Zig type stored through the C API output pointer for a key. + fn OutType(comptime self: DecoderData) type { + return switch (self) { + .invalid => void, + .max_continuation_bytes, .source_offset => usize, + .history_rows_primary, .history_rows_alternate => u64, + .progress_screen => terminal_c.TerminalScreen, + .progress_rows => usize, + .progress_remaining => u32, + .retain_continuation => bool, + _ => void, + }; + } +}; + +/// Owns the source adapter and all state needed by an opaque C decoder handle. +const DecoderWrapper = struct { + /// A callback or borrowed-buffer source with uniform reader access. + const Source = union(enum) { + callback: io_c.ReaderAdapter, + buffer: std.Io.Reader, + + /// Return the stable `std.Io.Reader` used by the snapshot decoder. + fn reader(self: *Source) *std.Io.Reader { + return switch (self.*) { + .callback => |*value| &value.interface, + .buffer => |*value| value, + }; + } + + /// Return the number of source bytes consumed without reading ahead. + fn offset(self: *const Source) usize { + return switch (self.*) { + .callback => |*value| value.offset, + .buffer => |*value| value.seek, + }; + } + }; + + /// READY metadata that remains queryable through FINISH or a later error. + const Metadata = struct { + history_rows: std.EnumMap(terminal_c.TerminalScreen, u64), + }; + + /// Decoder lifecycle and the data available in each phase. + const State = union(enum) { + configuring, + + history: struct { + terminal: terminal_c.Terminal, + metadata: Metadata, + progress: ?snapshot_core.Decoder.Progress = null, + }, + + finished: Metadata, + + /// READY failures have no metadata. Failures from `next` retain the + /// READY metadata even though decoding cannot continue. + failed: ?Metadata, + }; + + alloc: std.mem.Allocator, + source: Source, + decoder: snapshot_core.Decoder, + state: State, + max_continuation_bytes: usize, + retain_continuation: bool, +}; + +/// C: GhosttySnapshotDecoder, an opaque nullable decoder handle. +pub const Decoder = ?*DecoderWrapper; + +/// Create a decoder backed by a synchronous C reader callback. +pub fn decoder_new( + alloc_: ?*const CAllocator, + out_: ?*Decoder, + reader: io_c.Reader, +) callconv(lib.calling_conv) Result { + // Validate C-owned output and callback pointers before allocating anything. + const out = out_ orelse return .invalid_value; + out.* = null; + if (reader.read == null) return .invalid_value; + + // Store the adapter inline so its std.Io.Reader has a stable address. + return decoderNewSource(alloc_, out, .{ + .callback = io_c.ReaderAdapter.init(reader), + }); +} + +/// Create a decoder backed by immutable, caller-owned bytes. +pub fn decoder_new_buf( + alloc_: ?*const CAllocator, + out_: ?*Decoder, + ptr: ?[*]const u8, + len: usize, +) callconv(lib.calling_conv) Result { + // Normalize the C pointer and length into a borrowed Zig slice. + const out = out_ orelse return .invalid_value; + out.* = null; + const bytes: []const u8 = if (ptr) |value| + value[0..len] + else if (len == 0) + &.{} + else + return .invalid_value; + + // The fixed reader records its current seek position as the source offset. + return decoderNewSource(alloc_, out, .{ + .buffer = .fixed(bytes), + }); +} + +/// Allocate and initialize a decoder around either supported source type. +fn decoderNewSource( + alloc_: ?*const CAllocator, + out: *Decoder, + source: DecoderWrapper.Source, +) Result { + // Allocate first so the source and its embedded reader never move again. + const alloc = lib.alloc.default(alloc_); + const wrapper = alloc.create(DecoderWrapper) catch return .out_of_memory; + errdefer alloc.destroy(wrapper); + + // Initialize the core decoder only after its reader has a stable address. + wrapper.* = undefined; + wrapper.alloc = alloc; + wrapper.source = source; + wrapper.state = .configuring; + wrapper.max_continuation_bytes = default_max_continuation_bytes; + wrapper.retain_continuation = false; + wrapper.decoder = .init(wrapper.source.reader()); + out.* = wrapper; + return .success; +} + +/// Destroy a decoder without taking ownership of any returned terminal. +pub fn decoder_free(decoder_: Decoder) callconv(lib.calling_conv) void { + const decoder = decoder_ orelse return; + const alloc = decoder.alloc; + alloc.destroy(decoder); +} + +/// Set a decoder option while the decoder is still configuring. +pub fn decoder_set( + decoder_: Decoder, + option: DecoderOption, + value_: ?*const anyopaque, +) callconv(lib.calling_conv) Result { + // Options freeze as soon as any decoding attempt starts. + const decoder = decoder_ orelse return .invalid_value; + switch (decoder.state) { + .configuring => {}, + else => return .invalid_value, + } + + // Interpret the erased C pointer according to the selected option. + const value = value_ orelse return .invalid_value; + switch (option) { + .max_continuation_bytes => decoder.max_continuation_bytes = + @as(*const usize, @ptrCast(@alignCast(value))).*, + .retain_continuation => decoder.retain_continuation = + @as(*const bool, @ptrCast(@alignCast(value))).*, + _ => return .invalid_value, + } + return .success; +} + +/// Read one typed decoder value through the type-erased C API. +pub fn decoder_get( + decoder_: Decoder, + data: DecoderData, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + // Enumerate known keys so each branch recovers the correct output type. + return switch (data) { + inline .invalid, + .max_continuation_bytes, + .source_offset, + .history_rows_primary, + .history_rows_alternate, + .progress_screen, + .progress_rows, + .progress_remaining, + .retain_continuation, + => |comptime_data| decoderGetTyped( + decoder_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + _ => .invalid_value, + }; +} + +/// Implement a getter after the key has selected its concrete output type. +fn decoderGetTyped( + decoder_: Decoder, + comptime data: DecoderData, + out: *data.OutType(), +) Result { + const decoder = decoder_ orelse return .invalid_value; + switch (data) { + // Decoder-wide configuration and source state. + .invalid => return .invalid_value, + .max_continuation_bytes => { + if (decoderFailed(decoder)) return .no_value; + out.* = decoder.max_continuation_bytes; + }, + .source_offset => { + if (decoderFailed(decoder)) return .no_value; + out.* = decoder.source.offset(); + }, + .retain_continuation => { + if (decoderFailed(decoder)) return .no_value; + out.* = decoder.retain_continuation; + }, + + // READY metadata remains available after history decoding completes. + .history_rows_primary => { + const metadata = decoderMetadata(decoder) orelse return .no_value; + out.* = metadata.history_rows.get(.primary) orelse return .no_value; + }, + .history_rows_alternate => { + const metadata = decoderMetadata(decoder) orelse return .no_value; + out.* = metadata.history_rows.get(.alternate) orelse + return .no_value; + }, + + // Progress describes only the most recent successful `next` call. + .progress_screen => { + const progress = decoderProgress(decoder) orelse return .no_value; + out.* = progress.key; + }, + .progress_rows => { + const progress = decoderProgress(decoder) orelse return .no_value; + out.* = progress.rows; + }, + .progress_remaining => { + const progress = decoderProgress(decoder) orelse return .no_value; + out.* = progress.remaining; + }, + else => return .invalid_value, + } + return .success; +} + +/// Return whether a consuming operation has permanently failed. +fn decoderFailed(decoder: *const DecoderWrapper) bool { + return switch (decoder.state) { + .failed => true, + else => false, + }; +} + +/// Return READY metadata in every state where it remains meaningful. +fn decoderMetadata( + decoder: *const DecoderWrapper, +) ?DecoderWrapper.Metadata { + return switch (decoder.state) { + .history => |value| value.metadata, + .finished => |value| value, + .failed => |value| value, + .configuring => null, + }; +} + +/// Return page progress only during incremental history decoding. +fn decoderProgress( + decoder: *const DecoderWrapper, +) ?snapshot_core.Decoder.Progress { + return switch (decoder.state) { + .history => |value| value.progress, + else => null, + }; +} + +/// Query several typed decoder values in order, stopping at the first error. +pub fn decoder_get_multi( + decoder_: Decoder, + count: usize, + keys_: ?[*]const DecoderData, + values_: ?[*]?*anyopaque, + out_written: ?*usize, +) callconv(lib.calling_conv) Result { + // Invalid arrays and first-key failures both report zero completed writes. + if (out_written) |written| written.* = 0; + const keys = keys_ orelse return .invalid_value; + const values = values_ orelse return .invalid_value; + + // Reuse the single-key path so availability rules remain identical. + for (0..count) |i| { + const result = decoder_get(decoder_, keys[i], values[i]); + if (result != .success) { + if (out_written) |written| written.* = i; + return result; + } + } + if (out_written) |written| written.* = count; + return .success; +} + +/// Decode through READY and return a renderable terminal for incremental use. +pub fn decoder_ready( + decoder_: Decoder, + out_: ?*terminal_c.Terminal, +) callconv(lib.calling_conv) Result { + // Validate the output and require an untouched decoder lifecycle. + const out = out_ orelse return .invalid_value; + out.* = null; + const decoder = decoder_ orelse return .invalid_value; + switch (decoder.state) { + .configuring => {}, + else => return .invalid_value, + } + // Decode READY and transfer the decoded state into a C-owned terminal. + const ready = decoderReadyTerminal(decoder) catch |err| { + decoder.state = .{ .failed = null }; + return decoderMapError(decoder, err); + }; + + // Keep only the terminal handle and queryable metadata for page decoding. + decoder.state = .{ .history = .{ + .terminal = ready.terminal, + .metadata = ready.metadata, + } }; + out.* = ready.terminal; + return .success; +} + +/// Decode and apply exactly one history page, or validate FINISH. +pub fn decoder_next( + decoder_: Decoder, +) callconv(lib.calling_conv) Result { + // FINISH is idempotent; every other non-history state rejects `next`. + const decoder = decoder_ orelse return .invalid_value; + switch (decoder.state) { + .finished => return .no_value, + .history => {}, + else => return .invalid_value, + } + + // Resolve the terminal retained by READY and clear stale page progress. + const history = &decoder.state.history; + const terminal = history.terminal orelse return .invalid_value; + const native = terminal_c.zigTerminal(terminal).?; + history.progress = null; + + // Consume one validated record and preserve READY metadata on failure. + const progress = decoder.decoder.next(decoder.alloc, native) catch |err| { + const metadata = history.metadata; + decoder.state = .{ .failed = metadata }; + return decoderMapError(decoder, err); + }; + + // Publish page progress, or transition permanently to validated FINISH. + if (progress) |value| { + history.progress = value; + return .success; + } + + const metadata = history.metadata; + decoder.state = .{ .finished = metadata }; + return .no_value; +} + +/// Decode and validate the complete snapshot transactionally. +pub fn decoder_decode( + decoder_: Decoder, + out_: ?*terminal_c.Terminal, +) callconv(lib.calling_conv) Result { + // Validate the output and require an untouched decoder lifecycle. + const out = out_ orelse return .invalid_value; + out.* = null; + const decoder = decoder_ orelse return .invalid_value; + switch (decoder.state) { + .configuring => {}, + else => return .invalid_value, + } + // Build the terminal from the renderable READY prefix. + const ready = decoderReadyTerminal(decoder) catch |err| { + decoder.state = .{ .failed = null }; + return decoderMapError(decoder, err); + }; + const native = terminal_c.zigTerminal(ready.terminal).?; + + // Apply every history page and require a valid FINISH record. + while (true) { + const progress = decoder.decoder.next(decoder.alloc, native) catch |err| { + terminal_c.free(ready.terminal); + decoder.state = .{ .failed = ready.metadata }; + return decoderMapError(decoder, err); + }; + if (progress == null) break; + } + + // Publish the terminal only after the entire snapshot succeeds. + decoder.state = .{ .finished = ready.metadata }; + out.* = ready.terminal; + return .success; +} + +/// Values produced while moving a core READY result into a C terminal. +const ReadyTerminal = struct { + terminal: terminal_c.Terminal, + metadata: DecoderWrapper.Metadata, +}; + +/// Decode READY with terminal-owned I/O and construct the C terminal. +fn decoderReadyTerminal(decoder: *DecoderWrapper) anyerror!ReadyTerminal { + const io: terminal_c.Io = .init; + var decoded = try decoder.decoder.ready( + decoder.alloc, + io.io(), + .{ .max_continuation_bytes = decoder.max_continuation_bytes }, + ); + defer decoded.deinit(decoder.alloc); + + // Copy small query metadata before `fromDecoded` consumes the core result. + const metadata: DecoderWrapper.Metadata = .{ + .history_rows = decoded.history_rows, + }; + + // Move terminal state and I/O into their final C-owned allocation. + const terminal = try terminal_c.fromDecoded( + decoder.alloc, + io, + &decoded, + if (decoder.retain_continuation) + decoder.max_continuation_bytes + else + 0, + ); + return .{ .terminal = terminal, .metadata = metadata }; +} + +/// Map decoder and source-adapter failures to public C result codes. +fn decoderMapError(decoder: *DecoderWrapper, err: anyerror) Result { + // Callback protocol failures are more specific than the core read error. + switch (decoder.source) { + .callback => |adapter| { + if (adapter.invalid_read) return .invalid_value; + if (adapter.callback_failed) return .io_error; + }, + .buffer => {}, + } + + // A successful zero-byte read is clean EOF by contract. Reaching it before + // the required marker therefore means truncated snapshot data, not an + // external I/O failure, and deliberately maps to invalid_value below. + return switch (err) { + error.OutOfMemory => .out_of_memory, + error.ContinuationLimitExceeded => .limit_exceeded, + error.ContinuationDisabled, + error.ContinuationUnavailable, + error.DecoderNotReady, + error.DecoderFailed, + => .invalid_value, + error.InvalidContinuation => .invalid_value, + else => .invalid_value, + }; +} + +/// Export the allocator-owned continuation required by snapshot encoding. +fn continuationOwned(terminal: terminal_c.Terminal) struct { + result: Result, + bytes: []u8, +} { + // The terminal allocator also owns the temporary continuation copy. + const native = terminal_c.zigTerminal(terminal) orelse return .{ + .result = .invalid_value, + .bytes = &.{}, + }; + const alloc = native.gpa(); + + // Snapshotting can prove an untracked ground stream needs no replay bytes; + // only non-ground streams require tracking to have retained their prefix. + const bytes = terminal_c.continuationAllocIo( + terminal, + alloc, + true, + ) catch |err| { + return .{ + .result = switch (err) { + error.InvalidValue => .invalid_value, + error.OutOfMemory => .out_of_memory, + error.ContinuationDisabled, + error.ContinuationUnavailable, + => .invalid_value, + }, + .bytes = &.{}, + }; + }; + return .{ .result = .success, .bytes = bytes }; +} + +/// Convert exported bytes to the core snapshot continuation representation. +fn continuationValue(bytes: []const u8) snapshot_core.Continuation { + return if (bytes.len == 0) .ground else .{ .bytes = bytes }; +} + +/// Encode a terminal snapshot to a synchronous C writer callback. +pub fn encode( + terminal: terminal_c.Terminal, + writer: io_c.Writer, +) callconv(lib.calling_conv) Result { + // Validate both handles and preflight the terminal continuation. + const native = terminal_c.zigTerminal(terminal) orelse return .invalid_value; + if (writer.write == null) return .invalid_value; + const continuation = continuationOwned(terminal); + if (continuation.result != .success) return continuation.result; + defer native.gpa().free(continuation.bytes); + + // Stream the snapshot through the callback adapter, batching the + // encoder's writes into few callback invocations. + var buffer: [io_c.WriterAdapter.recommended_buffer_len]u8 = undefined; + var adapter: io_c.WriterAdapter = .initBuffered(writer, &buffer); + snapshot_core.encode( + native.gpa(), + &adapter.interface, + native, + .{ .continuation = continuationValue(continuation.bytes) }, + ) catch |err| return mapEncodeError(err, &adapter); + adapter.interface.flush() catch + return mapEncodeError(error.WriteFailed, &adapter); + return .success; +} + +/// Encode a terminal snapshot into a caller-provided fixed buffer. +pub fn encode_buf( + terminal: terminal_c.Terminal, + buf: ?[*]u8, + buf_len: usize, + out_written_: ?*usize, +) callconv(lib.calling_conv) Result { + // Validate output storage and preflight the terminal continuation. + const out_written = out_written_ orelse return .invalid_value; + out_written.* = 0; + if (buf == null and buf_len != 0) return .invalid_value; + const native = terminal_c.zigTerminal(terminal) orelse return .invalid_value; + const continuation = continuationOwned(terminal); + if (continuation.result != .success) return continuation.result; + defer native.gpa().free(continuation.bytes); + + // A null size query becomes a zero-capacity fixed writer and follows the + // same WriteFailed counting path as every other undersized destination. + const destination: []u8 = if (buf) |ptr| ptr[0..buf_len] else &.{}; + var writer: std.Io.Writer = .fixed(destination); + snapshot_core.encode( + native.gpa(), + &writer, + native, + .{ .continuation = continuationValue(continuation.bytes) }, + ) catch |err| switch (err) { + error.WriteFailed => { + // The fixed writer may already contain a valid snapshot prefix. + // Repeat only on this failure path to report the exact capacity. + var counter: std.Io.Writer.Discarding = .init(&.{}); + snapshot_core.encode( + native.gpa(), + &counter.writer, + native, + .{ .continuation = continuationValue(continuation.bytes) }, + ) catch |count_err| return mapEncodeError(count_err, null); + out_written.* = std.math.cast(usize, counter.count) orelse + return .limit_exceeded; + return .out_of_space; + }, + else => return mapEncodeError(err, null), + }; + out_written.* = writer.end; + return .success; +} + +/// Encode a terminal snapshot into a newly allocated C-owned buffer. +pub fn encode_alloc( + terminal: terminal_c.Terminal, + alloc_: ?*const CAllocator, + out_ptr_: ?*?[*]u8, + out_len_: ?*usize, +) callconv(lib.calling_conv) Result { + // Initialize outputs before validating terminal state or allocating bytes. + const out_ptr = out_ptr_ orelse return .invalid_value; + const out_len = out_len_ orelse return .invalid_value; + out_ptr.* = null; + out_len.* = 0; + + // Preflight continuation state before building an allocating writer. + const native = terminal_c.zigTerminal(terminal) orelse return .invalid_value; + const continuation = continuationOwned(terminal); + if (continuation.result != .success) return continuation.result; + defer native.gpa().free(continuation.bytes); + + // Encode once, then transfer ownership of the writer's completed slice. + const alloc = lib.alloc.default(alloc_); + var writer: std.Io.Writer.Allocating = .init(alloc); + defer writer.deinit(); + snapshot_core.encode( + native.gpa(), + &writer.writer, + native, + .{ .continuation = continuationValue(continuation.bytes) }, + ) catch |err| return mapEncodeError(err, null); + const bytes = writer.toOwnedSlice() catch return .out_of_memory; + out_ptr.* = bytes.ptr; + out_len.* = bytes.len; + return .success; +} + +/// Map core encoder and callback-adapter failures to public result codes. +fn mapEncodeError( + err: anyerror, + adapter: ?*const io_c.WriterAdapter, +) Result { + // Callback validation happens before encoding, so invalid_write can only + // mean output accounting overflow; callback_failed is external I/O. + if (adapter) |value| { + if (value.invalid_write) return .limit_exceeded; + if (value.callback_failed) return .io_error; + } + + // Fixed and allocating writers surface only core allocation or size errors. + return switch (err) { + error.OutOfMemory, error.WriteFailed => .out_of_memory, + error.Overflow, + error.PayloadTooLarge, + error.PageCountOverflow, + error.ScrollbackLimitOverflow, + error.StringTooLong, + => .limit_exceeded, + else => .invalid_value, + }; +} + +/// Enable continuation tracking for tests that encode C terminal snapshots. +fn testEnableContinuation(terminal: terminal_c.Terminal) !void { + const limit: usize = default_max_continuation_bytes; + try testing.expectEqual(Result.success, terminal_c.set( + terminal, + .continuation_max_bytes, + &limit, + )); +} + +test "decoder option and empty source" { + var decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &decoder, + null, + 0, + )); + defer decoder_free(decoder); + + var limit: usize = 0; + try testing.expectEqual(Result.success, decoder_get( + decoder, + .max_continuation_bytes, + &limit, + )); + try testing.expectEqual(default_max_continuation_bytes, limit); + + limit = 1234; + try testing.expectEqual(Result.success, decoder_set( + decoder, + .max_continuation_bytes, + &limit, + )); + limit = 0; + try testing.expectEqual(Result.success, decoder_get( + decoder, + .max_continuation_bytes, + &limit, + )); + try testing.expectEqual(1234, limit); + + var retain = true; + try testing.expectEqual(Result.success, decoder_get( + decoder, + .retain_continuation, + &retain, + )); + try testing.expect(!retain); + retain = true; + try testing.expectEqual(Result.success, decoder_set( + decoder, + .retain_continuation, + &retain, + )); + retain = false; + try testing.expectEqual(Result.success, decoder_get( + decoder, + .retain_continuation, + &retain, + )); + try testing.expect(retain); + + var written: usize = 99; + try testing.expectEqual(Result.invalid_value, decoder_get_multi( + decoder, + 1, + null, + null, + &written, + )); + try testing.expectEqual(@as(usize, 0), written); + + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.invalid_value, decoder_decode( + decoder, + &terminal, + )); + try testing.expectEqual(null, terminal); +} + +test "snapshot C API full round trip restores continuation" { + var source: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &source, + 20, + 4, + )); + defer terminal_c.free(source); + try testEnableContinuation(source); + terminal_c.vt_write(source, "hello\x1b[31", "hello\x1b[31".len); + + var encoded_ptr: ?[*]u8 = null; + var encoded_len: usize = 0; + try testing.expectEqual(Result.success, encode_alloc( + source, + &lib.alloc.test_allocator, + &encoded_ptr, + &encoded_len, + )); + const encoded = encoded_ptr.?[0..encoded_len]; + defer lib.alloc.default(&lib.alloc.test_allocator).free(encoded); + + var decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &decoder, + encoded.ptr, + encoded.len, + )); + defer decoder_free(decoder); + + var restored: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, decoder_decode(decoder, &restored)); + defer terminal_c.free(restored); + + const source_text = try terminal_c.zigTerminal(source).?.plainString(testing.allocator); + defer testing.allocator.free(source_text); + const restored_text = try terminal_c.zigTerminal(restored).?.plainString(testing.allocator); + defer testing.allocator.free(restored_text); + try testing.expectEqualStrings(source_text, restored_text); + + var restored_limit: usize = std.math.maxInt(usize); + try testing.expectEqual(Result.success, terminal_c.get( + restored, + .continuation_max_bytes, + &restored_limit, + )); + try testing.expectEqual(@as(usize, 0), restored_limit); + + // Parser state is restored, but its tracking policy is not. The terminal + // cannot be snapshotted again until the restored sequence reaches ground. + var restored_required: usize = 0; + try testing.expectEqual(Result.invalid_value, encode_buf( + restored, + null, + 0, + &restored_required, + )); + terminal_c.vt_write(restored, "m", 1); + try testing.expectEqual(Result.out_of_space, encode_buf( + restored, + null, + 0, + &restored_required, + )); + try testing.expect(restored_required > 0); + + var offset: usize = 0; + try testing.expectEqual(Result.success, decoder_get( + decoder, + .source_offset, + &offset, + )); + try testing.expectEqual(encoded.len, offset); + try testing.expectEqual(Result.no_value, decoder_next(decoder)); + + var retained_decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &retained_decoder, + encoded.ptr, + encoded.len, + )); + defer if (retained_decoder != null) decoder_free(retained_decoder); + const retained_limit: usize = 1024; + try testing.expectEqual(Result.success, decoder_set( + retained_decoder, + .max_continuation_bytes, + &retained_limit, + )); + const retain = true; + try testing.expectEqual(Result.success, decoder_set( + retained_decoder, + .retain_continuation, + &retain, + )); + + // The returned tracker owns the exact decoded continuation, so the + // decoder can be freed before callers export those terminal-owned bytes. + var retained: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, decoder_decode( + retained_decoder, + &retained, + )); + decoder_free(retained_decoder); + retained_decoder = null; + defer terminal_c.free(retained); + + var retained_terminal_limit: usize = 0; + try testing.expectEqual(Result.success, terminal_c.get( + retained, + .continuation_max_bytes, + &retained_terminal_limit, + )); + try testing.expectEqual(retained_limit, retained_terminal_limit); + var continuation_buf: [16]u8 = undefined; + var continuation_len: usize = 0; + try testing.expectEqual(Result.success, terminal_c.continuation_buf( + retained, + &continuation_buf, + continuation_buf.len, + &continuation_len, + )); + try testing.expectEqualStrings( + "\x1b[31", + continuation_buf[0..continuation_len], + ); + + // Disabling tracking releases the exported prefix without changing the + // unfinished parser state. The final byte still completes the SGR. + const disabled: usize = 0; + try testing.expectEqual(Result.success, terminal_c.set( + retained, + .continuation_max_bytes, + &disabled, + )); + try testing.expectEqual(Result.invalid_value, terminal_c.continuation_buf( + retained, + &continuation_buf, + continuation_buf.len, + &continuation_len, + )); + terminal_c.vt_write(retained, "m", 1); + var retained_ground = false; + try testing.expectEqual(Result.success, terminal_c.get( + retained, + .vt_ground, + &retained_ground, + )); + try testing.expect(retained_ground); + + var limited: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &limited, + encoded.ptr, + encoded.len, + )); + defer decoder_free(limited); + const limit: usize = 3; + try testing.expectEqual(Result.success, decoder_set( + limited, + .max_continuation_bytes, + &limit, + )); + var rejected: terminal_c.Terminal = null; + try testing.expectEqual(Result.limit_exceeded, decoder_decode( + limited, + &rejected, + )); + try testing.expectEqual(null, rejected); + try testing.expectEqual(Result.invalid_value, decoder_set( + limited, + .max_continuation_bytes, + &limit, + )); + var failed_offset: usize = 0; + try testing.expectEqual(Result.no_value, decoder_get( + limited, + .source_offset, + &failed_offset, + )); + + try testing.expectEqual(Result.success, terminal_c.set( + source, + .continuation_max_bytes, + &disabled, + )); + var required: usize = 0; + try testing.expectEqual(Result.invalid_value, encode_buf( + source, + null, + 0, + &required, + )); +} + +test "snapshot decoder retains every supported continuation class" { + const cases = [_]struct { + name: []const u8, + prefix: []const u8, + suffix: []const u8, + }{ + .{ .name = "ground", .prefix = "", .suffix = "X" }, + .{ .name = "CSI", .prefix = "\x1b[31", .suffix = "mX" }, + .{ .name = "OSC", .prefix = "\x1b]2;title", .suffix = "\x07" }, + .{ .name = "DCS", .prefix = "\x1bP$qm", .suffix = "\x1b\\" }, + .{ .name = "APC", .prefix = "\x1b_Ga=q;payload", .suffix = "\x1b\\" }, + .{ .name = "UTF-8", .prefix = "\xF0\x9F", .suffix = "\x98\x84" }, + }; + const limit: usize = 4096; + const disabled: usize = 0; + const retain = true; + + for (cases) |case| { + errdefer std.log.err("retained continuation case failed: {s}", .{case.name}); + + var source: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &source, + 20, + 4, + )); + defer terminal_c.free(source); + try testing.expectEqual(Result.success, terminal_c.set( + source, + .continuation_max_bytes, + &limit, + )); + terminal_c.vt_write(source, case.prefix.ptr, case.prefix.len); + + var snapshot_ptr: ?[*]u8 = null; + var snapshot_len: usize = 0; + try testing.expectEqual(Result.success, encode_alloc( + source, + &lib.alloc.test_allocator, + &snapshot_ptr, + &snapshot_len, + )); + const snapshot = snapshot_ptr.?[0..snapshot_len]; + defer lib.alloc.default(&lib.alloc.test_allocator).free(snapshot); + + var decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &decoder, + snapshot.ptr, + snapshot.len, + )); + defer if (decoder != null) decoder_free(decoder); + try testing.expectEqual(Result.success, decoder_set( + decoder, + .max_continuation_bytes, + &limit, + )); + try testing.expectEqual(Result.success, decoder_set( + decoder, + .retain_continuation, + &retain, + )); + + var restored: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, decoder_decode( + decoder, + &restored, + )); + defer terminal_c.free(restored); + decoder_free(decoder); + decoder = null; + + var restored_limit: usize = 0; + try testing.expectEqual(Result.success, terminal_c.get( + restored, + .continuation_max_bytes, + &restored_limit, + )); + try testing.expectEqual(limit, restored_limit); + + var continuation: [4096]u8 = undefined; + var continuation_len: usize = 0; + try testing.expectEqual(Result.success, terminal_c.continuation_buf( + restored, + &continuation, + continuation.len, + &continuation_len, + )); + try testing.expectEqualStrings( + case.prefix, + continuation[0..continuation_len], + ); + + // Releasing the retained bytes must not reset the parser. Both the + // source and replica should reach the same fully serializable state + // after consuming the suffix that followed the snapshot cut. + try testing.expectEqual(Result.success, terminal_c.set( + restored, + .continuation_max_bytes, + &disabled, + )); + try testing.expectEqual(Result.invalid_value, terminal_c.continuation_buf( + restored, + &continuation, + continuation.len, + &continuation_len, + )); + terminal_c.vt_write(source, case.suffix.ptr, case.suffix.len); + terminal_c.vt_write(restored, case.suffix.ptr, case.suffix.len); + + var source_ground = false; + var restored_ground = false; + try testing.expectEqual(Result.success, terminal_c.get( + source, + .vt_ground, + &source_ground, + )); + try testing.expectEqual(Result.success, terminal_c.get( + restored, + .vt_ground, + &restored_ground, + )); + try testing.expect(source_ground); + try testing.expect(restored_ground); + + var source_final_ptr: ?[*]u8 = null; + var source_final_len: usize = 0; + try testing.expectEqual(Result.success, encode_alloc( + source, + &lib.alloc.test_allocator, + &source_final_ptr, + &source_final_len, + )); + const source_final = source_final_ptr.?[0..source_final_len]; + defer lib.alloc.default(&lib.alloc.test_allocator).free(source_final); + + var restored_final_ptr: ?[*]u8 = null; + var restored_final_len: usize = 0; + try testing.expectEqual(Result.success, encode_alloc( + restored, + &lib.alloc.test_allocator, + &restored_final_ptr, + &restored_final_len, + )); + const restored_final = restored_final_ptr.?[0..restored_final_len]; + defer lib.alloc.default(&lib.alloc.test_allocator).free(restored_final); + try testing.expectEqualSlices(u8, source_final, restored_final); + } +} + +test "snapshot encoding accepts an untracked ground terminal" { + var source: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &source, + 10, + 3, + )); + defer terminal_c.free(source); + + var limit: usize = std.math.maxInt(usize); + try testing.expectEqual(Result.success, terminal_c.get( + source, + .continuation_max_bytes, + &limit, + )); + try testing.expectEqual(@as(usize, 0), limit); + + terminal_c.vt_write(source, "ground", "ground".len); + var required: usize = 0; + try testing.expectEqual(Result.out_of_space, encode_buf( + source, + null, + 0, + &required, + )); + try testing.expect(required > 0); + + // Once untracked input leaves ground, the missing prefix is unknowable. + terminal_c.vt_write(source, "\x1b[31", "\x1b[31".len); + try testing.expectEqual(Result.invalid_value, encode_buf( + source, + null, + 0, + &required, + )); +} + +test "snapshot callbacks stop at FINISH and map I/O failures" { + var source: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &source, + 10, + 3, + )); + defer terminal_c.free(source); + try testEnableContinuation(source); + terminal_c.vt_write(source, "callback", "callback".len); + + var required: usize = 0; + try testing.expectEqual(Result.out_of_space, encode_buf( + source, + null, + 0, + &required, + )); + const buffer_encoded = try testing.allocator.alloc(u8, required); + defer testing.allocator.free(buffer_encoded); + var buffer_written: usize = 0; + try testing.expectEqual(Result.success, encode_buf( + source, + buffer_encoded.ptr, + buffer_encoded.len, + &buffer_written, + )); + try testing.expectEqual(required, buffer_written); + + // A non-null undersized buffer takes the fixed-first path. It may contain + // the prefix written before capacity exhaustion while still reporting the + // exact complete size. + var short: [10]u8 = @splat(0xAA); + var short_required: usize = 0; + try testing.expectEqual(Result.out_of_space, encode_buf( + source, + &short, + short.len, + &short_required, + )); + try testing.expectEqual(required, short_required); + try testing.expectEqualStrings("GHOSTSNP", short[0..8]); + + const encoded = try testing.allocator.alloc(u8, required); + defer testing.allocator.free(encoded); + + const WriteContext = struct { + destination: []u8, + offset: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + if (len > self.destination.len - self.offset) return false; + @memcpy(self.destination[self.offset..][0..len], data[0..len]); + self.offset += len; + return true; + } + }; + var write_context: WriteContext = .{ .destination = encoded }; + try testing.expectEqual(Result.success, encode(source, .{ + .write = &WriteContext.write, + .userdata = &write_context, + })); + try testing.expectEqual(required, write_context.offset); + try testing.expectEqualSlices(u8, buffer_encoded, encoded); + + var failing = testing.FailingAllocator.init(testing.allocator, .{ + .fail_index = 0, + }); + const failing_zig = failing.allocator(); + const failing_c: CAllocator = .fromZig(&failing_zig); + var failed_ptr: ?[*]u8 = null; + var failed_len: usize = 99; + try testing.expectEqual(Result.out_of_memory, encode_alloc( + source, + &failing_c, + &failed_ptr, + &failed_len, + )); + try testing.expectEqual(null, failed_ptr); + try testing.expectEqual(@as(usize, 0), failed_len); + + const FailWriter = struct { + fn write(_: ?*anyopaque, _: [*]const u8, _: usize) callconv(lib.calling_conv) bool { + return false; + } + }; + try testing.expectEqual(Result.io_error, encode(source, .{ + .write = &FailWriter.write, + })); + + const combined = try testing.allocator.alloc(u8, encoded.len + 4); + defer testing.allocator.free(combined); + @memcpy(combined[0..encoded.len], encoded); + @memcpy(combined[encoded.len..], "tail"); + + const ReadContext = struct { + source: []const u8, + offset: usize = 0, + + fn read( + userdata: ?*anyopaque, + destination: [*]u8, + capacity: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + const remaining = self.source[self.offset..]; + const len = @min(remaining.len, capacity, 3); + @memcpy(destination[0..len], remaining[0..len]); + self.offset += len; + out_read.* = len; + return true; + } + }; + var read_context: ReadContext = .{ .source = combined }; + var decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new( + &lib.alloc.test_allocator, + &decoder, + .{ .read = &ReadContext.read, .userdata = &read_context }, + )); + defer decoder_free(decoder); + var restored: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, decoder_decode(decoder, &restored)); + defer terminal_c.free(restored); + try testing.expectEqual(encoded.len, read_context.offset); + try testing.expectEqualStrings("tail", read_context.source[read_context.offset..]); + + const FailReader = struct { + fn read( + _: ?*anyopaque, + _: [*]u8, + _: usize, + _: *usize, + ) callconv(lib.calling_conv) bool { + return false; + } + }; + var failed_decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new( + &lib.alloc.test_allocator, + &failed_decoder, + .{ .read = &FailReader.read }, + )); + defer decoder_free(failed_decoder); + var failed_terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.io_error, decoder_decode( + failed_decoder, + &failed_terminal, + )); + + const EofReader = struct { + fn read( + _: ?*anyopaque, + _: [*]u8, + _: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + out_read.* = 0; + return true; + } + }; + var eof_decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new( + &lib.alloc.test_allocator, + &eof_decoder, + .{ .read = &EofReader.read }, + )); + defer decoder_free(eof_decoder); + // Successful EOF before READY/FINISH is truncated snapshot data. It is + // intentionally INVALID_VALUE; only a false callback is IO_ERROR. + try testing.expectEqual(Result.invalid_value, decoder_decode( + eof_decoder, + &failed_terminal, + )); + + const InvalidReader = struct { + fn read( + _: ?*anyopaque, + _: [*]u8, + capacity: usize, + out_read: *usize, + ) callconv(lib.calling_conv) bool { + out_read.* = capacity + 1; + return true; + } + }; + var invalid_decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new( + &lib.alloc.test_allocator, + &invalid_decoder, + .{ .read = &InvalidReader.read }, + )); + defer decoder_free(invalid_decoder); + try testing.expectEqual(Result.invalid_value, decoder_decode( + invalid_decoder, + &failed_terminal, + )); +} + +test "snapshot incremental decoder exposes READY and page progress" { + var source: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &source, + 215, + 2, + )); + defer terminal_c.free(source); + try testEnableContinuation(source); + // Keep multiple complete pages. The ordinary C-terminal byte limit keeps + // at least one page but can evict older ones before snapshot encoding. + try testing.expectEqual(Result.success, terminal_c.set( + source, + .scrollback_max_bytes, + null, + )); + const first_page_rows = terminal_c.zigTerminal(source).?.screens + .get(.primary).?.pages.pages.first.?.capacity().rows; + for (0..@as(usize, first_page_rows) * 3) |_| + terminal_c.vt_write(source, "x\r\n", 3); + const ready_continuation = "\x1b]2;ready"; + terminal_c.vt_write( + source, + ready_continuation, + ready_continuation.len, + ); + + var encoded_ptr: ?[*]u8 = null; + var encoded_len: usize = 0; + try testing.expectEqual(Result.success, encode_alloc( + source, + &lib.alloc.test_allocator, + &encoded_ptr, + &encoded_len, + )); + const encoded = encoded_ptr.?[0..encoded_len]; + defer lib.alloc.default(&lib.alloc.test_allocator).free(encoded); + + var decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &decoder, + encoded.ptr, + encoded.len, + )); + defer decoder_free(decoder); + const retained_limit: usize = 1024; + try testing.expectEqual(Result.success, decoder_set( + decoder, + .max_continuation_bytes, + &retained_limit, + )); + const retain = true; + try testing.expectEqual(Result.success, decoder_set( + decoder, + .retain_continuation, + &retain, + )); + + var restored: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, decoder_ready(decoder, &restored)); + defer terminal_c.free(restored); + + // READY applies the same retention policy as one-shot decode and makes + // the unfinished snapshot continuation immediately exportable. + var restored_limit: usize = 0; + try testing.expectEqual(Result.success, terminal_c.get( + restored, + .continuation_max_bytes, + &restored_limit, + )); + try testing.expectEqual(retained_limit, restored_limit); + var ready_buf: [32]u8 = undefined; + var ready_len: usize = 0; + try testing.expectEqual(Result.success, terminal_c.continuation_buf( + restored, + &ready_buf, + ready_buf.len, + &ready_len, + )); + try testing.expectEqualStrings( + ready_continuation, + ready_buf[0..ready_len], + ); + + var history_rows: u64 = 0; + try testing.expectEqual(Result.success, decoder_get( + decoder, + .history_rows_primary, + &history_rows, + )); + try testing.expect(history_rows > 0); + + var page_count: usize = 0; + while (true) { + const result = decoder_next(decoder); + if (result == .no_value) break; + try testing.expectEqual(Result.success, result); + page_count += 1; + + var screen: terminal_c.TerminalScreen = undefined; + var rows: usize = 0; + var remaining: u32 = 0; + const keys = [_]DecoderData{ + .progress_screen, + .progress_rows, + .progress_remaining, + }; + const values = [_]?*anyopaque{ &screen, &rows, &remaining }; + var written: usize = 0; + try testing.expectEqual(Result.success, decoder_get_multi( + decoder, + keys.len, + &keys, + @constCast(&values), + &written, + )); + try testing.expectEqual(keys.len, written); + try testing.expectEqual(terminal_c.TerminalScreen.primary, screen); + try testing.expect(rows > 0); + } + try testing.expect(page_count > 0); + var rows: usize = 0; + try testing.expectEqual(Result.no_value, decoder_get( + decoder, + .progress_rows, + &rows, + )); + try testing.expectEqual(Result.no_value, decoder_next(decoder)); + + var source_total: usize = 0; + var restored_total: usize = 0; + try testing.expectEqual(Result.success, terminal_c.get( + source, + .total_rows, + &source_total, + )); + try testing.expectEqual(Result.success, terminal_c.get( + restored, + .total_rows, + &restored_total, + )); + try testing.expectEqual(source_total, restored_total); + + var dropped_decoder: Decoder = null; + try testing.expectEqual(Result.success, decoder_new_buf( + &lib.alloc.test_allocator, + &dropped_decoder, + encoded.ptr, + encoded.len, + )); + defer decoder_free(dropped_decoder); + var dropped: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, decoder_ready( + dropped_decoder, + &dropped, + )); + defer terminal_c.free(dropped); + try testing.expectEqual(Result.success, terminal_c.resize( + dropped, + 214, + 2, + 0, + 0, + )); + try testing.expectEqual(Result.success, decoder_next(dropped_decoder)); + var dropped_rows: usize = 1; + try testing.expectEqual(Result.success, decoder_get( + dropped_decoder, + .progress_rows, + &dropped_rows, + )); + try testing.expectEqual(@as(usize, 0), dropped_rows); + while (decoder_next(dropped_decoder) == .success) {} + try testing.expectEqual(Result.no_value, decoder_next(dropped_decoder)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/style.zig b/vendor/libghostty-vt/src/terminal/c/style.zig index 82729fa9..bea4d074 100644 --- a/vendor/libghostty-vt/src/terminal/c/style.zig +++ b/vendor/libghostty-vt/src/terminal/c/style.zig @@ -25,20 +25,32 @@ pub const Color = extern struct { tag: ColorTag, value: ColorValue, + // fromColor converts the tag as a plain integer, which requires + // the internal and C tag values to line up. + comptime { + const Tag = std.meta.Tag(style.Style.Color); + for (@typeInfo(Tag).@"enum".fields) |f| { + assert(f.value == @intFromEnum(@field(ColorTag, f.name))); + } + } + pub fn fromColor(c: style.Style.Color) Color { - return switch (c) { - .none => .{ - .tag = .none, - .value = .{ ._padding = 0 }, - }, - .palette => |idx| .{ - .tag = .palette, - .value = .{ .palette = idx }, - }, - .rgb => |rgb| .{ - .tag = .rgb, - .value = .{ .rgb = rgb.cval() }, - }, + // The value is built as a single integer rather than through + // the per-variant union fields: the C union layout puts + // .palette at byte 0 and .rgb at bytes 0-2, which is exactly + // the internal payload representation, so each variant is the + // payload zero-extended to the u64 union backing. This keeps + // the conversion to two stores (tag + value) per color, which + // matters for the per-cell style reads in the render state + // API. + const value: u64 = switch (c) { + .none => 0, + .palette => |idx| idx, + .rgb => |rgb| @as(u24, @bitCast(rgb)), + }; + return .{ + .tag = @enumFromInt(@intFromEnum(std.meta.activeTag(c))), + .value = .{ ._padding = value }, }; } }; @@ -59,27 +71,83 @@ pub const Style = extern struct { overline: bool, underline: c_int, - pub fn fromStyle(s: style.Style) Style { - return .{ - .fg_color = .fromColor(s.fg_color), - .bg_color = .fromColor(s.bg_color), - .underline_color = .fromColor(s.underline_color), - .bold = s.flags.bold, - .italic = s.flags.italic, - .faint = s.flags.faint, - .blink = s.flags.blink, - .inverse = s.flags.inverse, - .invisible = s.flags.invisible, - .strikethrough = s.flags.strikethrough, - .overline = s.flags.overline, - .underline = @intFromEnum(s.flags.underline), + /// The default (empty) style in C representation. C + pub const default: Style = .{ + .fg_color = .{ .tag = .none, .value = .{ ._padding = 0 } }, + .bg_color = .{ .tag = .none, .value = .{ ._padding = 0 } }, + .underline_color = .{ .tag = .none, .value = .{ ._padding = 0 } }, + .bold = false, + .italic = false, + .faint = false, + .blink = false, + .inverse = false, + .invisible = false, + .strikethrough = false, + .overline = false, + .underline = 0, + }; + + // fromStyle writes the eight bool fields as one 8-byte store, + // which requires them to be consecutive and to match the low + // eight flag bits in order. + comptime { + const flag_names = [8][:0]const u8{ + "bold", "italic", "faint", "blink", + "inverse", "invisible", "strikethrough", "overline", }; + const base = @offsetOf(Style, "bold"); + for (flag_names, 0..) |name, i| { + assert(@offsetOf(Style, name) == base + i); + assert(@bitOffsetOf(@FieldType(style.Style, "flags"), name) == i); + } + } + + /// Write the C representation of the given style directly through + /// the out pointer. The hot per-cell style read in the render + /// state API uses this rather than `out.* = fromStyle(s)`: the + /// by-value form materializes a stack temporary plus a + /// @sizeOf(Style)-byte copy that LLVM does not elide. + pub fn write(s: style.Style, out: *Style) void { + out.size = @sizeOf(Style); + out.fg_color = .fromColor(s.fg_color); + out.bg_color = .fromColor(s.bg_color); + out.underline_color = .fromColor(s.underline_color); + + // I know this looks scary, but this results in truly measurable + // performance improvements due to how often styles are written + // especially in render loops. We vectorize our 8-bit to 8-byte + // write. + // + // We have to align(1) because we're ptrCasting a u8 pointer. + @as(*align(1) u64, @ptrCast(&out.bold)).* = bytes: { + // Spread the low eight flag bits (the eight bool fields, in + // order) into one byte each and write them with a single + // 8-byte store. + const flag_bits: u8 = @truncate(@as(u16, @bitCast(s.flags))); + const masks: @Vector(8, u8) = .{ 1, 2, 4, 8, 16, 32, 64, 128 }; + const hits = (@as(@Vector(8, u8), @splat(flag_bits)) & masks) == masks; + const bytes: @Vector(8, u8) = @select( + u8, + hits, + @as(@Vector(8, u8), @splat(1)), + @as(@Vector(8, u8), @splat(0)), + ); + break :bytes @bitCast(bytes); + }; + + out.underline = @intFromEnum(s.flags.underline); + } + + pub fn fromStyle(s: style.Style) Style { + var result: Style = undefined; + write(s, &result); + return result; } }; /// Returns the default style. pub fn default_style(result: *Style) callconv(lib.calling_conv) void { - result.* = .fromStyle(.{}); + result.* = .default; assert(result.size == @sizeOf(Style)); } diff --git a/vendor/libghostty-vt/src/terminal/c/sys.zig b/vendor/libghostty-vt/src/terminal/c/sys.zig index c4b2b17f..f622e8fd 100644 --- a/vendor/libghostty-vt/src/terminal/c/sys.zig +++ b/vendor/libghostty-vt/src/terminal/c/sys.zig @@ -3,6 +3,7 @@ const builtin = @import("builtin"); const lib = @import("../lib.zig"); const CAllocator = lib.alloc.Allocator; const terminal_sys = @import("../sys.zig"); +const stderr = @import("../../os/stderr.zig"); const Result = @import("result.zig").Result; /// C: GhosttySysImage @@ -22,6 +23,13 @@ pub const DecodePngFn = *const fn ( *Image, ) callconv(lib.calling_conv) bool; +/// C: GhosttySysRandomSecureFn +pub const RandomSecureFn = *const fn ( + ?*anyopaque, + [*]u8, + usize, +) callconv(lib.calling_conv) bool; + /// C: GhosttySysLogLevel pub const LogLevel = enum(c_int) { @"error" = 0, @@ -54,12 +62,14 @@ pub const Option = enum(c_int) { userdata = 0, decode_png = 1, log = 2, + random_secure = 3, pub fn InType(comptime self: Option) type { return switch (self) { .userdata => ?*const anyopaque, .decode_png => ?DecodePngFn, .log => ?LogFn, + .random_secure => ?RandomSecureFn, }; } }; @@ -70,6 +80,7 @@ const Global = struct { userdata: ?*anyopaque = null, decode_png: ?DecodePngFn = null, log: ?LogFn = null, + random_secure: ?RandomSecureFn = null, }; /// Global state for the C sys interface. @@ -86,7 +97,7 @@ fn decodePngWrapper( const c_alloc = CAllocator.fromZig(&alloc); var out: Image = undefined; - if (!func(global.userdata, &c_alloc, data.ptr, data.len, &out)) return error.InvalidData; + if (!func(global.userdata, &c_alloc, lib.String.init(data).ptr, data.len, &out)) return error.InvalidData; const result_data = out.data orelse return error.InvalidData; @@ -97,12 +108,18 @@ fn decodePngWrapper( }; } +/// Zig-compatible wrapper that calls through to the stored C callback. +fn randomSecureWrapper(buffer: []u8) terminal_sys.RandomSecureError!void { + const func = global.random_secure orelse return error.EntropyUnavailable; + if (!func(global.userdata, buffer.ptr, buffer.len)) return error.EntropyUnavailable; +} + pub fn set( option: Option, value: ?*const anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + _ = std.enums.fromInt(Option, @intFromEnum(option)) orelse { return .invalid_value; }; } @@ -126,6 +143,10 @@ fn setTyped( terminal_sys.decode_png = if (value != null) &decodePngWrapper else null; }, .log => global.log = value, + .random_secure => { + global.random_secure = value; + terminal_sys.random_secure = if (value != null) &randomSecureWrapper else null; + }, } return .success; } @@ -146,37 +167,30 @@ fn emitLog(level: LogLevel, scope: []const u8, message: []const u8) void { /// Emits logs in chunks. Almost all logs will be less than the chunk size /// but this allows emitting larger logs without heap allocation. const LogEmitter = struct { + const buffer_size = 2048; + c_level: LogLevel, scope_text: []const u8, - buf: [2048]u8 = undefined, - pos: usize = 0, - - fn write(self: *@This(), bytes: []const u8) error{}!usize { - var remaining = bytes; - while (remaining.len > 0) { - const space = self.buf.len - self.pos; - if (space == 0) { - self.flush(); - continue; - } - - const n = @min(remaining.len, space); - @memcpy(self.buf[self.pos..][0..n], remaining[0..n]); - self.pos += n; - remaining = remaining[n..]; - } + writer: std.Io.Writer, - return bytes.len; - } - - fn flush(self: *@This()) void { - if (self.pos == 0) return; - emitLog( - self.c_level, - self.scope_text, - self.buf[0..self.pos], - ); - self.pos = 0; + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + switch (data.len) { + 0 => unreachable, + 1 => if (splat == 0) return 0, + else => {}, + } + const self: *@This() = @fieldParentPtr("writer", w); + if (w.end > 0) { + emitLog( + self.c_level, + self.scope_text, + w.buffer[0..w.end], + ); + } + const len: usize = @min(data[0].len, w.buffer.len); + @memcpy(w.buffer[0..len], data[0][0..len]); + w.end = len; + return len; } }; @@ -197,18 +211,20 @@ pub fn logFn( const scope_text: []const u8 = if (scope == .default) "" else @tagName(scope); const c_level = LogLevel.fromStd(level); - var ctx: LogEmitter = .{ + var log_emitter_buffer: [LogEmitter.buffer_size]u8 = undefined; + var log_emitter: LogEmitter = .{ .c_level = c_level, .scope_text = scope_text, + .writer = .{ + .buffer = &log_emitter_buffer, + .vtable = &.{ + .drain = LogEmitter.drain, + }, + }, }; - const writer: std.io.GenericWriter( - *LogEmitter, - error{}, - LogEmitter.write, - ) = .{ .context = &ctx }; - - nosuspend writer.print(format, args) catch {}; - ctx.flush(); + + nosuspend log_emitter.writer.print(format, args) catch {}; + log_emitter.writer.flush() catch {}; } /// Built-in log callback that writes to stderr. @@ -216,8 +232,12 @@ pub fn logFn( /// Formats each message as "[level](scope): message\n". Can be passed /// directly to ghostty_sys_set(GHOSTTY_SYS_OPT_LOG, &ghostty_sys_log_stderr). /// -/// Uses std.debug.lockStderrWriter for thread-safe, mutex-protected output. -/// On freestanding/wasm targets this is a no-op (no stderr available). +/// Each log line is emitted with a single raw write to stderr, which keeps +/// concurrent log lines from interleaving. We intentionally avoid +/// `std.debug.lockStderr` because it routes through `std.Options.debug_io` +/// and would keep the entire `std.Io.Threaded` vtable alive in the binary +/// (see `os/stderr.zig`). On freestanding/wasm targets this is a no-op +/// (no stderr available). pub fn logStderr( _: ?*anyopaque, level: LogLevel, @@ -238,16 +258,32 @@ pub fn logStderr( .debug => "debug", }; - var buffer: [64]u8 = undefined; - const writer = std.debug.lockStderrWriter(&buffer); - defer std.debug.unlockStderrWriter(); - nosuspend { - if (scope.len > 0) { - writer.print("[{s}]({s}): {s}\n", .{ level_text, scope, message }) catch {}; - } else { - writer.print("[{s}]: {s}\n", .{ level_text, message }) catch {}; - } + // Large enough for a full logFn chunk plus the level/scope prefix. + var buffer: [LogEmitter.buffer_size + 128]u8 = undefined; + const line: ?[]const u8 = if (scope.len > 0) + std.fmt.bufPrint(&buffer, "[{s}]({s}): {s}\n", .{ level_text, scope, message }) catch null + else + std.fmt.bufPrint(&buffer, "[{s}]: {s}\n", .{ level_text, message }) catch null; + if (line) |v| { + stderr.write(v); + return; + } + + // The line didn't fit in our buffer (an embedder called us directly + // with a very large message). Fall back to writing the pieces + // separately; interleaving with other threads is possible here but + // this is a best-effort diagnostic path. + stderr.write("["); + stderr.write(level_text); + stderr.write("]"); + if (scope.len > 0) { + stderr.write("("); + stderr.write(scope); + stderr.write(")"); } + stderr.write(": "); + stderr.write(message); + stderr.write("\n"); } test "set decode_png with null clears" { diff --git a/vendor/libghostty-vt/src/terminal/c/terminal.zig b/vendor/libghostty-vt/src/terminal/c/terminal.zig index 0f95fcf1..73097573 100644 --- a/vendor/libghostty-vt/src/terminal/c/terminal.zig +++ b/vendor/libghostty-vt/src/terminal/c/terminal.zig @@ -1,9 +1,12 @@ +const builtin = @import("builtin"); const std = @import("std"); const testing = std.testing; const build_options = @import("terminal_options"); const lib = @import("../lib.zig"); const CAllocator = lib.alloc.Allocator; pub const ZigTerminal = @import("../Terminal.zig"); +const Action = @import("../stream.zig").Action; +const osc = @import("../osc.zig"); const Stream = @import("../stream_terminal.zig").Stream; const Screen = @import("../Screen.zig"); const ScreenSet = @import("../ScreenSet.zig"); @@ -21,24 +24,73 @@ const cell_c = @import("cell.zig"); const row_c = @import("row.zig"); const grid_ref_c = @import("grid_ref.zig"); const grid_ref_tracked_c = @import("grid_ref_tracked.zig"); +const search_c = @import("search.zig"); const selection_c = @import("selection.zig"); const style_c = @import("style.zig"); const color = @import("../color.zig"); const clipboard = @import("../clipboard.zig"); +const kitty_clipboard = @import("../kitty/clipboard.zig"); +const c_io = @import("io.zig"); +const snapshot_core = @import("../snapshot/main.zig"); const Result = @import("result.zig").Result; +const assert = @import("../../quirks.zig").inlineAssert; const Handler = @import("../stream_terminal.zig").Handler; +const max_path_bytes = if (builtin.os.tag == .freestanding) 4096 else std.fs.max_path_bytes; + const log = std.log.scoped(.terminal_c); +/// C terminals do not retain replay bytes unless the embedding application +/// opts in through `GHOSTTY_TERMINAL_OPT_CONTINUATION_MAX_BYTES`. +pub const default_continuation_max_bytes: usize = 0; + +/// Owns the `std.Io` implementation retained by every C terminal. +/// +/// Snapshot decoding creates this before the native terminal exists and +/// transfers it into the final C wrapper after READY. +/// +/// This is TinyIo on every target: it is stateless and supports exactly +/// the operations the terminal needs at a fraction of the code size of +/// `std.Io.Threaded` (see lib/TinyIo.zig), on POSIX and Windows alike. +/// On the remaining targets (e.g. freestanding wasm) TinyIo degrades to +/// `std.Io.failing`, which is correct: they have no filesystem. +pub const Io = struct { + impl: lib.TinyIo, + + pub const init: Io = .{ .impl = .init }; + + /// Return the value passed to native terminal construction and decoding. + pub fn io(self: Io) std.Io { + return self.impl.io(); + } +}; + /// Wrapper around ZigTerminal that tracks additional state for C API usage, /// such as the persistent VT stream needed to handle escape sequences split /// across multiple vt_write calls. const TerminalWrapper = struct { terminal: *ZigTerminal, + /// C construction has no I/O argument, so the wrapper retains the owner + /// created by `new` or transferred from snapshot decoding until `free`. + io: Io, + /// Allocator-owned copy of the temporary directory path for some + /// operations (e.g. kitty graphics). This is only allocated once the + /// embedder sets the option. + tmp_dir_path: ?[]u8 = null, + /// The terminfo name reported for XTGETTCAP "TN". The stream handler holds + /// a slice into this. + terminfo_name_buf: [Handler.max_terminfo_name_bytes]u8, stream: Stream, effects: Effects = .{}, tracked_grid_refs: std.AutoArrayHashMapUnmanaged(*grid_ref_tracked_c.TrackedGridRef, void) = .{}, + searches: std.AutoArrayHashMapUnmanaged(*search_c.SearchWrapper, void) = .{}, + + /// Fetches a `TerminalWrapper` reference from a `Handler`. + fn fromHandler(handler: *Handler) *TerminalWrapper { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + return @alignCast(@fieldParentPtr("stream", stream_ptr)); + } }; /// A single MIME representation in a clipboard write. @@ -50,6 +102,8 @@ pub const ClipboardContent = extern struct { }; /// A protocol-neutral request to replace or clear clipboard contents. +/// The embedder answers by calling `reply` with the request before the +/// callback returns. /// /// C: GhosttyClipboardWrite pub const ClipboardWrite = extern struct { @@ -57,23 +111,152 @@ pub const ClipboardWrite = extern struct { location: clipboard.Location, contents: ?[*]const ClipboardContent, contents_len: usize, + name: lib.String, + granted: bool, + can_remember: bool, + /// Terminal-owned reply state; opaque to the embedder. + ctx: *const anyopaque, + reply: ClipboardWriteReplyFn, +}; + +/// The reply to a clipboard write request. +/// +/// C: GhosttyClipboardWriteReply +pub const ClipboardWriteReply = extern struct { + size: usize, + result: clipboard.Write.Status, + remember: bool, +}; + +/// C function pointer type for replying to a clipboard write. +/// +/// C: GhosttyClipboardWriteReplyFn +pub const ClipboardWriteReplyFn = *const fn (*const ClipboardWrite, *const ClipboardWriteReply) callconv(lib.calling_conv) void; + +/// The reply to a clipboard read request. +/// +/// C: GhosttyClipboardReadReply +pub const ClipboardReadReply = extern struct { + size: usize, + result: clipboard.Read.Status, + contents: ?[*]const ClipboardContent, + contents_len: usize, + available: ?[*]const lib.String, + available_len: usize, + remember: bool, +}; + +/// A synchronous request to read clipboard contents. The embedder answers +/// by calling `reply` with the request before the callback returns. +/// +/// C: GhosttyClipboardRead +pub const ClipboardRead = extern struct { + size: usize, + location: clipboard.Location, + mimes: ?[*]const lib.String, + mimes_len: usize, + list: bool, + name: lib.String, + granted: bool, + can_remember: bool, + /// Terminal-owned reply state; opaque to the embedder. + ctx: *const anyopaque, + reply: ClipboardReadReplyFn, +}; + +/// C function pointer type for replying to a clipboard read. +/// +/// C: GhosttyClipboardReadReplyFn +pub const ClipboardReadReplyFn = *const fn (*const ClipboardRead, *const ClipboardReadReply) callconv(lib.calling_conv) void; + +/// A request to show a desktop notification. +/// +/// C: GhosttyTerminalDesktopNotification +pub const DesktopNotification = extern struct { + size: usize, + title: lib.String, + body: lib.String, +}; + +/// C: GhosttyTerminalProgressState +pub const ProgressState = osc.Command.ProgressReport.State; + +/// A progress report emitted by the running program. +/// +/// C: GhosttyTerminalProgressReport +pub const ProgressReport = extern struct { + size: usize, + state: ProgressState, + progress: i8, }; -/// C callback state for terminal effects. Trampolines are always -/// installed on the stream handler; they check these fields and -/// no-op when the corresponding callback is null. +/// A borrowed unsupported string sequence. +/// +/// C: GhosttyTerminalUnknownStringSequence +pub const UnknownStringSequence = extern struct { + truncated: bool, + content: lib.String, +}; + +/// An unsupported terminal sequence reported to the C callback. +/// +/// C: GhosttyTerminalUnknownSequence +pub const UnknownSequence = union(Tag) { + apc: UnknownStringSequence, + + /// C: GhosttyTerminalUnknownSequenceTag + pub const Tag = lib.Enum(lib.target, &.{"apc"}); + + const c_union = lib.TaggedUnion( + lib.target, + @This(), + // A future borrowed CSI payload may need parameter, separator, and + // intermediate arrays. Reserve 128 bytes so that representation and + // other structured sequence types can be added without an ABI break. + .{ .padding = [16]u64 }, + ); + pub const C = c_union.C; + pub const CValue = c_union.CValue; + pub const cval = c_union.cval; +}; + +/// A terminal mode and boolean value used for mode configuration. +/// +/// C: GhosttyTerminalModeConfig +pub const ModeConfig = extern struct { + mode: modes.ModeTag.Backing, + value: bool, + + fn toMode(self: ModeConfig) ?modes.Mode { + const tag: modes.ModeTag = @bitCast(self.mode); + return modes.modeFromInt(tag.value, tag.ansi); + } +}; + +/// C callback state for terminal effects. Most trampolines are always +/// installed on the stream handler; they check these fields and no-op when +/// the corresponding callback is null. The unknown-sequence and +/// clipboard trampolines are installed dynamically to preserve their +/// null fast paths (for clipboard_write, a null Zig-level effect makes +/// Kitty clipboard writes fail up front instead of spooling a +/// transaction that can never commit; for clipboard_read it keeps +/// reads denied). const Effects = struct { userdata: ?*anyopaque = null, write_pty: ?WritePtyFn = null, bell: ?BellFn = null, color_scheme: ?ColorSchemeFn = null, + desktop_notification: ?DesktopNotificationFn = null, device_attributes_cb: ?DeviceAttributesFn = null, enquiry: ?EnquiryFn = null, xtversion: ?XtversionFn = null, title_changed: ?TitleChangedFn = null, pwd_changed: ?PwdChangedFn = null, + progress_report: ?ProgressReportFn = null, size_cb: ?SizeFn = null, clipboard_write: ?ClipboardWriteFn = null, + clipboard_read: ?ClipboardReadFn = null, + unknown_sequence: ?UnknownSequenceFn = null, /// Scratch buffer for DA1 feature codes. The device attributes /// trampoline converts C feature codes into this buffer and returns @@ -105,8 +288,18 @@ const Effects = struct { pub const XtversionFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) lib.String; /// C function pointer type for the clipboard_write callback. The request - /// and its contents are borrowed and only valid for the callback duration. - pub const ClipboardWriteFn = *const fn (Terminal, ?*anyopaque, *const ClipboardWrite) callconv(lib.calling_conv) clipboard.WriteResult; + /// is borrowed for the callback duration and must be answered through + /// its reply function before the callback returns. + pub const ClipboardWriteFn = *const fn (Terminal, ?*anyopaque, *const ClipboardWrite) callconv(lib.calling_conv) void; + + /// C function pointer type for the clipboard_read callback. The request + /// is borrowed for the callback duration and must be answered through + /// its reply function before the callback returns. + pub const ClipboardReadFn = *const fn (Terminal, ?*anyopaque, *const ClipboardRead) callconv(lib.calling_conv) void; + + /// C function pointer type for the desktop_notification callback. The + /// request and its strings are borrowed for the callback duration. + pub const DesktopNotificationFn = *const fn (Terminal, ?*anyopaque, *const DesktopNotification) callconv(lib.calling_conv) void; /// C function pointer type for the title_changed callback. pub const TitleChangedFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) void; @@ -114,9 +307,17 @@ const Effects = struct { /// C function pointer type for the pwd_changed callback. pub const PwdChangedFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) void; - /// C function pointer type for the size callback. - /// Returns true and fills out_size if size is available, - /// or returns false to silently ignore the query. + /// C function pointer type for the progress_report callback. + pub const ProgressReportFn = *const fn (Terminal, ?*anyopaque, *const ProgressReport) callconv(lib.calling_conv) void; + + /// C function pointer type for the unknown_sequence callback. The request + /// and its content are borrowed for the callback duration. + pub const UnknownSequenceFn = *const fn (Terminal, ?*anyopaque, *const UnknownSequence.C) callconv(lib.calling_conv) void; + + /// C function pointer type for the size callback. Used by XTWINOPS queries + /// and VT-driven mode 2048 enable reports. Returns true and fills out_size + /// if size is available, or false to suppress the XTWINOPS response or + /// mode 2048 report. pub const SizeFn = *const fn (Terminal, ?*anyopaque, *size_report.Size) callconv(lib.calling_conv) bool; /// C function pointer type for the device_attributes callback. @@ -148,24 +349,27 @@ const Effects = struct { }; }; - fn writePtyTrampoline(handler: *Handler, data: [:0]const u8) void { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + fn writePtyTrampoline(handler: *Handler, data: []const u8) void { + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.write_pty orelse return; func(@ptrCast(wrapper), wrapper.effects.userdata, data.ptr, data.len); } fn bellTrampoline(handler: *Handler) void { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.bell orelse return; func(@ptrCast(wrapper), wrapper.effects.userdata); } - fn clipboardWriteTrampoline(handler: *Handler, write: clipboard.Write) clipboard.WriteResult { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); - const func = wrapper.effects.clipboard_write orelse return .unsupported; + /// Opaque context behind ClipboardWrite.ctx for the reply trampoline. + const ClipboardWriteCtx = struct { + write: clipboard.Write, + }; + + fn clipboardWriteTrampoline(handler: *Handler, write: clipboard.Write) void { + const wrapper = TerminalWrapper.fromHandler(handler); + const func = wrapper.effects.clipboard_write orelse + return write.reply(.unsupported); // Most protocols currently produce one representation, so keep that // path allocation-free while supporting arbitrary multi-MIME writes. @@ -174,35 +378,158 @@ const Effects = struct { stack_contents[0..write.contents.len] else wrapper.terminal.gpa().alloc(ClipboardContent, write.contents.len) catch - return .io_error; + return write.reply(.io_error); defer if (write.contents.len > stack_contents.len) wrapper.terminal.gpa().free(contents); for (contents, write.contents) |*c_content, content| { c_content.* = .{ - .mime = .{ - .ptr = content.mime.ptr, - .len = content.mime.len, - }, - .data = .{ - .ptr = content.data.ptr, - .len = content.data.len, - }, + .mime = .init(content.mime), + .data = .init(content.data), }; } + const ctx: ClipboardWriteCtx = .{ .write = write }; const request: ClipboardWrite = .{ .size = @sizeOf(ClipboardWrite), .location = write.location, .contents = if (contents.len > 0) contents.ptr else null, .contents_len = contents.len, + .name = .init(write.name), + .granted = write.granted, + .can_remember = write.can_remember, + .ctx = &ctx, + .reply = &clipboardWriteReplyTrampoline, + }; + func(@ptrCast(wrapper), wrapper.effects.userdata, &request); + } + + fn clipboardWriteReplyTrampoline( + request: *const ClipboardWrite, + reply: *const ClipboardWriteReply, + ) callconv(lib.calling_conv) void { + const ctx: *const ClipboardWriteCtx = @ptrCast(@alignCast(request.ctx)); + const write = ctx.write; + switch (reply.result) { + .success => write.reply(.{ .success = .{ .remember = reply.remember } }), + .denied => write.reply(.denied), + .busy => write.reply(.busy), + .invalid_data => write.reply(.invalid_data), + .io_error => write.reply(.io_error), + .unsupported, _ => write.reply(.unsupported), + } + } + + /// Opaque context behind ClipboardRead.ctx for the reply trampoline. + const ClipboardReadCtx = struct { + read: clipboard.Read, + wrapper: *TerminalWrapper, + }; + + fn clipboardReadTrampoline(handler: *Handler, read: clipboard.Read) void { + const wrapper = TerminalWrapper.fromHandler(handler); + const func = wrapper.effects.clipboard_read orelse return; + + // Requests carry a handful of MIME types, so keep the common case + // allocation-free. On OOM the request goes unanswered and the + // handler replies with an empty clipboard. + var sfa = std.heap.stackFallback(128, wrapper.terminal.gpa()); + const alloc = sfa.get(); + const mimes = alloc.alloc(lib.String, read.mimes.len) catch { + log.warn("out of memory converting clipboard read request", .{}); + return; + }; + defer alloc.free(mimes); + for (mimes, read.mimes) |*c_mime, mime| c_mime.* = .init(mime); + + const ctx: ClipboardReadCtx = .{ .read = read, .wrapper = wrapper }; + const request: ClipboardRead = .{ + .size = @sizeOf(ClipboardRead), + .location = read.location, + .mimes = if (mimes.len > 0) mimes.ptr else null, + .mimes_len = mimes.len, + .list = read.list, + .name = .init(read.name), + .granted = read.granted, + .can_remember = read.can_remember, + .ctx = &ctx, + .reply = &clipboardReadReplyTrampoline, + }; + func(@ptrCast(wrapper), wrapper.effects.userdata, &request); + } + + fn clipboardReadReplyTrampoline( + request: *const ClipboardRead, + reply: *const ClipboardReadReply, + ) callconv(lib.calling_conv) void { + const ctx: *const ClipboardReadCtx = @ptrCast(@alignCast(request.ctx)); + const read = ctx.read; + switch (reply.result) { + .success => {}, + .denied => return read.reply(.denied), + .busy => return read.reply(.busy), + .io_error => return read.reply(.io_error), + .unsupported, _ => return read.reply(.unsupported), + } + + const c_contents: []const ClipboardContent = if (reply.contents) |ptr| + ptr[0..reply.contents_len] + else + &.{}; + const c_available: []const lib.String = if (reply.available) |ptr| + ptr[0..reply.available_len] + else + &.{}; + + // Most replies carry one representation, so keep that path + // allocation-free while supporting arbitrary multi-MIME replies. + // On OOM we don't reply and the handler answers with an empty + // clipboard. + var sfa = std.heap.stackFallback(256, ctx.wrapper.terminal.gpa()); + const alloc = sfa.get(); + const contents = alloc.alloc(clipboard.Content, c_contents.len) catch { + log.warn("out of memory converting clipboard read reply", .{}); + return; }; - return func(@ptrCast(wrapper), wrapper.effects.userdata, &request); + defer alloc.free(contents); + for (contents, c_contents) |*content, c_content| { + content.* = .{ + .mime = c_content.mime.ptr[0..c_content.mime.len], + .data = c_content.data.ptr[0..c_content.data.len], + }; + } + const available = alloc.alloc([]const u8, c_available.len) catch { + log.warn("out of memory converting clipboard read reply", .{}); + return; + }; + defer alloc.free(available); + for (available, c_available) |*mime, c_mime| { + mime.* = c_mime.ptr[0..c_mime.len]; + } + + read.reply(.{ .success = .{ + .contents = contents, + .available = available, + .remember = reply.remember, + } }); + } + + fn desktopNotificationTrampoline( + handler: *Handler, + notification: Action.ShowDesktopNotification, + ) void { + const wrapper = TerminalWrapper.fromHandler(handler); + const func = wrapper.effects.desktop_notification orelse return; + const request: DesktopNotification = .{ + .size = @sizeOf(DesktopNotification), + .title = .init(notification.title), + .body = .init(notification.body), + }; + func(@ptrCast(wrapper), wrapper.effects.userdata, &request); } fn colorSchemeTrampoline(handler: *Handler) ?device_status.ColorScheme { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.color_scheme orelse return null; var scheme: device_status.ColorScheme = undefined; if (func(@ptrCast(wrapper), wrapper.effects.userdata, &scheme)) return scheme; @@ -210,8 +537,7 @@ const Effects = struct { } fn deviceAttributesTrampoline(handler: *Handler) device_attributes.Attributes { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.device_attributes_cb orelse return .{}; // Get our attributes from the callback. @@ -241,8 +567,7 @@ const Effects = struct { } fn enquiryTrampoline(handler: *Handler) []const u8 { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.enquiry orelse return ""; const result = func(@ptrCast(wrapper), wrapper.effects.userdata); if (result.len == 0) return ""; @@ -250,8 +575,7 @@ const Effects = struct { } fn xtversionTrampoline(handler: *Handler) []const u8 { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.xtversion orelse return ""; const result = func(@ptrCast(wrapper), wrapper.effects.userdata); if (result.len == 0) return ""; @@ -259,22 +583,50 @@ const Effects = struct { } fn titleChangedTrampoline(handler: *Handler) void { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.title_changed orelse return; func(@ptrCast(wrapper), wrapper.effects.userdata); } fn pwdChangedTrampoline(handler: *Handler) void { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.pwd_changed orelse return; func(@ptrCast(wrapper), wrapper.effects.userdata); } + fn progressReportTrampoline( + handler: *Handler, + report: osc.Command.ProgressReport, + ) void { + const wrapper = TerminalWrapper.fromHandler(handler); + const func = wrapper.effects.progress_report orelse return; + const c_report: ProgressReport = .{ + .size = @sizeOf(ProgressReport), + .state = @enumFromInt(@intFromEnum(report.state)), + .progress = if (report.progress) |value| @intCast(value) else -1, + }; + func(@ptrCast(wrapper), wrapper.effects.userdata, &c_report); + } + + fn unknownSequenceTrampoline( + handler: *Handler, + sequence: Handler.UnknownSequence, + ) void { + const wrapper = TerminalWrapper.fromHandler(handler); + const func = wrapper.effects.unknown_sequence orelse return; + const value = UnknownSequence.cval(switch (sequence) { + .apc => |apc_value| .{ + .apc = .{ + .truncated = apc_value.truncated, + .content = .init(apc_value.content), + }, + }, + }); + func(@ptrCast(wrapper), wrapper.effects.userdata, &value); + } + fn sizeTrampoline(handler: *Handler) ?size_report.Size { - const stream_ptr: *Stream = @fieldParentPtr("handler", handler); - const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const wrapper = TerminalWrapper.fromHandler(handler); const func = wrapper.effects.size_cb orelse return null; var s: size_report.Size = undefined; if (func(@ptrCast(wrapper), wrapper.effects.userdata, &s)) return s; @@ -295,13 +647,150 @@ pub fn zigTerminal(terminal_: Terminal) ?*ZigTerminal { return (terminal_ orelse return null).terminal; } -/// C: GhosttyTerminalOptions -pub const Options = extern struct { - cols: size.CellCountInt, - rows: size.CellCountInt, - max_scrollback: usize, +/// Attach the persistent C stream and I/O owner to a heap-stable terminal. +/// The caller retains ownership of both inputs if wrapper allocation fails. +fn wrap( + alloc: std.mem.Allocator, + t: *ZigTerminal, + io: Io, + continuation_max_bytes: usize, +) error{OutOfMemory}!Terminal { + const wrapper = alloc.create(TerminalWrapper) catch + return error.OutOfMemory; + + // Trampolines are always installed so setting C callbacks later takes + // effect immediately. + var handler: Stream.Handler = t.vtHandler(); + handler.effects = .{ + .write_pty = &Effects.writePtyTrampoline, + .bell = &Effects.bellTrampoline, + .color_scheme = &Effects.colorSchemeTrampoline, + .desktop_notification = &Effects.desktopNotificationTrampoline, + .drag_and_drop = null, + .device_attributes = &Effects.deviceAttributesTrampoline, + .enquiry = &Effects.enquiryTrampoline, + .xtversion = &Effects.xtversionTrampoline, + .title_changed = &Effects.titleChangedTrampoline, + .pwd_changed = &Effects.pwdChangedTrampoline, + .progress_report = &Effects.progressReportTrampoline, + .size = &Effects.sizeTrampoline, + + // Installed dynamically when the callback is set; see Effects. + .clipboard_write = null, + .clipboard_read = null, + }; + + wrapper.* = .{ + .terminal = t, + .io = io, + .terminfo_name_buf = undefined, + .stream = Stream.init(.{ + .allocator = alloc, + .handler = handler, + .continuation_max_bytes = continuation_max_bytes, + }), + }; + return wrapper; +} + +pub const RestoreContinuationError = error{ + OutOfMemory, + ContinuationDisabled, + ContinuationUnavailable, + InvalidContinuation, +}; + +/// Replay a decoded continuation exactly once into a newly created C terminal +/// and verify that the persistent stream exports the identical canonical +/// bytes. The terminal remains valid on error and may be freed normally. +pub fn restoreContinuation( + terminal_: Terminal, + continuation: []const u8, +) RestoreContinuationError!void { + const wrapper = terminal_ orelse return error.InvalidContinuation; + if (continuation.len > 0) wrapper.stream.nextSlice(continuation); + + var exported: std.Io.Writer.Allocating = .init(wrapper.terminal.gpa()); + defer exported.deinit(); + wrapper.stream.writeContinuation(&exported.writer) catch |err| switch (err) { + error.WriteFailed => return error.OutOfMemory, + error.ContinuationDisabled => return error.ContinuationDisabled, + error.ContinuationUnavailable => return error.ContinuationUnavailable, + }; + if (!std.mem.eql(u8, continuation, exported.written())) { + return error.InvalidContinuation; + } +} + +pub const FromDecodedError = error{ + OutOfMemory, + InvalidContinuation, }; +/// Transfer a core snapshot result into a caller-owned C terminal. +/// +/// `io` is the owner the decoded terminal was built with and is retained +/// by the returned wrapper. The decoded terminal is transferred only +/// after its final heap address has been allocated; its +/// continuation remains in `decoded` and is replayed before returning. +/// `continuation_max_bytes` selects the returned terminal's tracking policy: +/// zero uses a temporary exact-size tracker and restores the ordinary C +/// default before returning, while a nonzero value leaves tracking enabled +/// with that limit. +pub fn fromDecoded( + alloc: std.mem.Allocator, + io: Io, + decoded: *snapshot_core.Decoded, + continuation_max_bytes: usize, +) FromDecodedError!Terminal { + const native = alloc.create(ZigTerminal) catch + return error.OutOfMemory; + native.* = decoded.toOwned(); + + const continuation = switch (decoded.continuation) { + .ground => "", + .bytes => |bytes| bytes, + }; + assert(continuation_max_bytes == 0 or + continuation.len <= continuation_max_bytes); + + // Without opt-in retention, non-ground state needs tracking only long + // enough to verify that replay reconstructed the exact canonical + // continuation. With retention, even ground state needs a tracker so its + // continuation can be exported successfully as an empty slice. + const tracker_max_bytes = if (continuation_max_bytes > 0) + continuation_max_bytes + else + continuation.len; + const terminal = wrap(alloc, native, io, tracker_max_bytes) catch |err| { + native.deinit(alloc); + alloc.destroy(native); + return err; + }; + errdefer free(terminal); + + if (continuation.len > 0) { + restoreContinuation(terminal, continuation) catch |err| return switch (err) { + // The decoded bytes fit this fresh tracker's cap, so losing them + // while replaying can only be an allocation failure. + error.OutOfMemory, + error.ContinuationUnavailable, + => error.OutOfMemory, + error.ContinuationDisabled, + error.InvalidContinuation, + => error.InvalidContinuation, + }; + } + + // Unless the decoder opted into retention, restore the same disabled + // tracking default used by newly created C terminals. Disabling tracking + // does not alter the parser or UTF-8 state reconstructed above. + if (continuation_max_bytes == 0) { + setContinuationMaxBytes(terminal.?, default_continuation_max_bytes); + } + return terminal; +} + const NewError = error{ InvalidValue, OutOfMemory, @@ -310,9 +799,10 @@ const NewError = error{ pub fn new( alloc_: ?*const CAllocator, result: *Terminal, - opts: Options, + cols: size.CellCountInt, + rows: size.CellCountInt, ) callconv(lib.calling_conv) Result { - result.* = new_(alloc_, opts) catch |err| { + result.* = new_(alloc_, cols, rows) catch |err| { result.* = null; return switch (err) { error.InvalidValue => .invalid_value, @@ -325,26 +815,27 @@ pub fn new( fn new_( alloc_: ?*const CAllocator, - opts: Options, -) NewError!*TerminalWrapper { - if (opts.cols == 0 or opts.rows == 0) return error.InvalidValue; + cols: size.CellCountInt, + rows: size.CellCountInt, +) NewError!Terminal { + if (cols == 0 or rows == 0) return error.InvalidValue; const alloc = lib.alloc.default(alloc_); const t = alloc.create(ZigTerminal) catch return error.OutOfMemory; errdefer alloc.destroy(t); - const wrapper = alloc.create(TerminalWrapper) catch - return error.OutOfMemory; - errdefer alloc.destroy(wrapper); + const io: Io = .init; // Setup our terminal - t.* = try .init(alloc, .{ - .cols = opts.cols, - .rows = opts.rows, - .max_scrollback = opts.max_scrollback, - .default_modes = .{ .grapheme_cluster = true }, - }); + t.* = try .init( + io.io(), + alloc, + .{ + .cols = cols, + .rows = rows, + }, + ); errdefer t.deinit(alloc); // libghostty-vt embedders don't necessarily install Ghostty's shell @@ -352,28 +843,12 @@ fn new_( // Shells can still opt in with OSC 133;A;redraw=1. t.flags.shell_redraws_prompt = .false; - // Setup our stream with trampolines always installed so that - // setting C callbacks at any time takes effect immediately. - var handler: Stream.Handler = t.vtHandler(); - handler.effects = .{ - .write_pty = &Effects.writePtyTrampoline, - .bell = &Effects.bellTrampoline, - .color_scheme = &Effects.colorSchemeTrampoline, - .device_attributes = &Effects.deviceAttributesTrampoline, - .enquiry = &Effects.enquiryTrampoline, - .xtversion = &Effects.xtversionTrampoline, - .title_changed = &Effects.titleChangedTrampoline, - .pwd_changed = &Effects.pwdChangedTrampoline, - .size = &Effects.sizeTrampoline, - .clipboard_write = &Effects.clipboardWriteTrampoline, - }; - - wrapper.* = .{ - .terminal = t, - .stream = .initAlloc(alloc, handler), - }; - - return wrapper; + return try wrap( + alloc, + t, + io, + default_continuation_max_bytes, + ); } pub fn vt_write( @@ -385,6 +860,256 @@ pub fn vt_write( wrapper.stream.nextSlice(ptr[0..len]); } +pub fn vt_write_until_ground( + terminal_: Terminal, + ptr_: ?[*]const u8, + len: usize, + out_consumed_: ?*usize, +) callconv(lib.calling_conv) Result { + const out_consumed = out_consumed_ orelse return .invalid_value; + out_consumed.* = 0; + + const wrapper = terminal_ orelse return .invalid_value; + const input: []const u8 = if (ptr_) |ptr| + ptr[0..len] + else if (len == 0) + "" + else + return .invalid_value; + + if (wrapper.stream.nextSliceUntilGround(input)) |consumed| { + out_consumed.* = consumed; + return .success; + } + + out_consumed.* = len; + return .no_value; +} + +pub const ContinuationWriteError = error{ + InvalidValue, + WriteFailed, + ContinuationDisabled, + ContinuationUnavailable, +}; + +/// Write the exact replay-safe continuation for a C terminal to a Zig writer. +/// Snapshot encoding uses this helper so it can preflight continuation state +/// without converting its allocator or writer through the C ABI. +pub fn continuationWriteIo( + terminal_: Terminal, + writer: *std.Io.Writer, +) ContinuationWriteError!void { + // Keep handle validation here so the three public output forms and the + // snapshot encoder all use exactly the same continuation preflight. + const wrapper = terminal_ orelse return error.InvalidValue; + + // Stream owns the tracker and distinguishes disabled tracking from a + // tracker that lost bytes after allocation failure or limit overflow. + try wrapper.stream.writeContinuation(writer); +} + +pub const ContinuationAllocError = error{ + InvalidValue, + OutOfMemory, + ContinuationDisabled, + ContinuationUnavailable, +}; + +/// Return an allocator-owned copy of the terminal's replay-safe continuation. +/// The caller owns the returned slice and must free it with `alloc`. +/// +/// If `allow_untracked_ground` is true, disabled tracking is accepted only +/// when the stream is provably at ground and an owned empty slice is returned. +pub fn continuationAllocIo( + terminal_: Terminal, + alloc: std.mem.Allocator, + allow_untracked_ground: bool, +) ContinuationAllocError![]u8 { + const wrapper = terminal_ orelse return error.InvalidValue; + if (allow_untracked_ground and + wrapper.stream.continuation == null and + wrapper.stream.ground()) + { + return alloc.dupe(u8, "") catch error.OutOfMemory; + } + + // The allocating writer gives snapshot encoding and the public allocation + // API one common way to obtain an exact owned continuation. + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + + // A write failure from an Allocating writer can only be allocation failure; + // no external callback participates in this path. + continuationWriteIo(terminal_, &aw.writer) catch |err| switch (err) { + error.InvalidValue => return error.InvalidValue, + error.WriteFailed => return error.OutOfMemory, + error.ContinuationDisabled => return error.ContinuationDisabled, + error.ContinuationUnavailable => return error.ContinuationUnavailable, + }; + + // Transfer the buffer out before the deferred writer cleanup runs. + return aw.toOwnedSlice() catch error.OutOfMemory; +} + +/// Map errors that are intrinsic to continuation export. Public callback +/// failures receive finer classification in `continuation_write` below. +fn continuationErrorResult(err: ContinuationWriteError) Result { + return switch (err) { + error.InvalidValue => .invalid_value, + error.WriteFailed => .io_error, + error.ContinuationDisabled => .invalid_value, + error.ContinuationUnavailable => .invalid_value, + }; +} + +pub fn continuation_write( + terminal_: Terminal, + writer: c_io.Writer, +) callconv(lib.calling_conv) Result { + // Reject the missing callback before invoking the common helper so this is + // classified as a bad argument rather than a write failure. + if (writer.write == null) return .invalid_value; + + // The callback was validated above, so invalid_write can only mean output + // accounting overflow. Keep that distinct from callback rejection. + var buffer: [c_io.WriterAdapter.recommended_buffer_len]u8 = undefined; + var adapter: c_io.WriterAdapter = .initBuffered(writer, &buffer); + write: { + continuationWriteIo(terminal_, &adapter.interface) catch |err| switch (err) { + error.WriteFailed => break :write, + else => return continuationErrorResult(err), + }; + adapter.interface.flush() catch break :write; + return .success; + } + + if (adapter.invalid_write) return .limit_exceeded; + if (adapter.callback_failed) return .io_error; + return continuationErrorResult(error.WriteFailed); +} + +pub fn continuation_buf( + terminal_: Terminal, + out_: ?[*]u8, + out_len: usize, + out_written_: ?*usize, +) callconv(lib.calling_conv) Result { + const out_written = out_written_ orelse return .invalid_value; + // All failure paths leave deterministic output metadata. + out_written.* = 0; + if (out_ == null and out_len != 0) return .invalid_value; + + if (out_ == null) { + // A null/zero destination is the explicit size-query form. Discarding + // runs the real exporter, so disabled or unavailable tracking is still + // detected before a required length is reported. + var discarding: std.Io.Writer.Discarding = .init(&.{}); + continuationWriteIo(terminal_, &discarding.writer) catch |err| + return continuationErrorResult(err); + out_written.* = @intCast(discarding.count); + return .out_of_space; + } + + // Fixed writers report WriteFailed when capacity is exhausted. The stream + // exporter itself remains all-or-nothing from the API's perspective. + var writer: std.Io.Writer = .fixed(out_.?[0..out_len]); + continuationWriteIo(terminal_, &writer) catch |err| switch (err) { + error.WriteFailed => { + // Re-run against a counter to return the full required capacity, + // not merely the prefix that fit in the caller's buffer. + var discarding: std.Io.Writer.Discarding = .init(&.{}); + continuationWriteIo(terminal_, &discarding.writer) catch |count_err| + return continuationErrorResult(count_err); + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + else => return continuationErrorResult(err), + }; + + // `end` is the initialized prefix of the fixed destination. + out_written.* = writer.end; + return .success; +} + +pub fn continuation_alloc( + terminal_: Terminal, + alloc_: ?*const CAllocator, + out_ptr_: ?*?[*]u8, + out_len_: ?*usize, +) callconv(lib.calling_conv) Result { + const out_ptr = out_ptr_ orelse return .invalid_value; + const out_len = out_len_ orelse return .invalid_value; + // Make ownership unambiguous even if validation or allocation fails. + out_ptr.* = null; + out_len.* = 0; + + // Resolve NULL to libghostty-vt's default allocator before entering the + // shared Zig allocation path. + const bytes = continuationAllocIo( + terminal_, + lib.alloc.default(alloc_), + false, + ) catch |err| return switch (err) { + error.InvalidValue => .invalid_value, + error.OutOfMemory => .out_of_memory, + error.ContinuationDisabled => .invalid_value, + error.ContinuationUnavailable => .invalid_value, + }; + + // Ownership crosses the ABI here; callers release this exact pointer and + // length with ghostty_free and the same allocator selection. + // An idle parser has no continuation. Never export the empty Zig slice's + // sentinel pointer to a foreign runtime. + out_ptr.* = if (bytes.len == 0) null else bytes.ptr; + out_len.* = bytes.len; + return .success; +} + +fn continuationMaxBytes(wrapper: *const TerminalWrapper) usize { + // Absence of a tracker is the public representation of disabled tracking. + return if (wrapper.stream.continuation) |tracker| + tracker.max_bytes + else + 0; +} + +/// Change continuation tracking policy without disturbing normal VT parser +/// state. Bytes which were not retained while disabled or after exceeding an +/// earlier cap cannot be reconstructed: export remains unavailable until a +/// later feed reaches ground or contains a new replay start. +fn setContinuationMaxBytes(wrapper: *TerminalWrapper, max_bytes: usize) void { + if (max_bytes == 0) { + // Disabling releases retained bytes immediately. Parser and UTF-8 state + // continue normally; only future replay/export information is lost. + if (wrapper.stream.continuation) |*tracker| tracker.deinit(); + wrapper.stream.continuation = null; + return; + } + + if (wrapper.stream.continuation) |*tracker| { + // Changing a live cap preserves retained bytes when they still fit. + tracker.max_bytes = max_bytes; + if (tracker.bytes.items.len > max_bytes) { + // Once a retained prefix is discarded it cannot be reconstructed + // from parser state alone. Mark it broken until Stream observes a + // ground state or a new replay-safe sequence start. + tracker.bytes.clearRetainingCapacity(); + tracker.broken = true; + } + return; + } + + // Enabling from zero starts an empty tracker owned by the terminal's + // allocator. It can immediately track only if no earlier bytes are needed. + wrapper.stream.continuation = .init(wrapper.terminal.gpa(), max_bytes); + if (!wrapper.stream.ground()) { + // The parser was already mid-sequence while tracking was disabled, so + // exporting now would omit an unknown prefix. + wrapper.stream.continuation.?.broken = true; + } +} + pub fn compression_activity( terminal_: Terminal, out_activity_: ?*u64, @@ -402,9 +1127,7 @@ pub fn compress( ) callconv(lib.calling_conv) Result { const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; const out_result = out_result_ orelse return .invalid_value; - const mode = std.meta.intToEnum(CompressionMode, mode_) catch - return .invalid_value; - + const mode = std.enums.fromInt(CompressionMode, mode_) orelse return .invalid_value; out_result.* = t.compress(mode); return .success; } @@ -438,6 +1161,19 @@ pub const Option = enum(c_int) { glyph_protocol = 24, pwd_changed = 25, clipboard_write = 26, + scrollback_max_bytes = 27, + scrollback_max_lines = 28, + desktop_notification = 29, + progress_report = 30, + continuation_max_bytes = 31, + title_report = 32, + mode_default = 33, + mode = 34, + unknown_sequence = 35, + unknown_max_bytes = 36, + terminfo_name = 37, + clipboard_read = 38, + clipboard_write_max_bytes = 39, /// Input type expected for setting the option. pub fn InType(comptime self: Option) type { @@ -446,26 +1182,39 @@ pub const Option = enum(c_int) { .write_pty => ?Effects.WritePtyFn, .bell => ?Effects.BellFn, .color_scheme => ?Effects.ColorSchemeFn, + .desktop_notification => ?Effects.DesktopNotificationFn, .device_attributes => ?Effects.DeviceAttributesFn, .enquiry => ?Effects.EnquiryFn, .xtversion => ?Effects.XtversionFn, .title_changed => ?Effects.TitleChangedFn, .pwd_changed => ?Effects.PwdChangedFn, + .progress_report => ?Effects.ProgressReportFn, .size_cb => ?Effects.SizeFn, .clipboard_write => ?Effects.ClipboardWriteFn, - .title, .pwd => ?*const lib.String, + .clipboard_read => ?Effects.ClipboardReadFn, + .unknown_sequence => ?Effects.UnknownSequenceFn, + .title, .pwd, .terminfo_name => ?*const lib.String, .color_foreground, .color_background, .color_cursor => ?*const color.RGB.C, .color_palette => ?*const color.PaletteC, .kitty_image_storage_limit => ?*const u64, .kitty_image_medium_file, - .kitty_image_medium_temp_file, .kitty_image_medium_shared_mem, .glyph_protocol, + .title_report, => ?*const bool, - .apc_max_bytes, .apc_max_bytes_kitty => ?*const usize, + .kitty_image_medium_temp_file => ?*const lib.String, + .apc_max_bytes, + .apc_max_bytes_kitty, + .scrollback_max_bytes, + .scrollback_max_lines, + .continuation_max_bytes, + .unknown_max_bytes, + .clipboard_write_max_bytes, + => ?*const usize, .selection => ?*const selection_c.CSelection, .default_cursor_style => ?*const TerminalCursorStyle, .default_cursor_blink => ?*const bool, + .mode, .mode_default => ?*const ModeConfig, }; } }; @@ -476,7 +1225,7 @@ pub fn set( value: ?*const anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + _ = std.enums.fromInt(Option, @intFromEnum(option)) orelse { log.warn("terminal_set invalid option value={d}", .{@intFromEnum(option)}); return .invalid_value; }; @@ -503,13 +1252,39 @@ fn setTyped( .write_pty => wrapper.effects.write_pty = value, .bell => wrapper.effects.bell = value, .color_scheme => wrapper.effects.color_scheme = value, + .desktop_notification => wrapper.effects.desktop_notification = value, .device_attributes => wrapper.effects.device_attributes_cb = value, .enquiry => wrapper.effects.enquiry = value, .xtversion => wrapper.effects.xtversion = value, .title_changed => wrapper.effects.title_changed = value, .pwd_changed => wrapper.effects.pwd_changed = value, + .progress_report => wrapper.effects.progress_report = value, .size_cb => wrapper.effects.size_cb = value, - .clipboard_write => wrapper.effects.clipboard_write = value, + .clipboard_write => { + wrapper.effects.clipboard_write = value; + wrapper.stream.handler.effects.clipboard_write = if (value != null) + &Effects.clipboardWriteTrampoline + else + null; + }, + .clipboard_read => { + wrapper.effects.clipboard_read = value; + wrapper.stream.handler.effects.clipboard_read = if (value != null) + &Effects.clipboardReadTrampoline + else + null; + }, + .unknown_sequence => { + wrapper.effects.unknown_sequence = value; + wrapper.stream.handler.unknown_sequence = if (value != null) + &Effects.unknownSequenceTrampoline + else + null; + }, + .title_report => wrapper.stream.handler.title_report = if (value) |ptr| + ptr.* + else + false, .title => { const str = if (value) |v| v.ptr[0..v.len] else ""; wrapper.terminal.setTitle(str) catch return .out_of_memory; @@ -518,6 +1293,15 @@ fn setTyped( const str = if (value) |v| v.ptr[0..v.len] else ""; wrapper.terminal.setPwd(str) catch return .out_of_memory; }, + .terminfo_name => { + const str = if (value) |v| v.ptr[0..v.len] else ""; + if (str.len > wrapper.terminfo_name_buf.len) return .invalid_value; + @memcpy(wrapper.terminfo_name_buf[0..str.len], str); + wrapper.stream.handler.terminfo_name = if (str.len > 0) + wrapper.terminfo_name_buf[0..str.len] + else + null; + }, .color_foreground => { wrapper.terminal.colors.foreground.default = if (value) |v| .fromC(v.*) else null; wrapper.terminal.flags.dirty.palette = true; @@ -532,8 +1316,9 @@ fn setTyped( }, .color_palette => { wrapper.terminal.colors.palette.changeDefault( + wrapper.terminal.gpa(), if (value) |v| color.paletteZval(v) else color.default, - ); + ) catch return .out_of_memory; wrapper.terminal.flags.dirty.palette = true; }, .kitty_image_storage_limit => { @@ -542,11 +1327,10 @@ fn setTyped( var it = wrapper.terminal.screens.all.iterator(); while (it.next()) |entry| { const screen = entry.value.*; - screen.kitty_images.setLimit(screen.alloc, screen, limit) catch return .out_of_memory; + screen.kitty_images.setLimit(screen.io, screen.alloc, screen, limit); } }, .kitty_image_medium_file, - .kitty_image_medium_temp_file, .kitty_image_medium_shared_mem, => { if (comptime !build_options.kitty_graphics) return .success; @@ -556,12 +1340,40 @@ fn setTyped( const screen = entry.value.*; switch (option) { .kitty_image_medium_file => screen.kitty_images.image_limits.file = val, - .kitty_image_medium_temp_file => screen.kitty_images.image_limits.temporary_file = val, .kitty_image_medium_shared_mem => screen.kitty_images.image_limits.shared_memory = val, else => unreachable, } } }, + .kitty_image_medium_temp_file => { + if (comptime !build_options.kitty_graphics) return .success; + const alloc = wrapper.terminal.gpa(); + if (value) |v| { + if (v.len > max_path_bytes) return .out_of_memory; + const path = alloc.dupe(u8, v.ptr[0..v.len]) catch + return .out_of_memory; + var it = wrapper.terminal.screens.all.iterator(); + while (it.next()) |entry| { + const screen = entry.value.*; + screen.kitty_images.image_limits.temporary_file = .{ + .enabled = .{ .directory = path }, + }; + } + + // Every screen points at the new copy now so the previous + // one can be released. + if (wrapper.tmp_dir_path) |old| alloc.free(old); + wrapper.tmp_dir_path = path; + } else { + var it = wrapper.terminal.screens.all.iterator(); + while (it.next()) |entry| { + const screen = entry.value.*; + screen.kitty_images.image_limits.temporary_file = .disabled; + } + if (wrapper.tmp_dir_path) |old| alloc.free(old); + wrapper.tmp_dir_path = null; + } + }, .apc_max_bytes => { wrapper.stream.handler.apc_handler.max_bytes = if (value) |ptr| .initFull(ptr.*) @@ -590,16 +1402,36 @@ fn setTyped( }, .default_cursor_style => { const style = (if (value) |ptr| ptr.* else TerminalCursorStyle.block).toZig() orelse return .invalid_value; - wrapper.stream.handler.default_cursor_style = style; - if (wrapper.stream.handler.default_cursor) { - wrapper.terminal.screens.active.cursor.cursor_style = style; - } + wrapper.terminal.setDefaultCursorStyle(style); }, .default_cursor_blink => { const blink = if (value) |ptr| ptr.* else false; - wrapper.stream.handler.default_cursor_blink = blink; - if (wrapper.stream.handler.default_cursor) { - wrapper.terminal.modes.set(.cursor_blinking, blink); + wrapper.terminal.setDefaultCursorBlink(blink); + }, + .scrollback_max_bytes => wrapper.terminal.setScrollbackMaxBytes( + if (value) |ptr| ptr.* else null, + ), + .scrollback_max_lines => wrapper.terminal.setScrollbackMaxLines( + if (value) |ptr| ptr.* else null, + ), + .continuation_max_bytes => setContinuationMaxBytes( + wrapper, + if (value) |ptr| ptr.* else default_continuation_max_bytes, + ), + .unknown_max_bytes => wrapper.stream.handler.apc_handler.unknown_max_bytes = + if (value) |ptr| ptr.* else 0, + .clipboard_write_max_bytes => wrapper.stream.handler.kitty_clipboard_write_max_bytes = + if (value) |ptr| ptr.* else kitty_clipboard.max_write_size, + .mode, .mode_default => { + const config = (value orelse return .invalid_value).*; + const mode = config.toMode() orelse return .invalid_value; + switch (option) { + .mode => wrapper.terminal.modes.set(mode, config.value), + .mode_default => { + if (!modes.defaultConfigurable(mode)) return .invalid_value; + wrapper.terminal.modes.setDefault(mode, config.value); + }, + else => unreachable, } }, } @@ -652,34 +1484,17 @@ pub fn resize( cell_height_px: u32, ) callconv(lib.calling_conv) Result { const wrapper = terminal_ orelse return .invalid_value; - const t = wrapper.terminal; - if (cols == 0 or rows == 0) return .invalid_value; - t.resize(t.gpa(), cols, rows) catch return .out_of_memory; - - // Update pixel sizes - t.width_px = std.math.mul(u32, cols, cell_width_px) catch std.math.maxInt(u32); - t.height_px = std.math.mul(u32, rows, cell_height_px) catch std.math.maxInt(u32); - - // Disable synchronized output mode so that we show changes - // immediately for a resize. This is allowed by the spec. - t.modes.set(.synchronized_output, false); - - // If we have in-band size reporting enabled, send a report. - if (t.modes.get(.in_band_size_reports)) in_band: { - const func = wrapper.effects.write_pty orelse break :in_band; - - var buf: [1024]u8 = undefined; - var writer: std.Io.Writer = .fixed(&buf); - size_report.encode(&writer, .mode_2048, .{ - .rows = rows, - .columns = cols, - .cell_width = cell_width_px, - .cell_height = cell_height_px, - }) catch break :in_band; - - const data = writer.buffered(); - func(@ptrCast(wrapper), wrapper.effects.userdata, data.ptr, data.len); - } + wrapper.stream.handler.resize(.{ + .cols = cols, + .rows = rows, + .cell_size_px = .{ + .width = cell_width_px, + .height = cell_height_px, + }, + }) catch |err| return switch (err) { + error.InvalidValue => .invalid_value, + error.OutOfMemory => .out_of_memory, + }; return .success; } @@ -689,30 +1504,6 @@ pub fn reset(terminal_: Terminal) callconv(lib.calling_conv) void { t.fullReset(); } -pub fn mode_get( - terminal_: Terminal, - tag: modes.ModeTag.Backing, - out_value: *bool, -) callconv(lib.calling_conv) Result { - const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; - const mode_tag: modes.ModeTag = @bitCast(tag); - const mode = modes.modeFromInt(mode_tag.value, mode_tag.ansi) orelse return .invalid_value; - out_value.* = t.modes.get(mode); - return .success; -} - -pub fn mode_set( - terminal_: Terminal, - tag: modes.ModeTag.Backing, - value: bool, -) callconv(lib.calling_conv) Result { - const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; - const mode_tag: modes.ModeTag = @bitCast(tag); - const mode = modes.modeFromInt(mode_tag.value, mode_tag.ansi) orelse return .invalid_value; - t.modes.set(mode, value); - return .success; -} - /// C: GhosttyKittyGraphics pub const KittyGraphics = kitty_gfx_c.KittyGraphics; @@ -757,7 +1548,15 @@ pub const TerminalData = enum(c_int) { kitty_graphics = 30, selection = 31, viewport_active = 32, - modify_other_keys = 33, + vt_processing_error = 33, + scrollback_max_bytes = 34, + scrollback_max_lines = 35, + continuation_max_bytes = 36, + mode = 37, + vt_ground = 38, + cursor_at_prompt = 39, + clipboard_write_max_bytes = 40, + modify_other_keys = 41, /// Output type expected for querying the data of the given kind. pub fn OutType(comptime self: TerminalData) type { @@ -768,6 +1567,9 @@ pub const TerminalData = enum(c_int) { .cursor_visible, .mouse_tracking, .viewport_active, + .vt_processing_error, + .vt_ground, + .cursor_at_prompt, .modify_other_keys, => bool, .active_screen => TerminalScreen, @@ -775,7 +1577,13 @@ pub const TerminalData = enum(c_int) { .scrollbar => TerminalScrollbar, .cursor_style => style_c.Style, .title, .pwd => lib.String, - .total_rows, .scrollback_rows => usize, + .total_rows, + .scrollback_rows, + .scrollback_max_bytes, + .scrollback_max_lines, + .continuation_max_bytes, + .clipboard_write_max_bytes, + => usize, .width_px, .height_px => u32, .color_foreground, .color_background, @@ -787,11 +1595,12 @@ pub const TerminalData = enum(c_int) { .color_palette, .color_palette_default => color.PaletteC, .kitty_image_storage_limit => u64, .kitty_image_medium_file, - .kitty_image_medium_temp_file, .kitty_image_medium_shared_mem, => bool, + .kitty_image_medium_temp_file => lib.String, .kitty_graphics => KittyGraphics, .selection => selection_c.CSelection, + .mode => ModeConfig, }; } }; @@ -802,18 +1611,20 @@ pub fn get( out: ?*anyopaque, ) callconv(lib.calling_conv) Result { if (comptime std.debug.runtime_safety) { - _ = std.meta.intToEnum(TerminalData, @intFromEnum(data)) catch { + _ = std.enums.fromInt(TerminalData, @intFromEnum(data)) orelse { log.warn("terminal_get invalid data value={d}", .{@intFromEnum(data)}); return .invalid_value; }; } + const out_ptr = out orelse return .invalid_value; + return switch (data) { .invalid => .invalid_value, inline else => |comptime_data| getTyped( terminal_, comptime_data, - @ptrCast(@alignCast(out)), + @ptrCast(@alignCast(out_ptr)), ), }; } @@ -844,7 +1655,8 @@ fn getTyped( comptime data: TerminalData, out: *data.OutType(), ) Result { - const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; + const wrapper = terminal_ orelse return .invalid_value; + const t: *ZigTerminal = wrapper.terminal; switch (data) { .invalid => return .invalid_value, .cols => out.* = t.cols, @@ -880,7 +1692,7 @@ fn getTyped( .color_background_default => out.* = (t.colors.background.default orelse return .no_value).cval(), .color_cursor_default => out.* = (t.colors.cursor.default orelse return .no_value).cval(), .color_palette => out.* = color.paletteCval(&t.colors.palette.current), - .color_palette_default => out.* = color.paletteCval(&t.colors.palette.original), + .color_palette_default => out.* = color.paletteCval(t.colors.palette.original), .kitty_image_storage_limit => { if (comptime !build_options.kitty_graphics) return .no_value; out.* = @intCast(t.screens.active.kitty_images.total_limit); @@ -891,7 +1703,11 @@ fn getTyped( }, .kitty_image_medium_temp_file => { if (comptime !build_options.kitty_graphics) return .no_value; - out.* = t.screens.active.kitty_images.image_limits.temporary_file; + const dir = switch (t.screens.active.kitty_images.image_limits.temporary_file) { + .enabled => |d| d.directory, + .disabled => "", + }; + out.* = .init(dir); }, .kitty_image_medium_shared_mem => { if (comptime !build_options.kitty_graphics) return .no_value; @@ -906,6 +1722,25 @@ fn getTyped( ), .viewport_active => out.* = t.screens.active.pages.viewport == .active, .modify_other_keys => out.* = t.flags.modify_other_keys_2, + .vt_processing_error => out.* = wrapper.stream.handler.semantic_failure, + .vt_ground => out.* = wrapper.stream.ground(), + .scrollback_max_bytes => { + const max = t.screens.get(.primary).?.pages.limits.bytes.explicit; + if (max == std.math.maxInt(usize)) return .no_value; + out.* = max; + }, + .scrollback_max_lines => { + const max = t.screens.get(.primary).?.pages.limits.lines.explicit; + if (max == std.math.maxInt(usize)) return .no_value; + out.* = max; + }, + .continuation_max_bytes => out.* = continuationMaxBytes(wrapper), + .clipboard_write_max_bytes => out.* = wrapper.stream.handler.kitty_clipboard_write_max_bytes, + .mode => { + const mode = out.toMode() orelse return .invalid_value; + out.value = t.modes.get(mode); + }, + .cursor_at_prompt => out.* = t.cursorIsAtPrompt(), } return .success; @@ -988,22 +1823,30 @@ pub fn free(terminal_: Terminal) callconv(lib.calling_conv) void { for (wrapper.tracked_grid_refs.keys()) |ref| ref.terminal = null; wrapper.tracked_grid_refs.deinit(alloc); + for (wrapper.searches.keys()) |search| search.terminal = null; + wrapper.searches.deinit(alloc); wrapper.stream.deinit(); t.deinit(alloc); + if (wrapper.tmp_dir_path) |path| alloc.free(path); alloc.destroy(t); alloc.destroy(wrapper); } +fn testEnableContinuation(terminal: Terminal) !void { + const limit: usize = 1024; + try testing.expectEqual( + Result.success, + set(terminal, .continuation_max_bytes, &limit), + ); +} + test "new/free" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); try testing.expect(t != null); @@ -1016,26 +1859,392 @@ test "new invalid value" { try testing.expectEqual(Result.invalid_value, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 0, - .rows = 24, - .max_scrollback = 10_000, - }, + 0, + 24, )); try testing.expect(t == null); try testing.expectEqual(Result.invalid_value, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 0, - .max_scrollback = 10_000, - }, + 80, + 0, )); try testing.expect(t == null); } +test "continuation option and data" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + var value: usize = 0; + try testing.expectEqual( + Result.success, + get(t, .continuation_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(default_continuation_max_bytes, value); + + const custom: usize = 1234; + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &custom), + ); + try testing.expectEqual( + Result.success, + get(t, .continuation_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(custom, value); + + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, null), + ); + try testing.expectEqual( + Result.success, + get(t, .continuation_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(default_continuation_max_bytes, value); + + const disabled: usize = 0; + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &disabled), + ); + try testing.expectEqual( + Result.success, + get(t, .continuation_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(@as(usize, 0), value); + + var written: usize = 99; + try testing.expectEqual( + Result.invalid_value, + continuation_buf(t, null, 0, &written), + ); + try testing.expectEqual(@as(usize, 0), written); +} + +test "continuation buffer and allocator export exact suffix" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + try testEnableContinuation(t); + + vt_write(t, "A\x1b[31", 5); + + var required: usize = 0; + try testing.expectEqual( + Result.out_of_space, + continuation_buf(t, null, 0, &required), + ); + try testing.expectEqual(@as(usize, 4), required); + + var short: [2]u8 = undefined; + try testing.expectEqual( + Result.out_of_space, + continuation_buf(t, &short, short.len, &required), + ); + try testing.expectEqual(@as(usize, 4), required); + + var buf: [8]u8 = undefined; + var written: usize = 0; + try testing.expectEqual( + Result.success, + continuation_buf(t, &buf, buf.len, &written), + ); + try testing.expectEqualStrings("\x1b[31", buf[0..written]); + + var out_ptr: ?[*]u8 = null; + var out_len: usize = 0; + try testing.expectEqual(Result.success, continuation_alloc( + t, + &lib.alloc.test_allocator, + &out_ptr, + &out_len, + )); + const allocated = (out_ptr orelse return error.TestExpectedEqual)[0..out_len]; + defer lib.alloc.default(&lib.alloc.test_allocator).free(allocated); + try testing.expectEqualStrings("\x1b[31", allocated); + + vt_write(t, "m", 1); + try testing.expectEqual( + Result.out_of_space, + continuation_buf(t, null, 0, &required), + ); + try testing.expectEqual(@as(usize, 0), required); + + // Completing the sequence must return an empty, allocation-free result. + const failing: CAllocator = .fromZig(&std.mem.Allocator.failing); + try testing.expectEqual(Result.success, continuation_alloc(t, &failing, &out_ptr, &out_len)); + defer @import("allocator.zig").free(&failing, out_ptr, out_len); + try testing.expectEqual(null, out_ptr); + try testing.expectEqual(@as(usize, 0), out_len); +} + +test "continuation export tracks split UTF-8" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + try testEnableContinuation(t); + + const prefix = [_]u8{ 0xF0, 0x9F }; + vt_write(t, &prefix, prefix.len); + + var buf: [4]u8 = undefined; + var written: usize = 0; + try testing.expectEqual( + Result.success, + continuation_buf(t, &buf, buf.len, &written), + ); + try testing.expectEqualSlices(u8, &prefix, buf[0..written]); + + const suffix = [_]u8{ 0x98, 0x80 }; + vt_write(t, &suffix, suffix.len); + try testing.expectEqual( + Result.out_of_space, + continuation_buf(t, null, 0, &written), + ); + try testing.expectEqual(@as(usize, 0), written); +} + +test "continuation callback writer reports success and failure" { + const Sink = struct { + bytes: [8]u8 = undefined, + len: usize = 0, + + fn write( + userdata: ?*anyopaque, + data: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) bool { + const self: *@This() = @ptrCast(@alignCast(userdata.?)); + if (len > self.bytes.len - self.len) return false; + @memcpy(self.bytes[self.len..][0..len], data[0..len]); + self.len += len; + return true; + } + + fn fail( + _: ?*anyopaque, + _: [*]const u8, + _: usize, + ) callconv(lib.calling_conv) bool { + return false; + } + }; + + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + try testEnableContinuation(t); + vt_write(t, "\x1b[31", 4); + + var sink: Sink = .{}; + try testing.expectEqual(Result.success, continuation_write(t, .{ + .write = &Sink.write, + .userdata = &sink, + })); + try testing.expectEqualStrings("\x1b[31", sink.bytes[0..sink.len]); + + try testing.expectEqual(Result.io_error, continuation_write(t, .{ + .write = &Sink.fail, + })); + try testing.expectEqual( + Result.invalid_value, + continuation_write(t, .{}), + ); + try testing.expectEqual(Result.invalid_value, continuation_write(null, .{ + .write = &Sink.fail, + })); +} + +test "continuation runtime reconfiguration recovers safely" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const enough: usize = 8; + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &enough), + ); + vt_write(t, "\x1b[123", 5); + const too_small: usize = 2; + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &too_small), + ); + + var written: usize = 99; + try testing.expectEqual( + Result.invalid_value, + continuation_buf(t, null, 0, &written), + ); + try testing.expectEqual(@as(usize, 0), written); + + // Raising the limit cannot reconstruct discarded bytes, but a new ESC is + // a complete replay start and repairs tracking without first grounding. + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &enough), + ); + vt_write(t, "\x1b[", 2); + var buf: [8]u8 = undefined; + try testing.expectEqual( + Result.success, + continuation_buf(t, &buf, buf.len, &written), + ); + try testing.expectEqualStrings("\x1b[", buf[0..written]); + + const disabled: usize = 0; + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &disabled), + ); + try testing.expectEqual( + Result.success, + set(t, .continuation_max_bytes, &enough), + ); + try testing.expectEqual( + Result.invalid_value, + continuation_buf(t, null, 0, &written), + ); + + // Completing the sequence reaches ground and resets the broken marker. + vt_write(t, "m", 1); + try testing.expectEqual( + Result.out_of_space, + continuation_buf(t, null, 0, &written), + ); + try testing.expectEqual(@as(usize, 0), written); +} + +test "continuation internal allocation and restoration" { + var source: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &source, + 80, + 24, + )); + defer free(source); + try testEnableContinuation(source); + vt_write(source, "\x1b[31", 4); + + const alloc = lib.alloc.default(&lib.alloc.test_allocator); + const bytes = try continuationAllocIo(source, alloc, false); + defer alloc.free(bytes); + try testing.expectEqualStrings("\x1b[31", bytes); + + var restored: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &restored, + 80, + 24, + )); + defer free(restored); + try testEnableContinuation(restored); + try restoreContinuation(restored, bytes); + + const reexported = try continuationAllocIo(restored, alloc, false); + defer alloc.free(reexported); + try testing.expectEqualStrings(bytes, reexported); + + var invalid: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &invalid, + 80, + 24, + )); + defer free(invalid); + try testEnableContinuation(invalid); + try testing.expectError( + error.InvalidContinuation, + restoreContinuation(invalid, "A"), + ); +} + +test "set scrollback limits" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 3, + )); + defer free(t); + + const primary = t.?.terminal.screens.get(.primary).?; + + const max_bytes: usize = 0; + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_bytes, &max_bytes), + ); + try testing.expectEqual( + @as(usize, 0), + primary.pages.limits.bytes.explicit, + ); + try testing.expect(primary.no_scrollback); + + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_bytes, null), + ); + try testing.expectEqual( + std.math.maxInt(usize), + primary.pages.limits.bytes.explicit, + ); + try testing.expect(!primary.no_scrollback); + + const max_lines: usize = 12; + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_lines, &max_lines), + ); + try testing.expectEqual( + max_lines, + primary.pages.limits.lines.explicit, + ); + + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_lines, null), + ); + try testing.expectEqual( + std.math.maxInt(usize), + primary.pages.limits.lines.explicit, + ); +} + test "free null" { free(null); } @@ -1045,11 +2254,8 @@ test "scroll_viewport" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 5, - .rows = 2, - .max_scrollback = 10_000, - }, + 5, + 2, )); defer free(t); @@ -1107,11 +2313,8 @@ test "scroll_viewport row" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 5, - .rows = 2, - .max_scrollback = 10_000, - }, + 5, + 2, )); defer free(t); @@ -1167,11 +2370,8 @@ test "scroll_viewport row alt screen" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 5, - .rows = 2, - .max_scrollback = 10_000, - }, + 5, + 2, )); defer free(t); @@ -1220,11 +2420,8 @@ test "compression invalid arguments" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000_000, - }, + 80, + 24, )); defer free(t); @@ -1247,11 +2444,8 @@ test "compression activity and incremental scheduling" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000_000, - }, + 80, + 24, )); defer free(t); @@ -1314,11 +2508,8 @@ test "reset" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer free(t); @@ -1339,11 +2530,8 @@ test "resize" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer free(t); @@ -1361,11 +2549,8 @@ test "resize invalid value" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer free(t); @@ -1378,11 +2563,8 @@ test "resize shrinks both axes with cursor at bottom" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1397,85 +2579,152 @@ test "resize shrinks both axes with cursor at bottom" { try testing.expectEqual(23, t.?.terminal.rows); } -test "mode_get and mode_set" { +test "set and get mode" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); - var value: bool = undefined; - // DEC mode 25 (cursor_visible) defaults to true const cursor_visible: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); - try testing.expectEqual(Result.success, mode_get(t, cursor_visible, &value)); - try testing.expect(value); + var config: ModeConfig = .{ .mode = cursor_visible, .value = undefined }; + try testing.expectEqual(Result.success, get(t, .mode, @ptrCast(&config))); + try testing.expect(config.value); // Set it to false - try testing.expectEqual(Result.success, mode_set(t, cursor_visible, false)); - try testing.expectEqual(Result.success, mode_get(t, cursor_visible, &value)); - try testing.expect(!value); + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + try testing.expectEqual(Result.success, get(t, .mode, @ptrCast(&config))); + try testing.expect(!config.value); // ANSI mode 4 (insert) defaults to false const insert: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 4, .ansi = true }); - try testing.expectEqual(Result.success, mode_get(t, insert, &value)); - try testing.expect(!value); - - try testing.expectEqual(Result.success, mode_set(t, insert, true)); - try testing.expectEqual(Result.success, mode_get(t, insert, &value)); - try testing.expect(value); + config.mode = insert; + try testing.expectEqual(Result.success, get(t, .mode, @ptrCast(&config))); + try testing.expect(!config.value); + + config.value = true; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + try testing.expectEqual(Result.success, get(t, .mode, @ptrCast(&config))); + try testing.expect(config.value); } -test "mode_get null" { - var value: bool = undefined; - const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); - try testing.expectEqual(Result.invalid_value, mode_get(null, tag, &value)); -} +test "set mode default updates current and reset value" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); -test "mode_set null" { - const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); - try testing.expectEqual(Result.invalid_value, mode_set(null, tag, true)); + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ + .value = 2027, + .ansi = false, + }); + var config: ModeConfig = .{ .mode = tag, .value = true }; + try testing.expectEqual(Result.success, set( + t, + .mode_default, + @ptrCast(&config), + )); + try testing.expect(t.?.terminal.modes.get(.grapheme_cluster)); + try testing.expect(t.?.terminal.modes.default.grapheme_cluster); + + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + try testing.expect(!t.?.terminal.modes.get(.grapheme_cluster)); + try testing.expect(t.?.terminal.modes.default.grapheme_cluster); + + // Setting the default also unconditionally replaces the current value. + config.value = true; + try testing.expectEqual(Result.success, set( + t, + .mode_default, + @ptrCast(&config), + )); + try testing.expect(t.?.terminal.modes.get(.grapheme_cluster)); + + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + vt_write(t, "\x1bc", 2); + try testing.expect(t.?.terminal.modes.get(.grapheme_cluster)); + + config.value = false; + try testing.expectEqual(Result.success, set( + t, + .mode_default, + @ptrCast(&config), + )); + try testing.expect(!t.?.terminal.modes.get(.grapheme_cluster)); + try testing.expect(!t.?.terminal.modes.default.grapheme_cluster); } -test "mode_get unknown mode" { +test "set mode default validates configuration" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); - var value: bool = undefined; - const unknown: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }); - try testing.expectEqual(Result.invalid_value, mode_get(t, unknown, &value)); + try testing.expectEqual(Result.invalid_value, set( + t, + .mode_default, + null, + )); + + var config: ModeConfig = .{ + .mode = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }), + .value = true, + }; + try testing.expectEqual(Result.invalid_value, set( + t, + .mode_default, + @ptrCast(&config), + )); + + config.mode = @bitCast(modes.ModeTag{ .value = 1047, .ansi = false }); + try testing.expectEqual(Result.invalid_value, set( + t, + .mode_default, + @ptrCast(&config), + )); } -test "mode_set unknown mode" { +test "set and get mode null" { + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); + var config: ModeConfig = .{ .mode = tag, .value = true }; + try testing.expectEqual(Result.invalid_value, set(null, .mode, @ptrCast(&config))); + try testing.expectEqual(Result.invalid_value, get(null, .mode, @ptrCast(&config))); +} + +test "set and get mode validate configuration" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); - const unknown: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }); - try testing.expectEqual(Result.invalid_value, mode_set(t, unknown, true)); + try testing.expectEqual(Result.invalid_value, set(t, .mode, null)); + try testing.expectEqual(Result.invalid_value, get(t, .mode, null)); + + var config: ModeConfig = .{ + .mode = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }), + .value = true, + }; + try testing.expectEqual(Result.invalid_value, set(t, .mode, @ptrCast(&config))); + try testing.expectEqual(Result.invalid_value, get(t, .mode, @ptrCast(&config))); } test "vt_write" { @@ -1483,11 +2732,8 @@ test "vt_write" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer free(t); @@ -1498,16 +2744,196 @@ test "vt_write" { try testing.expectEqualStrings("Hello", str); } +test "vt_write_until_ground result contract" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + // Input remains untouched when the stream is already at ground. + var consumed: usize = 99; + const untouched = "unprocessed"; + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, untouched, untouched.len, &consumed), + ); + try testing.expectEqual(@as(usize, 0), consumed); + + // Complete a split CSI and stop before inspecting the printable suffix. + vt_write(t, "\x1b[31", 4); + const input = "mABC\x1b["; + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, input, input.len, &consumed), + ); + try testing.expectEqual(@as(usize, 1), consumed); + try testing.expect(t.?.stream.ground()); + + var str = try t.?.terminal.plainString(testing.allocator); + try testing.expectEqualStrings("", str); + testing.allocator.free(str); + + // The untouched suffix can be processed after work at the boundary. + vt_write(t, input.ptr + consumed, input.len - consumed); + str = try t.?.terminal.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC", str); + try testing.expect(!t.?.stream.ground()); + + // Exhausting input while unfinished is distinct from reaching ground on + // the final byte, even though both consume the entire input. + try testing.expectEqual( + Result.no_value, + vt_write_until_ground(t, "123", 3, &consumed), + ); + try testing.expectEqual(@as(usize, 3), consumed); + try testing.expect(!t.?.stream.ground()); + + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, "m", 1, &consumed), + ); + try testing.expectEqual(@as(usize, 1), consumed); + try testing.expect(t.?.stream.ground()); +} + +test "vt_write_until_ground handles UTF-8 and abort boundaries" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + var ground: bool = false; + try testing.expectEqual( + Result.success, + get(t, .vt_ground, @ptrCast(&ground)), + ); + try testing.expect(ground); + + vt_write(t, &.{0xF0}, 1); + try testing.expectEqual( + Result.success, + get(t, .vt_ground, @ptrCast(&ground)), + ); + try testing.expect(!ground); + + const utf8_suffix = [_]u8{ 0x9F, 0x98, 0x84 }; + var consumed: usize = 99; + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, &utf8_suffix, utf8_suffix.len, &consumed), + ); + try testing.expectEqual(utf8_suffix.len, consumed); + try testing.expect(t.?.stream.ground()); + + // A malformed continuation resets the decoder and reaches ground after + // processing the retry byte. + vt_write(t, &.{ 0xE0, 0xA0 }, 2); + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, "A", 1, &consumed), + ); + try testing.expectEqual(@as(usize, 1), consumed); + try testing.expect(t.?.stream.ground()); + + vt_write(t, "\x1b[123", 5); + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, &.{0x18}, 1, &consumed), + ); + try testing.expectEqual(@as(usize, 1), consumed); + try testing.expect(t.?.stream.ground()); +} + +test "vt_write_until_ground invokes effects only for consumed input" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var bell_count: usize = 0; + + fn bell(_: Terminal, _: ?*anyopaque) callconv(lib.calling_conv) void { + bell_count += 1; + } + }; + S.bell_count = 0; + try testing.expectEqual(Result.success, set(t, .bell, @ptrCast(&S.bell))); + + vt_write(t, "\x1b[31", 4); + const input = "m\x07"; + var consumed: usize = 99; + try testing.expectEqual( + Result.success, + vt_write_until_ground(t, input, input.len, &consumed), + ); + try testing.expectEqual(@as(usize, 1), consumed); + try testing.expectEqual(@as(usize, 0), S.bell_count); + + vt_write(t, input.ptr + consumed, input.len - consumed); + try testing.expectEqual(@as(usize, 1), S.bell_count); +} + +test "vt_write_until_ground validates arguments" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + var consumed: usize = 99; + try testing.expectEqual( + Result.invalid_value, + vt_write_until_ground(null, "x", 1, &consumed), + ); + try testing.expectEqual(@as(usize, 0), consumed); + + consumed = 99; + try testing.expectEqual( + Result.invalid_value, + vt_write_until_ground(t, null, 1, &consumed), + ); + try testing.expectEqual(@as(usize, 0), consumed); + + try testing.expectEqual( + Result.invalid_value, + vt_write_until_ground(t, "", 0, null), + ); + + // NULL represents a valid empty slice. While unfinished it consumes zero + // bytes and reports that no ground boundary was found. + vt_write(t, "\x1b[", 2); + consumed = 99; + try testing.expectEqual( + Result.no_value, + vt_write_until_ground(t, null, 0, &consumed), + ); + try testing.expectEqual(@as(usize, 0), consumed); +} + test "vt_write split escape sequence" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer free(t); @@ -1528,11 +2954,8 @@ test "vt_write split combining mark after base at right edge" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 2, - .rows = 2, - .max_scrollback = 0, - }, + 2, + 2, )); defer free(t); @@ -1551,11 +2974,8 @@ test "get cols and rows" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1572,11 +2992,8 @@ test "get cursor position" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1590,6 +3007,51 @@ test "get cursor position" { try testing.expectEqual(0, y); } +test "get vt_processing_error" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + var processing_error: bool = true; + try testing.expectEqual(Result.success, get( + t, + .vt_processing_error, + @ptrCast(&processing_error), + )); + try testing.expect(!processing_error); + + // Force a non-graceful terminal-owned update failure through the public + // VT write path. + { + const alloc = t.?.terminal.screens.active.alloc; + t.?.terminal.screens.active.alloc = testing.failing_allocator; + defer t.?.terminal.screens.active.alloc = alloc; + + const input = "\x1B]2;unavailable\x1B\\"; + vt_write(t, input, input.len); + } + + try testing.expectEqual(Result.success, get( + t, + .vt_processing_error, + @ptrCast(&processing_error), + )); + try testing.expect(processing_error); + + reset(t); + try testing.expectEqual(Result.success, get( + t, + .vt_processing_error, + @ptrCast(&processing_error), + )); + try testing.expect(processing_error); +} + test "get null" { var cols: size.CellCountInt = undefined; try testing.expectEqual(Result.invalid_value, get(null, .cols, @ptrCast(&cols))); @@ -1600,11 +3062,8 @@ test "get cursor_visible" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1613,22 +3072,47 @@ test "get cursor_visible" { try testing.expect(visible); // DEC mode 25 controls cursor visibility - const cursor_visible_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); - try testing.expectEqual(Result.success, mode_set(t, cursor_visible_mode, false)); + var config: ModeConfig = .{ + .mode = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }), + .value = false, + }; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); try testing.expectEqual(Result.success, get(t, .cursor_visible, @ptrCast(&visible))); try testing.expect(!visible); } +test "get cursor_at_prompt" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + var at_prompt: bool = undefined; + try testing.expectEqual(Result.success, get(t, .cursor_at_prompt, @ptrCast(&at_prompt))); + try testing.expect(!at_prompt); + + const prompt_start = "\x1b]133;A\x07"; + vt_write(t, prompt_start, prompt_start.len); + try testing.expectEqual(Result.success, get(t, .cursor_at_prompt, @ptrCast(&at_prompt))); + try testing.expect(at_prompt); + + const alternate_screen = "\x1b[?1049h"; + vt_write(t, alternate_screen, alternate_screen.len); + try testing.expectEqual(Result.success, get(t, .cursor_at_prompt, @ptrCast(&at_prompt))); + try testing.expect(!at_prompt); +} + test "get active_screen" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1642,11 +3126,8 @@ test "get kitty_keyboard_flags" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1663,15 +3144,7 @@ test "get kitty_keyboard_flags" { test "get modify_other_keys" { var t: Terminal = null; - try testing.expectEqual(Result.success, new( - &lib.alloc.test_allocator, - &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, - )); + try testing.expectEqual(Result.success, new(&lib.alloc.test_allocator, &t, 80, 24)); defer free(t); var enabled: bool = undefined; @@ -1692,11 +3165,8 @@ test "get mouse_tracking" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1705,34 +3175,50 @@ test "get mouse_tracking" { try testing.expect(!tracking); // Enable X10 mouse (DEC mode 9) - const x10_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9, .ansi = false }); - try testing.expectEqual(Result.success, mode_set(t, x10_mode, true)); + var config: ModeConfig = .{ + .mode = @bitCast(modes.ModeTag{ .value = 9, .ansi = false }), + .value = true, + }; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); try testing.expect(tracking); // Disable X10, enable normal mouse (DEC mode 1000) - try testing.expectEqual(Result.success, mode_set(t, x10_mode, false)); - const normal_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1000, .ansi = false }); - try testing.expectEqual(Result.success, mode_set(t, normal_mode, true)); + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + config = .{ + .mode = @bitCast(modes.ModeTag{ .value = 1000, .ansi = false }), + .value = true, + }; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); try testing.expect(tracking); // Disable normal, enable button mouse (DEC mode 1002) - try testing.expectEqual(Result.success, mode_set(t, normal_mode, false)); - const button_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1002, .ansi = false }); - try testing.expectEqual(Result.success, mode_set(t, button_mode, true)); + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + config = .{ + .mode = @bitCast(modes.ModeTag{ .value = 1002, .ansi = false }), + .value = true, + }; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); try testing.expect(tracking); // Disable button, enable any mouse (DEC mode 1003) - try testing.expectEqual(Result.success, mode_set(t, button_mode, false)); - const any_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1003, .ansi = false }); - try testing.expectEqual(Result.success, mode_set(t, any_mode, true)); + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); + config = .{ + .mode = @bitCast(modes.ModeTag{ .value = 1003, .ansi = false }), + .value = true, + }; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); try testing.expect(tracking); // Disable all - should be false again - try testing.expectEqual(Result.success, mode_set(t, any_mode, false)); + config.value = false; + try testing.expectEqual(Result.success, set(t, .mode, @ptrCast(&config))); try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); try testing.expect(!tracking); } @@ -1742,11 +3228,8 @@ test "get total_rows" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 10_000, - }, + 80, + 24, )); defer free(t); @@ -1760,11 +3243,8 @@ test "get scrollback_rows" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 3, - .max_scrollback = 10_000, - }, + 80, + 3, )); defer free(t); @@ -1779,16 +3259,87 @@ test "get scrollback_rows" { try testing.expectEqual(@as(usize, 2), scrollback); } +test "get configured scrollback limits" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 3, + )); + defer free(t); + + var value: usize = undefined; + try testing.expectEqual( + Result.success, + get(t, .scrollback_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(@as(usize, 10_000), value); + try testing.expectEqual( + Result.no_value, + get(t, .scrollback_max_lines, @ptrCast(&value)), + ); + + const max_bytes: usize = 0; + const max_lines: usize = 12; + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_bytes, &max_bytes), + ); + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_lines, &max_lines), + ); + try testing.expectEqual( + Result.success, + get(t, .scrollback_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(max_bytes, value); + try testing.expectEqual( + Result.success, + get(t, .scrollback_max_lines, @ptrCast(&value)), + ); + try testing.expectEqual(max_lines, value); + + // The configured limits belong to the primary screen and remain + // readable while an alternate screen is active. + vt_write(t, "\x1b[?1049h", 8); + try testing.expectEqual( + Result.success, + get(t, .scrollback_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual(max_bytes, value); + try testing.expectEqual( + Result.success, + get(t, .scrollback_max_lines, @ptrCast(&value)), + ); + try testing.expectEqual(max_lines, value); + + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_bytes, null), + ); + try testing.expectEqual( + Result.success, + set(t, .scrollback_max_lines, null), + ); + try testing.expectEqual( + Result.no_value, + get(t, .scrollback_max_bytes, @ptrCast(&value)), + ); + try testing.expectEqual( + Result.no_value, + get(t, .scrollback_max_lines, @ptrCast(&value)), + ); +} + test "get invalid" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1800,11 +3351,8 @@ test "set default cursor style and blink" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1832,6 +3380,12 @@ test "set default cursor style and blink" { vt_write(t, "\x1b[0 q", 5); try testing.expectEqual(Screen.CursorStyle.underline, t.?.terminal.screens.active.cursor.cursor_style); try testing.expect(t.?.terminal.modes.get(.cursor_blinking)); + + // RIS also restores cursor defaults from Terminal-owned state. + vt_write(t, "\x1b[2 q", 5); + reset(t); + try testing.expectEqual(Screen.CursorStyle.underline, t.?.terminal.screens.active.cursor.cursor_style); + try testing.expect(t.?.terminal.modes.get(.cursor_blinking)); } test "set and get selection" { @@ -1839,11 +3393,8 @@ test "set and get selection" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1887,11 +3438,8 @@ test "selection derivation helpers" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -1977,11 +3525,8 @@ test "selection_adjust mutates snapshot end" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2025,11 +3570,8 @@ test "selection_order and selection_ordered" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2078,11 +3620,8 @@ test "selection_contains" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2136,11 +3675,8 @@ test "selection_equal" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2148,11 +3684,8 @@ test "selection_equal" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &other_t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(other_t); @@ -2225,11 +3758,8 @@ test "selection_order invalid values" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2243,11 +3773,8 @@ test "grid_ref" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2281,7 +3808,8 @@ test "point_from_grid_ref roundtrip active" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer free(t); @@ -2306,7 +3834,8 @@ test "point_from_grid_ref roundtrip viewport" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + 80, + 24, )); defer free(t); @@ -2329,7 +3858,8 @@ test "point_from_grid_ref history ref to active returns no_value" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 4, .max_scrollback = 10_000 }, + 80, + 4, )); defer free(t); @@ -2364,7 +3894,8 @@ test "point_from_grid_ref null node" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer free(t); @@ -2377,11 +3908,8 @@ test "set write_pty callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2415,16 +3943,45 @@ test "set write_pty callback" { try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); } +test "write_pty receives DECRQSS response" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |data| testing.allocator.free(data); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |data| testing.allocator.free(data); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + const query = "\x1B[1m\x1BP$qm\x1B\\"; + vt_write(t, query, query.len); + try testing.expectEqualStrings("\x1BP1$r0;1m\x1B\\", S.last_data.?); +} + test "write_pty receives OSC color query response" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2460,11 +4017,8 @@ test "set write_pty without callback ignores queries" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2477,11 +4031,8 @@ test "set write_pty null clears callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2506,11 +4057,8 @@ test "set bell callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2546,11 +4094,8 @@ test "bell without callback is silent" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2563,11 +4108,8 @@ test "set enquiry callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2605,11 +4147,8 @@ test "enquiry without callback is silent" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2622,11 +4161,8 @@ test "set xtversion callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2665,11 +4201,8 @@ test "xtversion without callback reports default" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2696,16 +4229,80 @@ test "xtversion without callback reports default" { try testing.expectEqualStrings("\x1BP>|libghostty\x1B\\", S.last_data.?); } +test "set terminfo_name option" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + // While no name is set the query goes unanswered; other capabilities + // are still served from the static map. + const query = "\x1BP+q" ++ std.fmt.bytesToHex("TN", .upper) ++ "\x1B\\"; + vt_write(t, query, query.len); + try testing.expect(S.last_data == null); + const co_query = "\x1BP+q" ++ std.fmt.bytesToHex("Co", .upper) ++ "\x1B\\"; + vt_write(t, co_query, co_query.len); + try testing.expectEqualStrings( + "\x1BP1+r" ++ std.fmt.bytesToHex("Co", .upper) ++ "=" ++ + std.fmt.bytesToHex("256", .upper) ++ "\x1B\\", + S.last_data.?, + ); + S.deinit(); + + // The name is copied, so the caller's buffer can go away afterwards. + var name: [14]u8 = "xterm-256color".*; + const value: lib.String = .{ .ptr = &name, .len = name.len }; + try testing.expectEqual(Result.success, set(t, .terminfo_name, @ptrCast(&value))); + @memset(&name, 'z'); + + vt_write(t, query, query.len); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings( + "\x1BP1+r" ++ std.fmt.bytesToHex("TN", .upper) ++ "=" ++ + std.fmt.bytesToHex("xterm-256color", .upper) ++ "\x1B\\", + S.last_data.?, + ); + + // Clearing with NULL leaves the query unanswered again. + S.deinit(); + try testing.expectEqual(Result.success, set(t, .terminfo_name, null)); + vt_write(t, query, query.len); + try testing.expect(S.last_data == null); + + // Names beyond the maximum are rejected rather than truncated. + const long: [Handler.max_terminfo_name_bytes + 1]u8 = @splat('a'); + const long_value: lib.String = .{ .ptr = &long, .len = long.len }; + try testing.expectEqual(Result.invalid_value, set(t, .terminfo_name, @ptrCast(&long_value))); +} + test "set title_changed callback" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2740,11 +4337,8 @@ test "title_changed without callback is silent" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2752,16 +4346,280 @@ test "title_changed without callback is silent" { vt_write(t, "\x1B]2;Hello\x1B\\", 10); } +test "kitty_image_medium_temp_file empty output" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + var t: Terminal = null; + try testing.expectEqual(Result.success, new(&lib.alloc.test_allocator, &t, 80, 24)); + defer free(t); + + const empty: lib.String = .{ .ptr = "", .len = 0 }; + try testing.expectEqual(Result.success, set(t, .kitty_image_medium_temp_file, &empty)); + var result: lib.String = undefined; + try testing.expectEqual(Result.success, get(t, .kitty_image_medium_temp_file, &result)); + try testing.expectEqual(@as(usize, 0), result.len); + try testing.expectEqual(@as([*]const u8, ""), result.ptr); +} + +test "set desktop_notification callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var count: usize = 0; + var last_userdata: ?*anyopaque = null; + var last_size: usize = 0; + var title: [64]u8 = undefined; + var title_len: usize = 0; + var body: [64]u8 = undefined; + var body_len: usize = 0; + + fn desktopNotification( + _: Terminal, + ud: ?*anyopaque, + notification: *const DesktopNotification, + ) callconv(lib.calling_conv) void { + count += 1; + last_userdata = ud; + last_size = notification.size; + title_len = notification.title.len; + body_len = notification.body.len; + @memcpy(title[0..title_len], notification.title.ptr[0..title_len]); + @memcpy(body[0..body_len], notification.body.ptr[0..body_len]); + } + }; + S.count = 0; + S.last_userdata = null; + S.last_size = 0; + S.title_len = 0; + S.body_len = 0; + + var sentinel: u8 = 99; + try testing.expectEqual(Result.success, set(t, .userdata, @ptrCast(&sentinel))); + try testing.expectEqual(Result.success, set( + t, + .desktop_notification, + @ptrCast(&S.desktopNotification), + )); + + // Split OSC 777 across writes to exercise the persistent VT parser. + const seq_a = "\x1B]777;notify;Codex;"; + const seq_b = "Needs attention\x1B\\"; + vt_write(t, seq_a, seq_a.len); + try testing.expectEqual(@as(usize, 0), S.count); + vt_write(t, seq_b, seq_b.len); + try testing.expectEqual(@as(usize, 1), S.count); + try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); + try testing.expectEqual(@sizeOf(DesktopNotification), S.last_size); + try testing.expectEqualStrings("Codex", S.title[0..S.title_len]); + try testing.expectEqualStrings("Needs attention", S.body[0..S.body_len]); + + // OSC 9 has no title and preserves its body. + const seq_c = "\x1B]9;Build complete\x07"; + vt_write(t, seq_c, seq_c.len); + try testing.expectEqual(@as(usize, 2), S.count); + try testing.expectEqualStrings("", S.title[0..S.title_len]); + try testing.expectEqualStrings("Build complete", S.body[0..S.body_len]); + + // Removing the callback takes effect immediately. + try testing.expectEqual(Result.success, set(t, .desktop_notification, null)); + vt_write(t, seq_c, seq_c.len); + try testing.expectEqual(@as(usize, 2), S.count); +} + +test "set progress_report callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var count: usize = 0; + var last_userdata: ?*anyopaque = null; + var last_size: usize = 0; + var last_state: ProgressState = .remove; + var last_progress: i8 = -1; + + fn progressReport( + _: Terminal, + ud: ?*anyopaque, + report: *const ProgressReport, + ) callconv(lib.calling_conv) void { + count += 1; + last_userdata = ud; + last_size = report.size; + last_state = report.state; + last_progress = report.progress; + } + }; + S.count = 0; + S.last_userdata = null; + S.last_size = 0; + S.last_state = .remove; + S.last_progress = -1; + + var sentinel: u8 = 100; + try testing.expectEqual(Result.success, set(t, .userdata, @ptrCast(&sentinel))); + try testing.expectEqual(Result.success, set( + t, + .progress_report, + @ptrCast(&S.progressReport), + )); + + const cases = [_]struct { + sequence: []const u8, + state: ProgressState, + progress: i8, + }{ + .{ .sequence = "\x1B]9;4;0;\x1B\\", .state = .remove, .progress = -1 }, + .{ .sequence = "\x1B]9;4;1;42\x07", .state = .set, .progress = 42 }, + .{ .sequence = "\x1B]9;4;2;7\x1B\\", .state = .@"error", .progress = 7 }, + .{ .sequence = "\x1B]9;4;3\x1B\\", .state = .indeterminate, .progress = -1 }, + .{ .sequence = "\x1B]9;4;4;75\x1B\\", .state = .pause, .progress = 75 }, + }; + + for (cases, 1..) |case, expected_count| { + const midpoint = case.sequence.len / 2; + vt_write(t, case.sequence.ptr, midpoint); + try testing.expectEqual(expected_count - 1, S.count); + vt_write(t, case.sequence.ptr + midpoint, case.sequence.len - midpoint); + try testing.expectEqual(expected_count, S.count); + try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); + try testing.expectEqual(@sizeOf(ProgressReport), S.last_size); + try testing.expectEqual(case.state, S.last_state); + try testing.expectEqual(case.progress, S.last_progress); + } + + try testing.expectEqual(Result.success, set(t, .progress_report, null)); + const ignored = "\x1B]9;4;1;90\x1B\\"; + vt_write(t, ignored, ignored.len); + try testing.expectEqual(@as(usize, cases.len), S.count); +} + +test "set unknown_sequence callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var count: usize = 0; + var last_terminal: Terminal = null; + var last_userdata: ?*anyopaque = null; + var last_tag: UnknownSequence.Tag = .apc; + var last_truncated: bool = false; + var content: [64]u8 = undefined; + var content_len: usize = 0; + + fn unknownSequence( + terminal_: Terminal, + ud: ?*anyopaque, + sequence: *const UnknownSequence.C, + ) callconv(lib.calling_conv) void { + count += 1; + last_terminal = terminal_; + last_userdata = ud; + last_tag = sequence.tag; + const apc_value = sequence.value.apc; + last_truncated = apc_value.truncated; + content_len = @min(apc_value.content.len, content.len); + @memcpy(content[0..content_len], apc_value.content.ptr[0..content_len]); + } + }; + S.count = 0; + S.last_terminal = null; + S.last_userdata = null; + S.last_tag = .apc; + S.last_truncated = false; + S.content_len = 0; + + var sentinel: u8 = 101; + try testing.expectEqual(Result.success, set(t, .userdata, @ptrCast(&sentinel))); + + const max_bytes: usize = 8; + try testing.expectEqual(Result.success, set( + t, + .unknown_max_bytes, + @ptrCast(&max_bytes), + )); + try testing.expectEqual(max_bytes, t.?.stream.handler.apc_handler.unknown_max_bytes); + + // A byte limit without a callback performs no external effect. + const before_callback = "\x1B_abc;xy\x1B\\"; + vt_write(t, before_callback, before_callback.len); + try testing.expectEqual(@as(usize, 0), S.count); + try testing.expect(t.?.stream.handler.unknown_sequence == null); + + try testing.expectEqual(Result.success, set( + t, + .unknown_sequence, + @ptrCast(&S.unknownSequence), + )); + try testing.expect(t.?.stream.handler.unknown_sequence != null); + + // Split a complete APC across writes to exercise persistent parser state. + const seq_a = "\x1B_abc;"; + const seq_b = "xy\x1B\\"; + vt_write(t, seq_a, seq_a.len); + try testing.expectEqual(@as(usize, 0), S.count); + vt_write(t, seq_b, seq_b.len); + try testing.expectEqual(@as(usize, 1), S.count); + try testing.expectEqual(t, S.last_terminal); + try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); + try testing.expectEqual(UnknownSequence.Tag.apc, S.last_tag); + try testing.expect(!S.last_truncated); + try testing.expectEqualStrings("abc;xy", S.content[0..S.content_len]); + + // Content beyond the generic limit is omitted and marked truncated. + const truncated = "\x1B_abcdefghijkl\x1B\\"; + vt_write(t, truncated, truncated.len); + try testing.expectEqual(@as(usize, 2), S.count); + try testing.expect(S.last_truncated); + try testing.expectEqualStrings("abcdefgh", S.content[0..S.content_len]); + + // CAN aborts the APC and must not invoke the callback. + const aborted = "\x1B_abcdef\x18"; + vt_write(t, aborted, aborted.len); + try testing.expectEqual(@as(usize, 2), S.count); + + // Clearing the callback restores the null fast path immediately. + try testing.expectEqual(Result.success, set(t, .unknown_sequence, null)); + try testing.expect(t.?.stream.handler.unknown_sequence == null); + vt_write(t, before_callback, before_callback.len); + try testing.expectEqual(@as(usize, 2), S.count); + + // A NULL limit disables capture even after reinstalling the callback. + try testing.expectEqual(Result.success, set( + t, + .unknown_sequence, + @ptrCast(&S.unknownSequence), + )); + try testing.expectEqual(Result.success, set(t, .unknown_max_bytes, null)); + try testing.expectEqual(@as(usize, 0), t.?.stream.handler.apc_handler.unknown_max_bytes); + vt_write(t, before_callback, before_callback.len); + try testing.expectEqual(@as(usize, 2), S.count); +} + test "set pwd_changed callback" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2800,11 +4658,8 @@ test "set clipboard_write callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2820,13 +4675,16 @@ test "set clipboard_write callback" { var last_mime_lens: [8]usize = @splat(0); var last_data: [8][64]u8 = undefined; var last_data_lens: [8]usize = @splat(0); - var next_result: clipboard.WriteResult = .success; + var last_name_len: usize = 0; + var last_granted: bool = true; + var last_can_remember: bool = true; + var next_result: clipboard.Write.Status = .success; fn clipboardWrite( terminal_: Terminal, ud: ?*anyopaque, request: *const ClipboardWrite, - ) callconv(lib.calling_conv) clipboard.WriteResult { + ) callconv(lib.calling_conv) void { count += 1; last_terminal = terminal_; last_userdata = ud; @@ -2834,6 +4692,9 @@ test "set clipboard_write callback" { last_location = request.location; last_contents_null = request.contents == null; last_contents_len = request.contents_len; + last_name_len = request.name.len; + last_granted = request.granted; + last_can_remember = request.can_remember; if (request.contents) |ptr| { for (ptr[0..@min(request.contents_len, last_mimes.len)], 0..) |content, i| { @@ -2851,7 +4712,11 @@ test "set clipboard_write callback" { } } - return next_result; + request.reply(request, &.{ + .size = @sizeOf(ClipboardWriteReply), + .result = next_result, + .remember = false, + }); } }; S.count = 0; @@ -2878,6 +4743,11 @@ test "set clipboard_write callback" { try testing.expectEqualStrings("text/plain", S.last_mimes[0][0..S.last_mime_lens[0]]); try testing.expectEqualSlices(u8, "hello\x00world", S.last_data[0][0..S.last_data_lens[0]]); + // OSC 52 carries no program identity or password grant state. + try testing.expectEqual(@as(usize, 0), S.last_name_len); + try testing.expect(!S.last_granted); + try testing.expect(!S.last_can_remember); + // OSC 52 destinations are normalized rather than exposed as wire bytes. const location_cases = [_]struct { selector: u8, @@ -2917,8 +4787,9 @@ test "set clipboard_write callback" { try testing.expectEqualStrings("text/plain", S.last_mimes[0][0..S.last_mime_lens[0]]); try testing.expectEqualStrings("iTerm", S.last_data[0][0..S.last_data_lens[0]]); - // Every representation is converted, and callback results propagate - // through the C trampoline for protocols that can acknowledge writes. + // Every representation is converted, and callback replies propagate + // back through the C trampoline for protocols that can acknowledge + // writes. const internal_contents = [_]clipboard.Content{ .{ .mime = "text/plain", .data = "plain" }, .{ .mime = "application/octet-stream", .data = "a\x00b" }, @@ -2926,13 +4797,27 @@ test "set clipboard_write callback" { .{ .mime = "text/rtf", .data = "{\\rtf1 plain}" }, .{ .mime = "image/png", .data = "\x89PNG" }, }; + const Reply = struct { + var last: ?clipboard.Write.Result = null; + fn reply(_: *anyopaque, result: clipboard.Write.Result) void { + last = result; + } + }; S.next_result = .busy; const handler = &t.?.stream.handler; - const write_result = handler.effects.clipboard_write.?(handler, .{ + handler.effects.clipboard_write.?(handler, .{ .location = .primary, .contents = &internal_contents, + .name = "app", + .granted = true, + .can_remember = true, + .reply_ctx = handler, + .reply_fn = &Reply.reply, }); - try testing.expectEqual(clipboard.WriteResult.busy, write_result); + try testing.expect(Reply.last.? == .busy); + try testing.expectEqual(@as(usize, 3), S.last_name_len); + try testing.expect(S.last_granted); + try testing.expect(S.last_can_remember); try testing.expectEqual(@as(usize, 7), S.count); try testing.expectEqual(@as(usize, 5), S.last_contents_len); try testing.expectEqualStrings( @@ -2943,8 +4828,10 @@ test "set clipboard_write callback" { try testing.expectEqualStrings("image/png", S.last_mimes[4][0..S.last_mime_lens[4]]); try testing.expectEqualSlices(u8, "\x89PNG", S.last_data[4][0..S.last_data_lens[4]]); - // Removing the callback takes effect immediately. + // Removing the callback takes effect immediately and uninstalls + // the trampoline. try testing.expectEqual(Result.success, set(t, .clipboard_write, null)); + try testing.expect(t.?.stream.handler.effects.clipboard_write == null); const after_remove = "\x1B]52;c;eA==\x1B\\"; vt_write(t, after_remove, after_remove.len); try testing.expectEqual(@as(usize, 7), S.count); @@ -2955,11 +4842,8 @@ test "clipboard_write without callback is unsupported and silent" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2967,12 +4851,400 @@ test "clipboard_write without callback is unsupported and silent" { const seq = "\x1B]52;c;aGVsbG8=\x1B\\"; vt_write(t, seq, seq.len); - const handler = &t.?.stream.handler; - const result = handler.effects.clipboard_write.?(handler, .{ - .location = .standard, - .contents = &.{.{ .mime = "text/plain", .data = "hello" }}, - }); - try testing.expectEqual(clipboard.WriteResult.unsupported, result); + // No trampoline is installed until a callback is set, so the + // stream skips clipboard work (and never spools a Kitty clipboard + // transaction it can't deliver). + try testing.expect(t.?.stream.handler.effects.clipboard_write == null); +} + +test "kitty clipboard write via C effects" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var responses: [512]u8 = undefined; + var responses_len: usize = 0; + var write_count: usize = 0; + var last_location: clipboard.Location = .standard; + var last_contents_len: usize = 0; + var last_mimes: [4][64]u8 = undefined; + var last_mime_lens: [4]usize = @splat(0); + var last_data: [4][64]u8 = undefined; + var last_data_lens: [4]usize = @splat(0); + var last_granted: bool = true; + var last_can_remember: bool = true; + var next_remember: bool = false; + + fn writePty( + _: Terminal, + _: ?*anyopaque, + ptr: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) void { + @memcpy(responses[responses_len..][0..len], ptr[0..len]); + responses_len += len; + } + + fn clipboardWrite( + _: Terminal, + _: ?*anyopaque, + request: *const ClipboardWrite, + ) callconv(lib.calling_conv) void { + write_count += 1; + last_location = request.location; + last_contents_len = request.contents_len; + if (request.contents) |ptr| { + for (ptr[0..@min(request.contents_len, last_mimes.len)], 0..) |content, i| { + last_mime_lens[i] = @min(content.mime.len, last_mimes[i].len); + @memcpy( + last_mimes[i][0..last_mime_lens[i]], + content.mime.ptr[0..last_mime_lens[i]], + ); + last_data_lens[i] = @min(content.data.len, last_data[i].len); + @memcpy( + last_data[i][0..last_data_lens[i]], + content.data.ptr[0..last_data_lens[i]], + ); + } + } + last_granted = request.granted; + last_can_remember = request.can_remember; + request.reply(request, &.{ + .size = @sizeOf(ClipboardWriteReply), + .result = .success, + .remember = next_remember, + }); + } + }; + S.responses_len = 0; + S.write_count = 0; + S.last_mime_lens = @splat(0); + S.last_data_lens = @splat(0); + S.last_granted = true; + S.last_can_remember = true; + S.next_remember = false; + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .clipboard_write, @ptrCast(&S.clipboardWrite))); + + // A full OSC 5522 write transaction: begin, chunked data for two + // representations, commit. Only the commit invokes the callback, + // and its result maps to the DONE response. + const seqs = [_][]const u8{ + "\x1B]5522;type=write:id=c1\x1B\\", + "\x1B]5522;type=wdata:mime=dGV4dC9wbGFpbg==;R2hvc3Q=\x1B\\", // "Ghost" + "\x1B]5522;type=wdata:mime=dGV4dC9wbGFpbg==;dHk=\x1B\\", // "ty" + "\x1B]5522;type=wdata:mime=dGV4dC9odG1s;PGI+aGk8L2I+\x1B\\", // "<b>hi</b>" + "\x1B]5522;type=wdata\x1B\\", + }; + for (seqs) |seq| vt_write(t, seq.ptr, seq.len); + + try testing.expectEqual(@as(usize, 1), S.write_count); + try testing.expectEqual(clipboard.Location.standard, S.last_location); + try testing.expectEqual(@as(usize, 2), S.last_contents_len); + try testing.expectEqualStrings("text/plain", S.last_mimes[0][0..S.last_mime_lens[0]]); + try testing.expectEqualStrings("Ghostty", S.last_data[0][0..S.last_data_lens[0]]); + try testing.expectEqualStrings("text/html", S.last_mimes[1][0..S.last_mime_lens[1]]); + try testing.expectEqualStrings("<b>hi</b>", S.last_data[1][0..S.last_data_lens[1]]); + try testing.expectEqualStrings( + "\x1B]5522;type=write:status=DONE:id=c1\x1B\\", + S.responses[0..S.responses_len], + ); + try testing.expect(!S.last_granted); + try testing.expect(!S.last_can_remember); + + // Password grants round-trip through the C reply: the first pw'd + // commit isn't granted and asks to remember, so the next one + // arrives granted. + S.responses_len = 0; + S.next_remember = true; + const grant_seqs = [_][]const u8{ + "\x1B]5522;type=write:id=g1:pw=c2VjcmV0:name=YXBw\x1B\\", + "\x1B]5522;type=wdata\x1B\\", + "\x1B]5522;type=write:id=g2:pw=c2VjcmV0:name=YXBw\x1B\\", + "\x1B]5522;type=wdata\x1B\\", + }; + for (grant_seqs) |seq| vt_write(t, seq.ptr, seq.len); + try testing.expectEqual(@as(usize, 3), S.write_count); + try testing.expect(S.last_granted); + try testing.expect(S.last_can_remember); + try testing.expectEqualStrings( + "\x1B]5522;type=write:status=DONE:id=g1\x1B\\" ++ + "\x1B]5522;type=write:status=DONE:id=g2\x1B\\", + S.responses[0..S.responses_len], + ); + S.next_remember = false; + + // Without a read callback reads are denied. + S.responses_len = 0; + const read = "\x1B]5522;type=read:id=r1;dGV4dC9wbGFpbg==\x1B\\"; + vt_write(t, read, read.len); + try testing.expectEqual(@as(usize, 3), S.write_count); + try testing.expectEqualStrings( + "\x1B]5522;type=read:status=EPERM:id=r1\x1B\\", + S.responses[0..S.responses_len], + ); + + // With a read callback the request is served through it. + const R = struct { + var count: usize = 0; + var last_mimes_len: usize = 0; + var last_mime_is_text: bool = false; + var last_list: bool = true; + var last_name_len: usize = 0; + var last_granted: bool = true; + var last_can_remember: bool = true; + + fn clipboardRead( + _: Terminal, + _: ?*anyopaque, + request: *const ClipboardRead, + ) callconv(lib.calling_conv) void { + count += 1; + last_mimes_len = request.mimes_len; + last_mime_is_text = request.mimes_len > 0 and std.mem.eql( + u8, + request.mimes.?[0].ptr[0..request.mimes.?[0].len], + "text/plain", + ); + last_list = request.list; + last_name_len = request.name.len; + last_granted = request.granted; + last_can_remember = request.can_remember; + + const mime: []const u8 = "text/plain"; + const data: []const u8 = "hello"; + const contents = [_]ClipboardContent{.{ + .mime = .init(mime), + .data = .init(data), + }}; + request.reply(request, &.{ + .size = @sizeOf(ClipboardReadReply), + .result = .success, + .contents = &contents, + .contents_len = contents.len, + .available = null, + .available_len = 0, + .remember = false, + }); + } + }; + try testing.expectEqual(Result.success, set(t, .clipboard_read, @ptrCast(&R.clipboardRead))); + S.responses_len = 0; + // name="app" without a password: forwarded for prompts, not + // rememberable. + const read2 = "\x1B]5522;type=read:id=r2:name=YXBw;dGV4dC9wbGFpbg==\x1B\\"; + vt_write(t, read2, read2.len); + try testing.expectEqual(@as(usize, 1), R.count); + try testing.expectEqual(@as(usize, 1), R.last_mimes_len); + try testing.expect(R.last_mime_is_text); + try testing.expect(!R.last_list); + try testing.expectEqual(@as(usize, 3), R.last_name_len); + try testing.expect(!R.last_granted); + try testing.expect(!R.last_can_remember); + try testing.expectEqualStrings( + "\x1B]5522;type=read:status=OK:id=r2\x1B\\" ++ + "\x1B]5522;type=read:status=DATA:id=r2:mime=dGV4dC9wbGFpbg==;aGVsbG8=\x1B\\" ++ + "\x1B]5522;type=read:status=DONE:id=r2\x1B\\", + S.responses[0..S.responses_len], + ); + + // Without a clipboard callback the transaction fails up front. + try testing.expectEqual(Result.success, set(t, .clipboard_write, null)); + S.responses_len = 0; + const begin = "\x1B]5522;type=write:id=c2\x1B\\"; + vt_write(t, begin, begin.len); + try testing.expectEqualStrings( + "\x1B]5522;type=write:status=ENOSYS:id=c2\x1B\\", + S.responses[0..S.responses_len], + ); +} + +test "set clipboard write max bytes" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var responses: [512]u8 = undefined; + var responses_len: usize = 0; + var write_count: usize = 0; + + fn writePty( + _: Terminal, + _: ?*anyopaque, + ptr: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) void { + @memcpy(responses[responses_len..][0..len], ptr[0..len]); + responses_len += len; + } + + fn clipboardWrite( + _: Terminal, + _: ?*anyopaque, + request: *const ClipboardWrite, + ) callconv(lib.calling_conv) void { + write_count += 1; + request.reply(request, &.{ + .size = @sizeOf(ClipboardWriteReply), + .result = .success, + .remember = false, + }); + } + }; + S.responses_len = 0; + S.write_count = 0; + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .clipboard_write, @ptrCast(&S.clipboardWrite))); + + // The built-in default reads back. + var max: usize = 0; + try testing.expectEqual(Result.success, get(t, .clipboard_write_max_bytes, @ptrCast(&max))); + try testing.expectEqual(@as(usize, kitty_clipboard.max_write_size), max); + + // Set a tiny limit; an oversized text write fails with EFBIG and + // never reaches the callback. + const limit: usize = 4; + try testing.expectEqual(Result.success, set(t, .clipboard_write_max_bytes, @ptrCast(&limit))); + try testing.expectEqual(Result.success, get(t, .clipboard_write_max_bytes, @ptrCast(&max))); + try testing.expectEqual(limit, max); + + const seqs = [_][]const u8{ + "\x1B]5522;type=write:id=c1\x1B\\", + "\x1B]5522;type=wdata:mime=dGV4dC9wbGFpbg==;SGVsbA==\x1B\\", // "Hell" + "\x1B]5522;type=wdata:mime=dGV4dC9wbGFpbg==;bw==\x1B\\", // "o" + "\x1B]5522;type=wdata\x1B\\", + }; + for (seqs) |seq| vt_write(t, seq.ptr, seq.len); + try testing.expectEqual(@as(usize, 0), S.write_count); + try testing.expectEqualStrings( + "\x1B]5522;type=write:status=EFBIG:id=c1\x1B\\", + S.responses[0..S.responses_len], + ); + + // A NULL value reverts to the built-in default. + try testing.expectEqual(Result.success, set(t, .clipboard_write_max_bytes, null)); + try testing.expectEqual(Result.success, get(t, .clipboard_write_max_bytes, @ptrCast(&max))); + try testing.expectEqual(@as(usize, kitty_clipboard.max_write_size), max); +} + +test "set clipboard_read callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + var count: usize = 0; + var last_size: usize = 0; + var last_location: clipboard.Location = .standard; + var last_mimes_len: usize = 0; + var last_mime_is_text: bool = false; + var last_list: bool = true; + var last_name_len: usize = 1; + var last_granted: bool = true; + var last_can_remember: bool = true; + var result: clipboard.Read.Status = .success; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + fn clipboardRead( + _: Terminal, + _: ?*anyopaque, + request: *const ClipboardRead, + ) callconv(lib.calling_conv) void { + count += 1; + last_size = request.size; + last_location = request.location; + last_mimes_len = request.mimes_len; + last_mime_is_text = request.mimes_len > 0 and std.mem.eql( + u8, + request.mimes.?[0].ptr[0..request.mimes.?[0].len], + "text/plain", + ); + last_list = request.list; + last_name_len = request.name.len; + last_granted = request.granted; + last_can_remember = request.can_remember; + + const mime: []const u8 = "text/plain"; + const data: []const u8 = "hello"; + const contents = [_]ClipboardContent{.{ + .mime = .init(mime), + .data = .init(data), + }}; + request.reply(request, &.{ + .size = @sizeOf(ClipboardReadReply), + .result = result, + .contents = &contents, + .contents_len = contents.len, + .available = null, + .available_len = 0, + .remember = false, + }); + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + // Without a callback the handler effect is unset and reads are silent. + try testing.expect(t.?.stream.handler.effects.clipboard_read == null); + const read_st = "\x1B]52;c;?\x1B\\"; + vt_write(t, read_st, read_st.len); + try testing.expect(S.last_data == null); + + try testing.expectEqual(Result.success, set(t, .clipboard_read, @ptrCast(&S.clipboardRead))); + try testing.expect(t.?.stream.handler.effects.clipboard_read != null); + + const read_bel = "\x1B]52;p;?\x07"; + vt_write(t, read_bel, read_bel.len); + try testing.expectEqual(1, S.count); + try testing.expectEqual(@sizeOf(ClipboardRead), S.last_size); + try testing.expectEqual(clipboard.Location.primary, S.last_location); + try testing.expectEqual(1, S.last_mimes_len); + try testing.expect(S.last_mime_is_text); + try testing.expect(!S.last_list); + try testing.expectEqual(0, S.last_name_len); + try testing.expect(!S.last_granted); + try testing.expect(!S.last_can_remember); + try testing.expectEqualStrings("\x1B]52;p;aGVsbG8=\x07", S.last_data.?); + + // Denied replies with an empty clipboard. + S.result = .denied; + vt_write(t, read_st, read_st.len); + try testing.expectEqual(2, S.count); + try testing.expectEqualStrings("\x1B]52;c;\x1B\\", S.last_data.?); + + // Clearing the callback uninstalls the handler effect. + try testing.expectEqual(Result.success, set(t, .clipboard_read, null)); + try testing.expect(t.?.stream.handler.effects.clipboard_read == null); } test "pwd_changed without callback is silent" { @@ -2980,11 +5252,8 @@ test "pwd_changed without callback is silent" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -2999,11 +5268,8 @@ test "set size callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3046,11 +5312,8 @@ test "size without callback is silent" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3058,16 +5321,116 @@ test "size without callback is silent" { vt_write(t, "\x1B[18t", 5); } +test "mode 2048 enable and disable use C callbacks" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var data: [128]u8 = undefined; + var len: usize = 0; + var calls: usize = 0; + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, length: usize) callconv(lib.calling_conv) void { + @memcpy(data[0..length], ptr[0..length]); + len = length; + calls += 1; + } + + fn sizeCb(_: Terminal, _: ?*anyopaque, out_size: *size_report.Size) callconv(lib.calling_conv) bool { + out_size.* = .{ + .rows = 24, + .columns = 80, + .cell_width = 8, + .cell_height = 16, + }; + return true; + } + }; + S.len = 0; + S.calls = 0; + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .size_cb, @ptrCast(&S.sizeCb))); + + const enable = "\x1B[?2048h"; + const disable = "\x1B[?2048l"; + vt_write(t, enable, enable.len); + vt_write(t, enable, enable.len); + + try testing.expectEqual(@as(usize, 2), S.calls); + try testing.expectEqualStrings("\x1B[48;24;80;384;640t", S.data[0..S.len]); + vt_write(t, disable, disable.len); + + try testing.expectEqual(@as(usize, 2), S.calls); + try testing.expect(!t.?.terminal.modes.get(.in_band_size_reports)); +} + +test "mode 2048 enable tolerates missing C callbacks" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var writes: usize = 0; + var sizes: usize = 0; + + fn writePty(_: Terminal, _: ?*anyopaque, _: [*]const u8, _: usize) callconv(lib.calling_conv) void { + writes += 1; + } + + fn sizeCb(_: Terminal, _: ?*anyopaque, out_size: *size_report.Size) callconv(lib.calling_conv) bool { + sizes += 1; + out_size.* = .{ + .rows = 24, + .columns = 80, + .cell_width = 8, + .cell_height = 16, + }; + return true; + } + }; + S.writes = 0; + S.sizes = 0; + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + const sequence = "\x1B[?2048h"; + vt_write(t, sequence, sequence.len); + + try testing.expectEqual(@as(usize, 0), S.writes); + try testing.expect(t.?.terminal.modes.get(.in_band_size_reports)); + var no_write: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &no_write, + 80, + 24, + )); + defer free(no_write); + try testing.expectEqual(Result.success, set(no_write, .size_cb, @ptrCast(&S.sizeCb))); + vt_write(no_write, sequence, sequence.len); + try testing.expectEqual(@as(usize, 1), S.sizes); + try testing.expect(no_write.?.terminal.modes.get(.in_band_size_reports)); +} + test "set device_attributes callback primary" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3117,11 +5480,8 @@ test "set device_attributes callback secondary" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3171,11 +5531,8 @@ test "set device_attributes callback tertiary" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3225,11 +5582,8 @@ test "device_attributes without callback uses default" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3261,11 +5615,8 @@ test "device_attributes callback returns false uses default" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3302,11 +5653,8 @@ test "set and get title" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3341,11 +5689,8 @@ test "set and get pwd" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3373,11 +5718,8 @@ test "get title set via vt_write" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3389,24 +5731,81 @@ test "get title set via vt_write" { try testing.expectEqualStrings("VT Title", title.ptr[0..title.len]); } +test "title report requires explicit opt in" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + 80, + 24, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |data| testing.allocator.free(data); + last_data = null; + } + + fn writePty( + _: Terminal, + _: ?*anyopaque, + ptr: [*]const u8, + len: usize, + ) callconv(lib.calling_conv) void { + if (last_data) |data| testing.allocator.free(data); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + }; + S.last_data = null; + defer S.deinit(); + + try testing.expectEqual( + Result.success, + set(t, .write_pty, @ptrCast(&S.writePty)), + ); + + const set_title = "\x1B]2;echo vulnerable\x1B\\"; + const query_title = "\x1B[21t"; + vt_write(t, set_title, set_title.len); + + // WRITE_PTY alone must not enable the security-sensitive response. + vt_write(t, query_title, query_title.len); + try testing.expect(S.last_data == null); + + const enabled = true; + try testing.expectEqual(Result.success, set(t, .title_report, &enabled)); + vt_write(t, query_title, query_title.len); + try testing.expectEqualStrings( + "\x1b]lecho vulnerable\x1b\\", + S.last_data.?, + ); + + // NULL restores the secure default. + S.deinit(); + try testing.expectEqual(Result.success, set(t, .title_report, null)); + vt_write(t, query_title, query_title.len); + try testing.expect(S.last_data == null); +} + test "resize updates pixel dimensions" { var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); - try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); + // Pixel geometry must still be applied when the cell dimensions match. + try testing.expectEqual(Result.success, resize(t, 80, 24, 9, 18)); const zt = t.?.terminal; - try testing.expectEqual(@as(u32, 100 * 9), zt.width_px); - try testing.expectEqual(@as(u32, 40 * 18), zt.height_px); + try testing.expectEqual(@as(u32, 80 * 9), zt.width_px); + try testing.expectEqual(@as(u32, 24 * 18), zt.height_px); } test "resize pixel overflow saturates" { @@ -3414,11 +5813,8 @@ test "resize pixel overflow saturates" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3434,18 +5830,16 @@ test "resize disables synchronized output" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); const zt = t.?.terminal; zt.modes.set(.synchronized_output, true); - try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); + // The terminal-level reset must run even if grid work is unnecessary. + try testing.expectEqual(Result.success, resize(t, 80, 24, 9, 18)); try testing.expect(!zt.modes.get(.synchronized_output)); } @@ -3454,11 +5848,8 @@ test "resize sends in-band size report" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3495,11 +5886,8 @@ test "resize no size report without mode 2048" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3523,11 +5911,8 @@ test "resize in-band report without write_pty callback" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3545,11 +5930,8 @@ test "resize zero cols" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3561,11 +5943,8 @@ test "resize zero rows" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3577,11 +5956,8 @@ test "grid_ref out of bounds" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3597,11 +5973,8 @@ test "set and get color_foreground" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3625,11 +5998,8 @@ test "set and get color_background" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3650,11 +6020,8 @@ test "set and get color_cursor" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3675,11 +6042,8 @@ test "set and get color_palette" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3706,11 +6070,8 @@ test "get color default vs effective with override" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3753,11 +6114,8 @@ test "get color default returns no_value when unset" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3772,11 +6130,8 @@ test "get color_palette_default vs current" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3805,11 +6160,8 @@ test "set color sets dirty flag" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ - .cols = 80, - .rows = 24, - .max_scrollback = 0, - }, + 80, + 24, )); defer free(t); @@ -3822,11 +6174,14 @@ test "set color sets dirty flag" { } test "set glyph protocol disables APC handling and clears glossary" { + if (comptime !build_options.glyph_protocol) return error.SkipZigTest; + var t: Terminal = null; try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer free(t); @@ -3853,7 +6208,8 @@ test "get_multi success" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer free(t); @@ -3874,7 +6230,8 @@ test "get_multi error sets out_written" { try testing.expectEqual(Result.success, new( &lib.alloc.test_allocator, &t, - .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + 80, + 24, )); defer free(t); diff --git a/vendor/libghostty-vt/src/terminal/c/types-schema-verify.py b/vendor/libghostty-vt/src/terminal/c/types-schema-verify.py new file mode 100644 index 00000000..1a8e064d --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/types-schema-verify.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Validate the ABI manifest exported by a native or WebAssembly library.""" + +from __future__ import annotations + +import argparse +import ctypes +import json +import sys +from pathlib import Path +from typing import Any + +try: + import jsonschema +except ImportError as error: + raise SystemExit( + "missing ABI schema verifier dependencies; run this inside " + "`nix develop`" + ) from error + + +def load_native_manifest(path: Path) -> bytes: + """Call ghostty_type_json in a native shared library.""" + library = ctypes.CDLL(str(path.resolve())) + type_json = library.ghostty_type_json + type_json.argtypes = () + type_json.restype = ctypes.c_char_p + + result = type_json() + if result is None: + raise RuntimeError("ghostty_type_json returned NULL") + return result + + +def load_wasm_manifest(path: Path) -> bytes: + """Call ghostty_type_json and read its result from WebAssembly memory.""" + try: + import wasmtime + except ImportError as error: + raise SystemExit( + "missing WebAssembly verifier dependencies; run this inside " + "`nix develop`" + ) from error + + engine = wasmtime.Engine() + module = wasmtime.Module.from_file(engine, str(path)) + store = wasmtime.Store(engine) + instance = wasmtime.Instance(store, module, []) + exports = instance.exports(store) + memory = exports["memory"] + type_json = exports["ghostty_type_json"] + + pointer = type_json(store) + data = memory.read(store, pointer, memory.data_len(store)) + terminator = data.find(b"\0") + if terminator < 0: + raise RuntimeError("ghostty_type_json result is not NUL terminated") + return bytes(data[:terminator]) + + +def load_manifest(path: Path) -> dict[str, Any]: + """Execute the public export and decode its JSON result.""" + encoded = ( + load_wasm_manifest(path) + if path.suffix.lower() == ".wasm" + else load_native_manifest(path) + ) + value = json.loads(encoded) + if not isinstance(value, dict): + raise ValueError("ghostty_type_json did not return a JSON object") + return value + + +def format_path(parts: list[object]) -> str: + """Format a jsonschema error path for command-line output.""" + return "/" + "/".join(str(part) for part in parts) + + +def validate(schema_path: Path, library_path: Path) -> None: + """Validate the schema itself and the manifest returned by the library.""" + schema = json.loads(schema_path.read_bytes()) + validator_type = jsonschema.validators.validator_for(schema) + validator_type.check_schema(schema) + + manifest = load_manifest(library_path) + errors = sorted( + validator_type(schema).iter_errors(manifest), + key=lambda error: list(error.absolute_path), + ) + if errors: + for error in errors: + print( + f"{format_path(list(error.absolute_path))}: {error.message}", + file=sys.stderr, + ) + raise SystemExit(f"ABI manifest failed {schema_path}") + + abi = manifest["abi"] + print( + f"validated {abi['target']}-{abi['os']} ABI manifest " + f"({len(manifest['types'])} types)" + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("schema", type=Path) + parser.add_argument("library", type=Path) + args = parser.parse_args() + validate(args.schema, args.library) + + +if __name__ == "__main__": + main() diff --git a/vendor/libghostty-vt/src/terminal/c/types.schema.json b/vendor/libghostty-vt/src/terminal/c/types.schema.json new file mode 100644 index 00000000..38108ebe --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/types.schema.json @@ -0,0 +1,506 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "libghostty-vt ABI type manifest", + "description": "Schema for the JSON returned by ghostty_type_json.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "abi", "library_version", "commit", "dirty", "types"], + "properties": { + "schema": { + "const": 1 + }, + "abi": { + "$ref": "#/$defs/abi" + }, + "library_version": { + "type": "string", + "minLength": 1 + }, + "commit": { + "type": ["string", "null"], + "minLength": 1 + }, + "dirty": { + "type": ["boolean", "null"] + }, + "types": { + "type": "object", + "minProperties": 1, + "propertyNames": { + "pattern": "^Ghostty[A-Za-z0-9_]+$" + }, + "additionalProperties": { + "$ref": "#/$defs/typeDescriptor" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveInteger": { + "type": "integer", + "minimum": 1 + }, + "typeReference": { + "type": "string", + "pattern": "^(Ghostty[A-Za-z0-9_]+|bool|f32|f64|function|[iu][1-9][0-9]*|opaque|void)$" + }, + "integerTypeReference": { + "type": "string", + "pattern": "^[iu][1-9][0-9]*$" + }, + "abi": { + "type": "object", + "additionalProperties": false, + "required": [ + "target", + "os", + "environment", + "pointer_size", + "usize_size", + "max_alignment", + "endian" + ], + "properties": { + "target": { + "type": "string", + "minLength": 1 + }, + "os": { + "type": "string", + "minLength": 1 + }, + "environment": { + "type": "string", + "minLength": 1 + }, + "pointer_size": { + "$ref": "#/$defs/positiveInteger" + }, + "usize_size": { + "$ref": "#/$defs/positiveInteger" + }, + "max_alignment": { + "description": "Maximum fundamental C ABI alignment in bytes.", + "$ref": "#/$defs/positiveInteger" + }, + "endian": { + "enum": ["little", "big"] + } + } + }, + "fieldBase": { + "type": "object", + "required": ["offset", "size", "type"], + "properties": { + "offset": { + "$ref": "#/$defs/nonNegativeInteger" + }, + "size": { + "$ref": "#/$defs/nonNegativeInteger" + } + } + }, + "plainField": { + "allOf": [ + { + "$ref": "#/$defs/fieldBase" + }, + { + "properties": { + "type": { + "$ref": "#/$defs/typeReference" + } + } + } + ], + "unevaluatedProperties": false + }, + "arrayField": { + "allOf": [ + { + "$ref": "#/$defs/fieldBase" + }, + { + "required": ["elem", "count"], + "properties": { + "type": { + "const": "array" + }, + "elem": { + "$ref": "#/$defs/typeReference" + }, + "count": { + "$ref": "#/$defs/nonNegativeInteger" + } + } + } + ], + "unevaluatedProperties": false + }, + "pointerField": { + "allOf": [ + { + "$ref": "#/$defs/fieldBase" + }, + { + "required": ["elem", "const"], + "properties": { + "type": { + "const": "pointer" + }, + "elem": { + "$ref": "#/$defs/typeReference" + }, + "const": { + "type": "boolean" + }, + "nullable": { + "const": true + } + } + } + ], + "unevaluatedProperties": false + }, + "taggedUnionField": { + "allOf": [ + { + "$ref": "#/$defs/fieldBase" + }, + { + "required": ["tag", "arms"], + "properties": { + "type": { + "$ref": "#/$defs/typeReference" + }, + "tag": { + "type": "string", + "minLength": 1 + }, + "arms": { + "type": "object", + "minProperties": 1, + "propertyNames": { + "pattern": "^[A-Z][A-Z0-9_]*$" + }, + "additionalProperties": { + "type": ["string", "null"] + } + } + } + } + ], + "unevaluatedProperties": false + }, + "field": { + "oneOf": [ + { + "$ref": "#/$defs/plainField" + }, + { + "$ref": "#/$defs/arrayField" + }, + { + "$ref": "#/$defs/pointerField" + }, + { + "$ref": "#/$defs/taggedUnionField" + } + ] + }, + "fields": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/field" + } + }, + "bitBase": { + "type": "object", + "required": ["lsb", "width"], + "properties": { + "lsb": { + "description": "Least-significant bit relative to the containing numerical value.", + "$ref": "#/$defs/nonNegativeInteger" + }, + "width": { + "description": "Physical width of this field in bits.", + "$ref": "#/$defs/positiveInteger" + } + } + }, + "scalarBit": { + "allOf": [ + { + "$ref": "#/$defs/bitBase" + }, + { + "required": ["type"], + "properties": { + "type": { + "$ref": "#/$defs/typeReference" + } + } + } + ], + "unevaluatedProperties": false + }, + "packedBit": { + "allOf": [ + { + "$ref": "#/$defs/bitBase" + }, + { + "required": ["kind", "bits"], + "properties": { + "kind": { + "const": "packed" + }, + "bits": { + "$ref": "#/$defs/bits" + } + } + } + ], + "unevaluatedProperties": false + }, + "packedArm": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "width", "bits"], + "properties": { + "kind": { + "const": "packed" + }, + "width": { + "description": "Physical width of this inline arm in bits.", + "$ref": "#/$defs/positiveInteger" + }, + "bits": { + "$ref": "#/$defs/bits" + } + } + }, + "taggedUnionBit": { + "allOf": [ + { + "$ref": "#/$defs/bitBase" + }, + { + "required": ["kind", "tag", "arms"], + "properties": { + "kind": { + "const": "union" + }, + "tag": { + "type": "string", + "minLength": 1 + }, + "arms": { + "type": "object", + "minProperties": 1, + "propertyNames": { + "pattern": "^[A-Z][A-Z0-9_]*$" + }, + "additionalProperties": { + "oneOf": [ + { + "$ref": "#/$defs/packedArm" + }, + { + "type": "null" + } + ] + } + } + } + } + ], + "unevaluatedProperties": false + }, + "bit": { + "oneOf": [ + { + "$ref": "#/$defs/scalarBit" + }, + { + "$ref": "#/$defs/packedBit" + }, + { + "$ref": "#/$defs/taggedUnionBit" + } + ] + }, + "bits": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "$ref": "#/$defs/bit" + } + }, + "descriptorBase": { + "type": "object", + "required": ["kind", "size", "align"], + "properties": { + "size": { + "$ref": "#/$defs/nonNegativeInteger" + }, + "align": { + "$ref": "#/$defs/positiveInteger" + } + } + }, + "structDescriptor": { + "allOf": [ + { + "$ref": "#/$defs/descriptorBase" + }, + { + "required": ["fields"], + "properties": { + "kind": { + "const": "struct" + }, + "fields": { + "$ref": "#/$defs/fields" + } + } + } + ], + "unevaluatedProperties": false + }, + "unionDescriptor": { + "allOf": [ + { + "$ref": "#/$defs/descriptorBase" + }, + { + "required": ["fields"], + "properties": { + "kind": { + "const": "union" + }, + "fields": { + "$ref": "#/$defs/fields" + } + } + } + ], + "unevaluatedProperties": false + }, + "enumDescriptor": { + "allOf": [ + { + "$ref": "#/$defs/descriptorBase" + }, + { + "required": ["underlying", "prefix", "values"], + "properties": { + "kind": { + "const": "enum" + }, + "underlying": { + "const": "i32" + }, + "prefix": { + "type": "string", + "minLength": 1 + }, + "values": { + "type": "object", + "minProperties": 1, + "propertyNames": { + "pattern": "^[A-Z][A-Z0-9_]*$" + }, + "additionalProperties": { + "type": "integer" + } + } + } + } + ], + "unevaluatedProperties": false + }, + "packedDescriptor": { + "allOf": [ + { + "$ref": "#/$defs/descriptorBase" + }, + { + "required": ["underlying", "bits"], + "properties": { + "kind": { + "const": "packed" + }, + "underlying": { + "description": "Integer backing type used to interpret the packed value.", + "$ref": "#/$defs/integerTypeReference" + }, + "bits": { + "$ref": "#/$defs/bits" + } + } + } + ], + "unevaluatedProperties": false + }, + "aliasDescriptor": { + "allOf": [ + { + "$ref": "#/$defs/descriptorBase" + }, + { + "required": ["type"], + "properties": { + "kind": { + "const": "alias" + }, + "type": { + "$ref": "#/$defs/typeReference" + } + } + } + ], + "unevaluatedProperties": false + }, + "opaqueDescriptor": { + "allOf": [ + { + "$ref": "#/$defs/descriptorBase" + }, + { + "properties": { + "kind": { + "const": "opaque" + } + } + } + ], + "unevaluatedProperties": false + }, + "typeDescriptor": { + "oneOf": [ + { + "$ref": "#/$defs/structDescriptor" + }, + { + "$ref": "#/$defs/unionDescriptor" + }, + { + "$ref": "#/$defs/enumDescriptor" + }, + { + "$ref": "#/$defs/packedDescriptor" + }, + { + "$ref": "#/$defs/aliasDescriptor" + }, + { + "$ref": "#/$defs/opaqueDescriptor" + } + ] + } + } +} diff --git a/vendor/libghostty-vt/src/terminal/c/types.zig b/vendor/libghostty-vt/src/terminal/c/types.zig index f160f385..4184de82 100644 --- a/vendor/libghostty-vt/src/terminal/c/types.zig +++ b/vendor/libghostty-vt/src/terminal/c/types.zig @@ -1,25 +1,54 @@ -//! Comptime-generated metadata describing the layout of all C API -//! extern structs for the current target. +//! Comptime-generated ABI metadata for the public libghostty-vt C types. //! -//! This is embedded in the binary as a const string and exposed via -//! `ghostty_type_json` so that WASM (and other FFI) consumers can -//! build structs without hardcoding byte offsets. +//! The manifest is embedded in the library and returned by +//! `ghostty_type_json`. It is intended for FFI consumers that cannot use the +//! C headers directly, most notably WebAssembly hosts. Its format is defined +//! by `types.schema.json`. const std = @import("std"); +const builtin = @import("builtin"); +const build_options = @import("terminal_options"); const lib = @import("../lib.zig"); +const c_abi = @import("../../lib/c_abi.zig"); + const color = @import("../color.zig"); -const color_c = @import("color.zig"); -const mouse_event = @import("mouse_event.zig"); +const clipboard = @import("../clipboard.zig"); +const device_status = @import("../device_status.zig"); +const focus_pkg = @import("../focus.zig"); +const formatter_pkg = @import("../formatter.zig"); +const modes_pkg = @import("../modes.zig"); +const mouse_pkg = @import("../mouse.zig"); +const page = @import("../page.zig"); const point = @import("../point.zig"); -const size_report = @import("size_report.zig"); +const Selection = @import("../Selection.zig"); +const sgr = @import("../sgr.zig"); -const terminal = @import("terminal.zig"); +const input_config = @import("../../input/config.zig"); +const input_key = @import("../../input/key.zig"); +const input_mouse = @import("../../input/mouse.zig"); + +const build_info = @import("build_info.zig"); +const cell = @import("cell.zig"); +const color_c = @import("color.zig"); const formatter = @import("formatter.zig"); +const grid_ref = @import("grid_ref.zig"); +const io = @import("io.zig"); +const key_encode = @import("key_encode.zig"); +const kitty_graphics = @import("kitty_graphics.zig"); +const mouse_encode = @import("mouse_encode.zig"); +const mouse_event = @import("mouse_event.zig"); +const osc = @import("osc.zig"); +const paste = @import("paste.zig"); +const render = @import("render.zig"); +const result = @import("result.zig"); +const row = @import("row.zig"); +const search = @import("search.zig"); const selection = @import("selection.zig"); const selection_gesture = @import("selection_gesture.zig"); -const render = @import("render.zig"); -const style_c = @import("style.zig"); -const mouse_encode = @import("mouse_encode.zig"); -const grid_ref = @import("grid_ref.zig"); +const size_report = @import("size_report.zig"); +const snapshot = @import("snapshot.zig"); +const style = @import("style.zig"); +const sys = @import("sys.zig"); +const terminal = @import("terminal.zig"); /// C: GhosttySurfacePosition pub const SurfacePosition = extern struct { @@ -33,233 +62,1113 @@ pub const Codepoints = extern struct { len: usize = 0, }; -/// All C API structs and their Ghostty C names. -pub const structs: std.StaticStringMap(StructInfo) = structs: { - @setEvalBranchQuota(10_000); - break :structs .initComptime(.{ - .{ "GhosttyBuffer", StructInfo.init(lib.Buffer) }, - .{ "GhosttyClipboardContent", StructInfo.init(terminal.ClipboardContent) }, - .{ "GhosttyClipboardWrite", StructInfo.init(terminal.ClipboardWrite) }, - .{ "GhosttyCodepoints", StructInfo.init(Codepoints) }, - .{ "GhosttyColorPaletteMask", StructInfo.init(color_c.PaletteMask) }, - .{ "GhosttyColorRgb", StructInfo.init(color.RGB.C) }, - .{ "GhosttyColorX11Entry", StructInfo.init(color_c.X11Entry) }, - .{ "GhosttyDeviceAttributes", StructInfo.init(terminal.DeviceAttributes) }, - .{ "GhosttyDeviceAttributesPrimary", StructInfo.init(terminal.DeviceAttributes.Primary) }, - .{ "GhosttyDeviceAttributesSecondary", StructInfo.init(terminal.DeviceAttributes.Secondary) }, - .{ "GhosttyDeviceAttributesTertiary", StructInfo.init(terminal.DeviceAttributes.Tertiary) }, - .{ "GhosttyFormatterTerminalOptions", StructInfo.init(formatter.TerminalOptions) }, - .{ "GhosttySelection", StructInfo.init(selection.CSelection) }, - .{ "GhosttyTerminalSelectWordOptions", StructInfo.init(selection.SelectWordOptions) }, - .{ "GhosttyTerminalSelectWordBetweenOptions", StructInfo.init(selection.SelectWordBetweenOptions) }, - .{ "GhosttyTerminalSelectLineOptions", StructInfo.init(selection.SelectLineOptions) }, - .{ "GhosttyFormatterTerminalExtra", StructInfo.init(formatter.TerminalOptions.Extra) }, - .{ "GhosttyFormatterScreenExtra", StructInfo.init(formatter.ScreenOptions.Extra) }, - .{ "GhosttyGridRef", StructInfo.init(grid_ref.CGridRef) }, - .{ "GhosttyMouseEncoderSize", StructInfo.init(mouse_encode.Size) }, - .{ "GhosttyMousePosition", StructInfo.init(mouse_event.Position) }, - .{ "GhosttyPoint", StructInfo.init(point.Point.C) }, - .{ "GhosttyPointCoordinate", StructInfo.init(point.Coordinate) }, - .{ "GhosttyRenderStateColors", StructInfo.init(render.Colors) }, - .{ "GhosttySelectionGestureBehaviors", StructInfo.init(selection_gesture.Behaviors) }, - .{ "GhosttySelectionGestureGeometry", StructInfo.init(selection_gesture.Geometry) }, - .{ "GhosttySizeReportSize", StructInfo.init(size_report.Size) }, - .{ "GhosttyString", StructInfo.init(lib.String) }, - .{ "GhosttySurfacePosition", StructInfo.init(SurfacePosition) }, - .{ "GhosttyStyle", StructInfo.init(style_c.Style) }, - .{ "GhosttyStyleColor", StructInfo.init(style_c.Color) }, - .{ "GhosttyTerminalOptions", StructInfo.init(terminal.Options) }, - .{ "GhosttyTerminalScrollbar", StructInfo.init(terminal.TerminalScrollbar) }, - .{ "GhosttyTerminalScrollViewport", StructInfo.init(terminal.ScrollViewport) }, - }); +const TypeDecl = struct { + name: []const u8, + T: type, + kind: Kind, + prefix: []const u8 = "", + sentinel_suffix: []const u8 = "MAX_VALUE", + alias_type: []const u8 = "", + tagged_union: ?TaggedUnion = null, + union_field_names_T: ?type = null, + + const Kind = enum { + @"struct", + @"union", + @"enum", + @"packed", + alias, + @"opaque", + }; + + const TaggedUnion = struct { + tag_field: []const u8, + value_field: []const u8, + arm_source: ArmSource, + + const ArmSource = enum { + fields, + generated, + }; + }; + + fn initStruct(comptime name: []const u8, comptime T: type) TypeDecl { + return .{ .name = name, .T = T, .kind = .@"struct" }; + } + + fn initTaggedStruct( + comptime name: []const u8, + comptime T: type, + comptime tag_field: []const u8, + comptime value_field: []const u8, + comptime arm_source: TaggedUnion.ArmSource, + ) TypeDecl { + return .{ + .name = name, + .T = T, + .kind = .@"struct", + .tagged_union = .{ + .tag_field = tag_field, + .value_field = value_field, + .arm_source = arm_source, + }, + }; + } + + fn initUnion( + comptime name: []const u8, + comptime T: type, + comptime field_names_T: ?type, + ) TypeDecl { + return .{ + .name = name, + .T = T, + .kind = .@"union", + .union_field_names_T = field_names_T, + }; + } + + fn initEnum( + comptime name: []const u8, + comptime T: type, + comptime prefix: []const u8, + ) TypeDecl { + return .{ .name = name, .T = T, .kind = .@"enum", .prefix = prefix }; + } + + fn initEnumSentinel( + comptime name: []const u8, + comptime T: type, + comptime prefix: []const u8, + comptime sentinel_suffix: []const u8, + ) TypeDecl { + return .{ + .name = name, + .T = T, + .kind = .@"enum", + .prefix = prefix, + .sentinel_suffix = sentinel_suffix, + }; + } + + fn initPacked(comptime name: []const u8, comptime T: type) TypeDecl { + return .{ .name = name, .T = T, .kind = .@"packed" }; + } + + fn initAlias( + comptime name: []const u8, + comptime T: type, + comptime alias_type: []const u8, + ) TypeDecl { + return .{ .name = name, .T = T, .kind = .alias, .alias_type = alias_type }; + } + + fn initOpaque(comptime name: []const u8) TypeDecl { + return .{ .name = name, .T = *anyopaque, .kind = .@"opaque" }; + } +}; + +/// Public C types. Names and enum prefixes are intentionally explicit because +/// Zig identifiers are not the C API contract. +const type_decls = [_]TypeDecl{ + .initStruct("GhosttyAllocator", lib.alloc.Allocator), + .initStruct("GhosttyAllocatorVtable", lib.alloc.VTable), + .initStruct("GhosttyBuffer", lib.Buffer), + .initStruct("GhosttyCellsView", cell.CellsView), + .initStruct("GhosttyClipboardContent", terminal.ClipboardContent), + .initStruct("GhosttyClipboardRead", terminal.ClipboardRead), + .initStruct("GhosttyClipboardReadReply", terminal.ClipboardReadReply), + .initStruct("GhosttyClipboardWrite", terminal.ClipboardWrite), + .initStruct("GhosttyClipboardWriteReply", terminal.ClipboardWriteReply), + .initStruct("GhosttyCodepoints", Codepoints), + .initStruct("GhosttyColorPaletteMask", color_c.PaletteMask), + .initStruct("GhosttyColorRgb", color.RGB.C), + .initStruct("GhosttyColorX11Entry", color_c.X11Entry), + .initStruct("GhosttyDeviceAttributes", terminal.DeviceAttributes), + .initStruct("GhosttyDeviceAttributesPrimary", terminal.DeviceAttributes.Primary), + .initStruct("GhosttyDeviceAttributesSecondary", terminal.DeviceAttributes.Secondary), + .initStruct("GhosttyDeviceAttributesTertiary", terminal.DeviceAttributes.Tertiary), + .initStruct("GhosttyFormatterScreenExtra", formatter.ScreenOptions.Extra), + .initStruct("GhosttyFormatterTerminalExtra", formatter.TerminalOptions.Extra), + .initStruct("GhosttyFormatterTerminalOptions", formatter.TerminalOptions), + .initStruct("GhosttyGridRef", grid_ref.CGridRef), + .initStruct("GhosttyKittyGraphicsPlacementRenderInfo", kitty_graphics.PlacementRenderInfo), + .initStruct("GhosttyMimeReader", io.MimeReader), + .initStruct("GhosttyMouseEncoderSize", mouse_encode.Size), + .initStruct("GhosttyMousePosition", mouse_event.Position), + .initStruct("GhosttyPaste", paste.Request), + .initTaggedStruct("GhosttyPoint", point.Point.C, "tag", "value", .generated), + .initStruct("GhosttyPointCoordinate", point.Coordinate), + .initUnion("GhosttyPointValue", point.Point.CValue, point.Point.C), + .initStruct("GhosttyReader", io.Reader), + .initStruct("GhosttyRenderStateColors", render.Colors), + .initStruct("GhosttyRenderStateCursor", render.Cursor), + .initStruct("GhosttyRenderStateRowSelection", render.RowSelection), + .initStruct("GhosttySelection", selection.CSelection), + .initStruct("GhosttySelectionBuffer", selection.CSelectionBuffer), + .initStruct("GhosttySelectionGestureBehaviors", selection_gesture.Behaviors), + .initStruct("GhosttySelectionGestureGeometry", selection_gesture.Geometry), + .initTaggedStruct("GhosttySgrAttribute", sgr.Attribute.C, "tag", "value", .generated), + .initStruct("GhosttySgrUnknown", sgr.Attribute.Unknown.C), + .initUnion("GhosttySgrAttributeValue", sgr.Attribute.CValue, sgr.Attribute.C), + .initStruct("GhosttySizeReportSize", size_report.Size), + .initStruct("GhosttyString", lib.String), + .initStruct("GhosttySurfacePosition", SurfacePosition), + .initStruct("GhosttyStyle", style.Style), + .initTaggedStruct("GhosttyStyleColor", style.Color, "tag", "value", .fields), + .initUnion("GhosttyStyleColorValue", style.ColorValue, null), + .initStruct("GhosttySysImage", sys.Image), + .initStruct("GhosttyTerminalDesktopNotification", terminal.DesktopNotification), + .initStruct("GhosttyTerminalModeConfig", terminal.ModeConfig), + .initStruct("GhosttyTerminalProgressReport", terminal.ProgressReport), + .initStruct("GhosttyTerminalScrollbar", terminal.TerminalScrollbar), + .initTaggedStruct("GhosttyTerminalScrollViewport", terminal.ScrollViewport, "tag", "value", .generated), + .initUnion( + "GhosttyTerminalScrollViewportValue", + terminal.ZigTerminal.ScrollViewport.CValue, + terminal.ZigTerminal.ScrollViewport.C, + ), + .initStruct("GhosttyTerminalSelectLineOptions", selection.SelectLineOptions), + .initStruct("GhosttyTerminalSelectWordBetweenOptions", selection.SelectWordBetweenOptions), + .initStruct("GhosttyTerminalSelectWordOptions", selection.SelectWordOptions), + .initStruct("GhosttyTerminalSelectionFormatOptions", selection.FormatOptions), + .initTaggedStruct("GhosttyTerminalUnknownSequence", terminal.UnknownSequence.C, "tag", "value", .generated), + .initStruct("GhosttyTerminalUnknownStringSequence", terminal.UnknownStringSequence), + .initUnion( + "GhosttyTerminalUnknownSequenceValue", + terminal.UnknownSequence.CValue, + terminal.UnknownSequence.C, + ), + .initStruct("GhosttyWriter", io.Writer), + + .initEnumSentinel("GhosttyResult", result.Result, "GHOSTTY_", "RESULT_MAX_VALUE"), + .initEnum("GhosttyBuildInfo", build_info.BuildInfo, "GHOSTTY_BUILD_INFO_"), + .initEnumSentinel("GhosttyOptimizeMode", build_info.OptimizeMode, "GHOSTTY_OPTIMIZE_", "MODE_MAX_VALUE"), + .initEnumSentinel("GhosttyCellContentTag", cell.ContentTag, "GHOSTTY_CELL_CONTENT_", "TAG_MAX_VALUE"), + .initEnum("GhosttyCellData", cell.CellData, "GHOSTTY_CELL_DATA_"), + .initEnum("GhosttyCellSemanticContent", cell.SemanticContent, "GHOSTTY_CELL_SEMANTIC_"), + .initEnum("GhosttyCellWide", cell.Wide, "GHOSTTY_CELL_WIDE_"), + .initEnum("GhosttyClipboardLocation", clipboard.Location, "GHOSTTY_CLIPBOARD_LOCATION_"), + .initEnum("GhosttyClipboardReadResult", clipboard.Read.Status, "GHOSTTY_CLIPBOARD_READ_RESULT_"), + .initEnum("GhosttyClipboardWriteResult", clipboard.Write.Status, "GHOSTTY_CLIPBOARD_WRITE_RESULT_"), + .initEnum("GhosttyColorScheme", device_status.ColorScheme, "GHOSTTY_COLOR_SCHEME_"), + .initEnum("GhosttyFocusEvent", focus_pkg.Event, "GHOSTTY_FOCUS_"), + .initEnum("GhosttyFormatterFormat", formatter_pkg.Format, "GHOSTTY_FORMATTER_FORMAT_"), + .initEnum("GhosttyKey", input_key.Key, "GHOSTTY_KEY_"), + .initEnum("GhosttyKeyAction", input_key.Action, "GHOSTTY_KEY_ACTION_"), + .initEnum("GhosttyKeyEncoderOption", key_encode.Option, "GHOSTTY_KEY_ENCODER_OPT_"), + .initEnum("GhosttyKittyGraphicsData", kitty_graphics.Data, "GHOSTTY_KITTY_GRAPHICS_DATA_"), + .initEnum("GhosttyKittyGraphicsImageData", kitty_graphics.ImageData, "GHOSTTY_KITTY_IMAGE_DATA_"), + .initEnum("GhosttyKittyGraphicsPlacementData", kitty_graphics.PlacementData, "GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_"), + .initEnum("GhosttyKittyGraphicsPlacementIteratorOption", kitty_graphics.PlacementIteratorOption, "GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_"), + .initEnum("GhosttyKittyImageCompression", kitty_graphics.ImageCompression, "GHOSTTY_KITTY_IMAGE_COMPRESSION_"), + .initEnum("GhosttyKittyImageFormat", kitty_graphics.ImageFormat, "GHOSTTY_KITTY_IMAGE_FORMAT_"), + .initEnum("GhosttyKittyPlacementLayer", kitty_graphics.PlacementLayer, "GHOSTTY_KITTY_PLACEMENT_LAYER_"), + .initEnum("GhosttyModeReportState", modes_pkg.Report.State, "GHOSTTY_MODE_REPORT_"), + .initEnum("GhosttyMouseAction", input_mouse.Action, "GHOSTTY_MOUSE_ACTION_"), + .initEnum("GhosttyMouseButton", input_mouse.Button, "GHOSTTY_MOUSE_BUTTON_"), + .initEnum("GhosttyMouseEncoderOption", mouse_encode.Option, "GHOSTTY_MOUSE_ENCODER_OPT_"), + .initEnum("GhosttyMouseFormat", mouse_pkg.Format, "GHOSTTY_MOUSE_FORMAT_"), + .initEnum("GhosttyMouseTrackingMode", mouse_pkg.Event, "GHOSTTY_MOUSE_TRACKING_"), + .initEnum("GhosttyOptionAsAlt", input_config.OptionAsAlt, "GHOSTTY_OPTION_AS_ALT_"), + .initEnum("GhosttyOscCommandData", osc.CommandData, "GHOSTTY_OSC_DATA_"), + .initEnumSentinel( + "GhosttyOscCommandType", + osc.CommandType, + "GHOSTTY_OSC_COMMAND_", + "TYPE_MAX_VALUE", + ), + .initEnum("GhosttyPasteSource", paste.Source, "GHOSTTY_PASTE_SOURCE_"), + .initEnum("GhosttyPointTag", point.Tag, "GHOSTTY_POINT_TAG_"), + .initEnum("GhosttyRenderStateCursorVisualStyle", render.CursorVisualStyle, "GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_"), + .initEnum("GhosttyRenderStateData", render.Data, "GHOSTTY_RENDER_STATE_DATA_"), + .initEnum("GhosttyRenderStateDirty", render.Dirty, "GHOSTTY_RENDER_STATE_DIRTY_"), + .initEnum("GhosttyRenderStateOption", render.SetOption, "GHOSTTY_RENDER_STATE_OPTION_"), + .initEnum("GhosttyRenderStateRowCellsData", render.RowCellsData, "GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_"), + .initEnum("GhosttyRenderStateRowData", render.RowData, "GHOSTTY_RENDER_STATE_ROW_DATA_"), + .initEnum("GhosttyRenderStateRowOption", render.RowOption, "GHOSTTY_RENDER_STATE_ROW_OPTION_"), + .initEnum("GhosttyRowData", row.RowData, "GHOSTTY_ROW_DATA_"), + .initEnum("GhosttyRowSemanticPrompt", row.SemanticPrompt, "GHOSTTY_ROW_SEMANTIC_"), + .initEnum("GhosttySearchData", search.Data, "GHOSTTY_SEARCH_DATA_"), + .initEnum("GhosttySearchOption", search.Option, "GHOSTTY_SEARCH_OPT_"), + .initEnum("GhosttySearchScroll", search.Scroll, "GHOSTTY_SEARCH_SCROLL_"), + .initEnum("GhosttySearchStatus", search.Status, "GHOSTTY_SEARCH_STATUS_"), + .initEnum("GhosttySelectionAdjust", Selection.Adjustment, "GHOSTTY_SELECTION_ADJUST_"), + .initEnum("GhosttySelectionGestureAutoscroll", selection_gesture.Autoscroll, "GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_"), + .initEnum("GhosttySelectionGestureBehavior", selection_gesture.Behavior, "GHOSTTY_SELECTION_GESTURE_BEHAVIOR_"), + .initEnum("GhosttySelectionGestureData", selection_gesture.Data, "GHOSTTY_SELECTION_GESTURE_DATA_"), + .initEnum("GhosttySelectionGestureEventOption", selection_gesture.EventOption, "GHOSTTY_SELECTION_GESTURE_EVENT_OPT_"), + .initEnum("GhosttySelectionGestureEventType", selection_gesture.EventType, "GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_"), + .initEnum("GhosttySelectionOrder", Selection.Order, "GHOSTTY_SELECTION_ORDER_"), + .initEnum("GhosttySgrAttributeTag", sgr.Attribute.Tag, "GHOSTTY_SGR_ATTR_"), + .initEnum("GhosttySgrUnderline", sgr.Attribute.Underline, "GHOSTTY_SGR_UNDERLINE_"), + .initEnumSentinel("GhosttySizeReportStyle", size_report.Style, "GHOSTTY_SIZE_REPORT_", "STYLE_MAX_VALUE"), + .initEnum("GhosttySnapshotDecoderData", snapshot.DecoderData, "GHOSTTY_SNAPSHOT_DECODER_DATA_"), + .initEnum("GhosttySnapshotDecoderOption", snapshot.DecoderOption, "GHOSTTY_SNAPSHOT_DECODER_OPT_"), + .initEnumSentinel("GhosttyStyleColorTag", style.ColorTag, "GHOSTTY_STYLE_COLOR_", "TAG_MAX_VALUE"), + .initEnum("GhosttySysLogLevel", sys.LogLevel, "GHOSTTY_SYS_LOG_LEVEL_"), + .initEnum("GhosttySysOption", sys.Option, "GHOSTTY_SYS_OPT_"), + .initEnum("GhosttyTerminalCompressionMode", terminal.CompressionMode, "GHOSTTY_TERMINAL_COMPRESSION_MODE_"), + .initEnum("GhosttyTerminalCompressionResult", terminal.CompressionResult, "GHOSTTY_TERMINAL_COMPRESSION_RESULT_"), + .initEnum("GhosttyTerminalCursorStyle", terminal.TerminalCursorStyle, "GHOSTTY_TERMINAL_CURSOR_STYLE_"), + .initEnum("GhosttyTerminalData", terminal.TerminalData, "GHOSTTY_TERMINAL_DATA_"), + .initEnum("GhosttyTerminalOption", terminal.Option, "GHOSTTY_TERMINAL_OPT_"), + .initEnum("GhosttyTerminalProgressState", terminal.ProgressState, "GHOSTTY_TERMINAL_PROGRESS_STATE_"), + .initEnum("GhosttyTerminalScreen", terminal.TerminalScreen, "GHOSTTY_TERMINAL_SCREEN_"), + .initEnum("GhosttyTerminalScrollViewportTag", terminal.ZigTerminal.ScrollViewport.Tag, "GHOSTTY_SCROLL_VIEWPORT_"), + .initEnum("GhosttyTerminalUnknownSequenceTag", terminal.UnknownSequence.Tag, "GHOSTTY_TERMINAL_UNKNOWN_SEQUENCE_"), + + .initPacked("GhosttyCell", page.Cell.CLayout), + .initAlias("GhosttyColorPaletteIndex", u8, "u8"), + .initAlias("GhosttyKittyKeyFlags", u8, "u8"), + .initAlias("GhosttyMode", u16, "u16"), + .initAlias("GhosttyMods", u16, "u16"), + .initAlias("GhosttyRow", u64, "u64"), + .initAlias("GhosttyStyleId", u16, "u16"), + + .initOpaque("GhosttyFormatter"), + .initOpaque("GhosttyKeyEncoder"), + .initOpaque("GhosttyKeyEvent"), + .initOpaque("GhosttyKittyGraphics"), + .initOpaque("GhosttyKittyGraphicsImage"), + .initOpaque("GhosttyKittyGraphicsPlacementIterator"), + .initOpaque("GhosttyMouseEncoder"), + .initOpaque("GhosttyMouseEvent"), + .initOpaque("GhosttyOscCommand"), + .initOpaque("GhosttyOscParser"), + .initOpaque("GhosttyRenderState"), + .initOpaque("GhosttyRenderStateRowCells"), + .initOpaque("GhosttyRenderStateRowIterator"), + .initOpaque("GhosttySearch"), + .initOpaque("GhosttySelectionGesture"), + .initOpaque("GhosttySelectionGestureEvent"), + .initOpaque("GhosttySgrParser"), + .initOpaque("GhosttySnapshotDecoder"), + .initOpaque("GhosttyTerminal"), + .initOpaque("GhosttyTrackedGridRef"), }; -/// The comptime-generated JSON string of all structs. +comptime { + @setEvalBranchQuota(100_000); + for (type_decls, 0..) |decl, i| { + for (type_decls[0..i]) |previous| { + if (std.mem.eql(u8, decl.name, previous.name)) + @compileError("duplicate public ABI type: " ++ decl.name); + } + } +} + pub const json: [:0]const u8 = json: { - @setEvalBranchQuota(100000); + @setEvalBranchQuota(1_000_000); var counter: std.Io.Writer.Discarding = .init(&.{}); - jsonWriteAll(&counter.writer) catch unreachable; + Json.writeAll(&counter.writer) catch unreachable; var buf: [counter.count:0]u8 = undefined; var writer: std.Io.Writer = .fixed(&buf); - jsonWriteAll(&writer) catch unreachable; + Json.writeAll(&writer) catch unreachable; const final = buf; break :json final[0..writer.end :0]; }; -/// Returns a pointer to the comptime-generated JSON string describing -/// the layout of all C API extern structs, and writes its length to `len`. -/// Exported as `ghostty_type_json` for FFI consumers. pub fn get_json() callconv(lib.calling_conv) [*:0]const u8 { return json.ptr; } -/// Meta information about a struct that we expose to ease writing -/// bindings in some languages, particularly WASM where we can't -/// easily share struct definitions and need to hardcode byte offsets. -pub const StructInfo = struct { - name: []const u8, - size: usize, - @"align": usize, - fields: []const FieldInfo, - - pub const FieldInfo = struct { - name: []const u8, - offset: usize, - size: usize, - type: []const u8, - }; +const Json = struct { + fn writeAll(writer: *std.Io.Writer) std.Io.Writer.Error!void { + var jws: std.json.Stringify = .{ .writer = writer }; + try jws.beginObject(); + try jws.objectField("schema"); + try jws.write(1); - pub fn init(comptime T: type) StructInfo { - comptime { - const fields = @typeInfo(T).@"struct".fields; - const field_infos: [fields.len]FieldInfo = blk: { - var infos: [fields.len]FieldInfo = undefined; - for (fields, 0..) |field, i| infos[i] = .{ - .name = field.name, - .offset = @offsetOf(T, field.name), - .size = @sizeOf(field.type), - .type = typeName(field.type), - }; - break :blk infos; - }; + try jws.objectField("abi"); + try jws.beginObject(); + try jws.objectField("target"); + try jws.write(@tagName(builtin.target.cpu.arch)); + try jws.objectField("os"); + try jws.write(@tagName(builtin.target.os.tag)); + try jws.objectField("environment"); + try jws.write(@tagName(builtin.target.abi)); + try jws.objectField("pointer_size"); + try jws.write(@sizeOf(*anyopaque)); + try jws.objectField("usize_size"); + try jws.write(@sizeOf(usize)); + try jws.objectField("max_alignment"); + try jws.write(c_abi.max_alignment); + try jws.objectField("endian"); + try jws.write(@tagName(builtin.target.cpu.arch.endian())); + try jws.endObject(); - return .{ - .name = @typeName(T), - .size = @sizeOf(T), - .@"align" = @alignOf(T), - .fields = &field_infos, - }; + try jws.objectField("library_version"); + try jws.write(build_options.version_string); + try jws.objectField("commit"); + if (build_options.version_build) |commit| try jws.write(commit) else try jws.write(null); + try jws.objectField("dirty"); + try jws.write(null); + + try jws.objectField("types"); + try jws.beginObject(); + inline for (type_decls) |decl| { + try jws.objectField(decl.name); + try writeType(decl, &jws); } + try jws.endObject(); + try jws.endObject(); } - pub fn jsonStringify( - self: *const StructInfo, - jws: anytype, - ) std.Io.Writer.Error!void { + fn writeType(comptime decl: TypeDecl, jws: *std.json.Stringify) std.Io.Writer.Error!void { try jws.beginObject(); - try jws.objectField("size"); - try jws.write(self.size); - try jws.objectField("align"); - try jws.write(self.@"align"); - try jws.objectField("fields"); + try jws.objectField("kind"); + try jws.write(@tagName(decl.kind)); + + switch (decl.kind) { + .@"struct", .@"union" => { + try writeSizeAlign(decl.T, jws); + try jws.objectField("fields"); + try jws.beginObject(); + if (decl.union_field_names_T != null) { + try writeMappedUnionFields(decl, jws); + } else { + const fields = switch (decl.kind) { + .@"struct" => @typeInfo(decl.T).@"struct".fields, + .@"union" => @typeInfo(decl.T).@"union".fields, + else => unreachable, + }; + inline for (fields) |field| { + try writeField( + decl, + field.name, + field.type, + if (decl.kind == .@"union") 0 else @offsetOf(decl.T, field.name), + jws, + ); + } + } + try jws.endObject(); + }, + .@"enum" => { + try writeSizeAlign(c_int, jws); + try jws.objectField("underlying"); + try jws.write("i32"); + try jws.objectField("prefix"); + try jws.write(decl.prefix); + try jws.objectField("values"); + try jws.beginObject(); + inline for (@typeInfo(decl.T).@"enum".fields) |field| { + try writeEnumObjectField(decl.name, field.name, jws); + try jws.write(field.value); + } + try jws.objectField(decl.sentinel_suffix); + try jws.write(std.math.maxInt(c_int)); + try jws.endObject(); + }, + .@"packed" => try writePackedType(decl.T, jws), + .alias => { + try writeSizeAlign(decl.T, jws); + try jws.objectField("type"); + try jws.write(decl.alias_type); + }, + .@"opaque" => try writeSizeAlign(*anyopaque, jws), + } + try jws.endObject(); + } + + fn writePackedType( + comptime Layout: type, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + try writeSizeAlign(Layout.Zig, jws); + try jws.objectField("underlying"); + try jws.write(publicTypeName(Layout.Backing)); + try jws.objectField("bits"); try jws.beginObject(); - for (self.fields) |field| { - try jws.objectField(field.name); + try writePackedBits(Layout, jws); + try jws.endObject(); + } + + fn writePackedBits( + comptime Layout: type, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + inline for (@typeInfo(Layout.Zig).@"struct".fields) |field| { + const field_tag = @field(Layout.Field, field.name); + const name = comptime Layout.fieldName(field_tag) orelse continue; + const options = Layout.fieldOptions(field_tag); + + try jws.objectField(name); try jws.beginObject(); - try jws.objectField("offset"); - try jws.write(field.offset); - try jws.objectField("size"); - try jws.write(field.size); - try jws.objectField("type"); - try jws.write(field.type); + try jws.objectField("lsb"); + try jws.write(Layout.bitOffset(field_tag)); + try jws.objectField("width"); + try jws.write(Layout.bitWidth(field_tag)); + + switch (options.encoding) { + .scalar => { + try jws.objectField("type"); + try jws.write(options.type_name orelse publicTypeName(field.type)); + }, + .@"packed" => |Nested| { + try jws.objectField("kind"); + try jws.write("packed"); + try jws.objectField("bits"); + try jws.beginObject(); + try writePackedBits(Nested, jws); + try jws.endObject(); + }, + .tagged_union => |UnionLayout| try writePackedTaggedUnion(Layout, UnionLayout, jws), + } try jws.endObject(); } + } + + fn writePackedTaggedUnion( + comptime Layout: type, + comptime UnionLayout: type, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + try jws.objectField("kind"); + try jws.write("union"); + try jws.objectField("tag"); + try jws.write(Layout.fieldName(UnionLayout.tag_field).?); + try jws.objectField("arms"); + try jws.beginObject(); + + const tag_options = Layout.fieldOptions(UnionLayout.tag_field); + const tag_type_name = tag_options.type_name orelse publicTypeName(UnionLayout.Tag); + inline for (@typeInfo(UnionLayout.Tag).@"enum".fields) |tag| { + try writeEnumObjectField(tag_type_name, tag.name, jws); + const arm = UnionLayout.arm(@field(UnionLayout.Tag, tag.name)) orelse { + try jws.write(null); + continue; + }; + switch (arm) { + inline else => |ArmLayout| try writePackedArm(ArmLayout, jws), + } + } + + try jws.endObject(); + } + + fn writePackedArm( + comptime Layout: type, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + try jws.beginObject(); + try jws.objectField("kind"); + try jws.write("packed"); + try jws.objectField("width"); + try jws.write(@bitSizeOf(Layout.Zig)); + try jws.objectField("bits"); + try jws.beginObject(); + try writePackedBits(Layout, jws); try jws.endObject(); try jws.endObject(); } -}; -fn jsonWriteAll(writer: *std.Io.Writer) std.Io.Writer.Error!void { - var jws: std.json.Stringify = .{ .writer = writer }; - try jws.beginObject(); - for (structs.keys(), structs.values()) |name, *info| { + fn writeField( + comptime decl: TypeDecl, + comptime name: []const u8, + comptime T: type, + comptime offset: usize, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { try jws.objectField(name); - try info.jsonStringify(&jws); + try jws.beginObject(); + try jws.objectField("offset"); + try jws.write(offset); + try jws.objectField("size"); + try jws.write(@sizeOf(T)); + try writeFieldType(decl.name, name, T, jws); + if (decl.tagged_union) |tagged| { + if (std.mem.eql(u8, name, tagged.value_field)) { + try jws.objectField("tag"); + try jws.write(tagged.tag_field); + try writeTaggedArms(decl, tagged, jws); + } + } + try jws.endObject(); + } + + fn writeMappedUnionFields( + comptime decl: TypeDecl, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + const FieldNames = decl.union_field_names_T.?; + const Tag = @FieldType(FieldNames, "tag"); + const tag_fields = @typeInfo(Tag).@"enum".fields; + + inline for (tag_fields, 0..) |field, i| { + const name = comptime FieldNames.cFieldRename(@field(Tag, field.name)) orelse continue; + if (comptime mappedUnionFieldIsDuplicate(decl, i, name)) continue; + try writeField(decl, name, @FieldType(decl.T, field.name), 0, jws); + } + + if (@hasField(decl.T, "_padding")) + try writeField(decl, "_padding", @FieldType(decl.T, "_padding"), 0, jws); } - try jws.endObject(); -} -fn typeName(comptime T: type) []const u8 { - return switch (@typeInfo(T)) { - .bool => "bool", - .float => |info| switch (info.bits) { - 32 => "f32", - 64 => "f64", - else => @compileError("unsupported float size"), - }, - .int => |info| switch (info.signedness) { - .signed => switch (info.bits) { + fn mappedUnionFieldIsDuplicate( + comptime decl: TypeDecl, + comptime index: usize, + comptime name: []const u8, + ) bool { + const FieldNames = decl.union_field_names_T.?; + const Tag = @FieldType(FieldNames, "tag"); + const tag_fields = @typeInfo(Tag).@"enum".fields; + const T = @FieldType(decl.T, tag_fields[index].name); + + inline for (tag_fields[0..index]) |previous| { + const previous_name = FieldNames.cFieldRename(@field(Tag, previous.name)) orelse continue; + if (std.mem.eql(u8, previous_name, name)) { + if (@FieldType(decl.T, previous.name) != T) + @compileError("tagged union metadata maps different field types to " ++ name); + return true; + } + } + + return false; + } + + fn writeSizeAlign(comptime T: type, jws: *std.json.Stringify) std.Io.Writer.Error!void { + try jws.objectField("size"); + try jws.write(@sizeOf(T)); + try jws.objectField("align"); + try jws.write(@alignOf(T)); + } + + fn writeFieldType( + comptime owner: []const u8, + comptime field_name: []const u8, + comptime T: type, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + if (comptime std.mem.eql(u8, owner, "GhosttyCellsView") and + std.mem.eql(u8, field_name, "ptr")) + { + try writePointerTypeNamed(T, true, "GhosttyCell", jws); + return; + } + if (comptime std.mem.eql(u8, owner, "GhosttyGridRef") and + std.mem.eql(u8, field_name, "node")) + { + try writePointerTypeNamed(T, true, "opaque", jws); + return; + } + + if (comptime fieldTypeOverride(owner, field_name)) |name| { + try jws.objectField("type"); + try jws.write(name); + return; + } + + switch (@typeInfo(T)) { + .array => |info| { + try jws.objectField("type"); + try jws.write("array"); + try jws.objectField("elem"); + try jws.write(publicTypeName(info.child)); + try jws.objectField("count"); + try jws.write(info.len); + }, + .optional => |info| try writePointerType(info.child, true, jws), + .pointer => try writePointerType(T, false, jws), + else => { + try jws.objectField("type"); + try jws.write(publicTypeName(T)); + }, + } + } + + fn writePointerType( + comptime T: type, + comptime nullable: bool, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + const info = @typeInfo(T).pointer; + try jws.objectField("type"); + try jws.write("pointer"); + try jws.objectField("elem"); + try jws.write(publicTypeName(info.child)); + try jws.objectField("const"); + try jws.write(info.is_const); + if (nullable) { + try jws.objectField("nullable"); + try jws.write(true); + } + } + + fn writePointerTypeNamed( + comptime T: type, + comptime nullable: bool, + comptime elem: []const u8, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + const pointer_type = switch (@typeInfo(T)) { + .optional => |info| info.child, + .pointer => T, + else => unreachable, + }; + const info = @typeInfo(pointer_type).pointer; + try jws.objectField("type"); + try jws.write("pointer"); + try jws.objectField("elem"); + try jws.write(elem); + try jws.objectField("const"); + try jws.write(info.is_const); + if (nullable) { + try jws.objectField("nullable"); + try jws.write(true); + } + } + + fn fieldTypeOverride(comptime owner: []const u8, comptime field_name: []const u8) ?[]const u8 { + if (std.mem.eql(u8, field_name, "value")) { + if (std.mem.eql(u8, owner, "GhosttyPoint")) return "GhosttyPointValue"; + if (std.mem.eql(u8, owner, "GhosttySgrAttribute")) return "GhosttySgrAttributeValue"; + if (std.mem.eql(u8, owner, "GhosttyStyleColor")) return "GhosttyStyleColorValue"; + if (std.mem.eql(u8, owner, "GhosttyTerminalScrollViewport")) return "GhosttyTerminalScrollViewportValue"; + if (std.mem.eql(u8, owner, "GhosttyTerminalUnknownSequence")) return "GhosttyTerminalUnknownSequenceValue"; + } + if (std.mem.eql(u8, owner, "GhosttyStyleColorValue") and std.mem.eql(u8, field_name, "palette")) + return "GhosttyColorPaletteIndex"; + if (std.mem.eql(u8, owner, "GhosttySgrAttributeValue")) { + if (std.mem.eql(u8, field_name, "underline")) return "GhosttySgrUnderline"; + if (std.mem.endsWith(u8, field_name, "_8") or std.mem.endsWith(u8, field_name, "_256")) + return "GhosttyColorPaletteIndex"; + } + if (std.mem.eql(u8, owner, "GhosttyTerminalModeConfig") and std.mem.eql(u8, field_name, "mode")) + return "GhosttyMode"; + return null; + } + + fn writeTaggedArms( + comptime decl: TypeDecl, + comptime tagged: TypeDecl.TaggedUnion, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + const Tag = @FieldType(decl.T, tagged.tag_field); + try jws.objectField("arms"); + try jws.beginObject(); + inline for (@typeInfo(Tag).@"enum".fields) |field| { + try writeEnumObjectField(publicTypeName(Tag), field.name, jws); + if (comptime taggedArm(decl, field.name)) |arm| try jws.write(arm) else try jws.write(null); + } + try jws.endObject(); + } + + fn taggedArm(comptime decl: TypeDecl, comptime tag_name: []const u8) ?[]const u8 { + const tagged = decl.tagged_union.?; + const Tag = @FieldType(decl.T, tagged.tag_field); + if (tagged.arm_source == .generated) + return decl.T.cFieldRename(@field(Tag, tag_name)); + + const Value = @FieldType(decl.T, tagged.value_field); + if (!@hasField(Value, tag_name)) return null; + return if (@sizeOf(@FieldType(Value, tag_name)) == 0) null else tag_name; + } + + fn publicTypeName(comptime T: type) []const u8 { + inline for (type_decls) |decl| switch (decl.kind) { + .@"struct", .@"union", .@"enum" => if (T == decl.T) return decl.name, + .@"packed", .alias, .@"opaque" => {}, + }; + return switch (@typeInfo(T)) { + .bool => "bool", + .float => |info| switch (info.bits) { + 32 => "f32", + 64 => "f64", + else => "opaque", + }, + .int => |info| intName(info.signedness, info.bits), + .comptime_int => "comptime_int", + .void => "void", + .@"opaque" => "opaque", + .@"fn" => "function", + .@"enum" => "enum", + .@"struct" => "struct", + .@"union" => "union", + else => "opaque", + }; + } + + fn intName(comptime signedness: std.builtin.Signedness, comptime bits: u16) []const u8 { + return switch (signedness) { + .signed => switch (bits) { 8 => "i8", 16 => "i16", 32 => "i32", 64 => "i64", - else => @compileError("unsupported signed int size"), + else => std.fmt.comptimePrint("i{d}", .{bits}), }, - .unsigned => switch (info.bits) { + .unsigned => switch (bits) { 8 => "u8", 16 => "u16", 32 => "u32", 64 => "u64", - else => @compileError("unsupported unsigned int size"), + else => std.fmt.comptimePrint("u{d}", .{bits}), }, - }, - .@"enum" => "enum", - .@"struct" => "struct", - .pointer => "pointer", - .array => "array", - else => "opaque", - }; -} + }; + } -test "json parses" { - const parsed = try std.json.parseFromSlice( - std.json.Value, - std.testing.allocator, - json, - .{}, + fn writeUpperObjectField(comptime name: []const u8, jws: *std.json.Stringify) std.Io.Writer.Error!void { + var upper: [name.len]u8 = undefined; + for (name, 0..) |c, i| upper[i] = std.ascii.toUpper(c); + try jws.objectField(&upper); + } + + fn writeEnumObjectField( + comptime enum_name: []const u8, + comptime zig_name: []const u8, + jws: *std.json.Stringify, + ) std.Io.Writer.Error!void { + if (std.mem.eql(u8, enum_name, "GhosttyKey") and std.mem.startsWith(u8, zig_name, "key_")) + return writeUpperObjectField(zig_name["key_".len..], jws); + if (std.mem.eql(u8, enum_name, "GhosttySgrAttributeTag")) { + if (std.mem.eql(u8, zig_name, "256_underline_color")) return jws.objectField("UNDERLINE_COLOR_256"); + if (std.mem.eql(u8, zig_name, "8_bg")) return jws.objectField("BG_8"); + if (std.mem.eql(u8, zig_name, "8_fg")) return jws.objectField("FG_8"); + if (std.mem.eql(u8, zig_name, "8_bright_bg")) return jws.objectField("BRIGHT_BG_8"); + if (std.mem.eql(u8, zig_name, "8_bright_fg")) return jws.objectField("BRIGHT_FG_8"); + if (std.mem.eql(u8, zig_name, "256_bg")) return jws.objectField("BG_256"); + if (std.mem.eql(u8, zig_name, "256_fg")) return jws.objectField("FG_256"); + } + if (std.mem.eql(u8, enum_name, "GhosttyTerminalOption") and std.mem.eql(u8, zig_name, "size_cb")) + return jws.objectField("SIZE"); + return writeUpperObjectField(zig_name, jws); + } + + fn isBuiltinType(name: []const u8) bool { + const builtins = [_][]const u8{ + "array", "bool", "f32", "f64", "function", "i8", "i16", "i32", + "i64", "opaque", "pointer", "u8", "u16", "u32", "u64", "void", + }; + for (builtins) |builtin_name| { + if (std.mem.eql(u8, name, builtin_name)) return true; + } + if (name.len > 1 and (name[0] == 'i' or name[0] == 'u') and + name[1] >= '1' and name[1] <= '9') + { + for (name[2..]) |c| if (!std.ascii.isDigit(c)) return false; + return true; + } + return false; + } +}; + +test "manifest parses and is versioned" { + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{}); + defer parsed.deinit(); + const root = parsed.value.object; + try std.testing.expectEqual(@as(i64, 1), root.get("schema").?.integer); + try std.testing.expect(root.contains("abi")); + try std.testing.expectEqual( + @as(i64, c_abi.max_alignment), + root.get("abi").?.object.get("max_alignment").?.integer, ); + try std.testing.expect(root.contains("library_version")); + const manifest_types = root.get("types").?.object; + try std.testing.expectEqual(type_decls.len, manifest_types.count()); + inline for (type_decls) |decl| try std.testing.expect(manifest_types.contains(decl.name)); + + const cursor_fields = manifest_types.get("GhosttyRenderStateCursor").?.object + .get("fields").?.object; + try std.testing.expect(cursor_fields.contains("size")); + try std.testing.expect(cursor_fields.contains("viewport_has_value")); + try std.testing.expect(cursor_fields.contains("viewport_x")); + try std.testing.expect(cursor_fields.contains("viewport_y")); + try std.testing.expect(cursor_fields.contains("wide_tail")); + try std.testing.expect(cursor_fields.contains("visible")); + try std.testing.expect(cursor_fields.contains("blinking")); + try std.testing.expect(cursor_fields.contains("password_input")); + try std.testing.expect(cursor_fields.contains("visual_style")); +} + +test "manifest describes enums, arrays, and tagged unions" { + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{}); defer parsed.deinit(); + const manifest_types = parsed.value.object.get("types").?.object; - const root = parsed.value.object; + const data = manifest_types.get("GhosttyRenderStateData").?.object; + try std.testing.expectEqualStrings("enum", data.get("kind").?.string); + try std.testing.expectEqual(@as(i64, @intFromEnum(render.Data.dirty)), data.get("values").?.object.get("DIRTY").?.integer); - // Verify we have all expected structs - try std.testing.expect(root.contains("GhosttyClipboardContent")); - try std.testing.expect(root.contains("GhosttyClipboardWrite")); - try std.testing.expect(root.contains("GhosttyTerminalOptions")); - try std.testing.expect(root.contains("GhosttyFormatterTerminalOptions")); - - const clipboard_content = root.get("GhosttyClipboardContent").?.object; - const clipboard_content_fields = clipboard_content.get("fields").?.object; - try std.testing.expect(clipboard_content_fields.contains("mime")); - try std.testing.expect(clipboard_content_fields.contains("data")); - - const clipboard_write = root.get("GhosttyClipboardWrite").?.object; - const clipboard_write_fields = clipboard_write.get("fields").?.object; - try std.testing.expect(clipboard_write_fields.contains("size")); - try std.testing.expect(clipboard_write_fields.contains("location")); - try std.testing.expect(clipboard_write_fields.contains("contents")); - try std.testing.expect(clipboard_write_fields.contains("contents_len")); - - // Verify GhosttyTerminalOptions fields - const term_opts = root.get("GhosttyTerminalOptions").?.object; - try std.testing.expect(term_opts.contains("size")); - try std.testing.expect(term_opts.contains("align")); - try std.testing.expect(term_opts.contains("fields")); - - const fields = term_opts.get("fields").?.object; - try std.testing.expect(fields.contains("cols")); - try std.testing.expect(fields.contains("rows")); - try std.testing.expect(fields.contains("max_scrollback")); - - // Verify field offsets make sense (cols should be at 0) - const cols = fields.get("cols").?.object; - try std.testing.expectEqual(0, cols.get("offset").?.integer); + const colors = manifest_types.get("GhosttyRenderStateColors").?.object; + const palette = colors.get("fields").?.object.get("palette").?.object; + try std.testing.expectEqualStrings("array", palette.get("type").?.string); + try std.testing.expectEqualStrings("GhosttyColorRgb", palette.get("elem").?.string); + try std.testing.expectEqual(@as(i64, 256), palette.get("count").?.integer); + + const style_color = manifest_types.get("GhosttyStyleColor").?.object; + const value = style_color.get("fields").?.object.get("value").?.object; + try std.testing.expectEqualStrings("GhosttyStyleColorValue", value.get("type").?.string); + try std.testing.expectEqualStrings("tag", value.get("tag").?.string); + try std.testing.expectEqualStrings("palette", value.get("arms").?.object.get("PALETTE").?.string); + try std.testing.expect(value.get("arms").?.object.get("NONE").? == .null); } -test "struct sizes are non-zero" { - const parsed = try std.json.parseFromSlice( - std.json.Value, - std.testing.allocator, - json, - .{}, +test "manifest describes the complete packed cell layout" { + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{}); + defer parsed.deinit(); + const manifest_types = parsed.value.object.get("types").?.object; + const descriptor = manifest_types.get("GhosttyCell").?.object; + + try std.testing.expectEqualStrings("packed", descriptor.get("kind").?.string); + try std.testing.expectEqual(@as(i64, @sizeOf(page.Cell.CLayout.Zig)), descriptor.get("size").?.integer); + try std.testing.expectEqualStrings("u64", descriptor.get("underlying").?.string); + + const bits = descriptor.get("bits").?.object; + inline for (@typeInfo(page.Cell.CLayout.Zig).@"struct".fields) |field| { + const field_tag = @field(page.Cell.CLayout.Field, field.name); + const name = comptime page.Cell.CLayout.fieldName(field_tag); + if (name) |public_name| { + const bit = bits.get(public_name).?.object; + try std.testing.expectEqual( + @as(i64, @intCast(@bitOffsetOf(page.Cell.CLayout.Zig, field.name))), + bit.get("lsb").?.integer, + ); + try std.testing.expectEqual( + @as(i64, @intCast(@bitSizeOf(field.type))), + bit.get("width").?.integer, + ); + } else { + try std.testing.expect(!bits.contains(field.name)); + } + } + + const content = bits.get("content").?.object; + try std.testing.expectEqualStrings("union", content.get("kind").?.string); + try std.testing.expectEqualStrings("content_tag", content.get("tag").?.string); + const arms = content.get("arms").?.object; + + const Content = @FieldType(page.Cell.CLayout.Zig, "content"); + const Codepoint = @FieldType(Content, "codepoint"); + const codepoint = arms.get("CODEPOINT").?.object; + const grapheme = arms.get("CODEPOINT_GRAPHEME").?.object; + try expectPackedArmField(codepoint, "codepoint", Codepoint, "data", "u21"); + try expectPackedArmField(grapheme, "codepoint", Codepoint, "data", "u21"); + try expectPackedArmField( + arms.get("BG_COLOR_PALETTE").?.object, + "index", + @FieldType(Content, "color_palette"), + "data", + "GhosttyColorPaletteIndex", ); + + const rgb = arms.get("BG_COLOR_RGB").?.object; + const Rgb = @FieldType(Content, "color_rgb"); + inline for (@typeInfo(Rgb).@"struct".fields) |field| + try expectPackedArmField(rgb, field.name, Rgb, field.name, "u8"); +} + +test "manifest packed cell layouts decode real values" { + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{}); + defer parsed.deinit(); + const manifest_types = parsed.value.object.get("types").?.object; + const cell_bits = manifest_types.get("GhosttyCell").?.object.get("bits").?.object; + + var codepoint = page.Cell.CLayout.Zig.init('A'); + try expectDecodedCellContent(manifest_types, cell_bits, @bitCast(codepoint), "codepoint", 'A'); + + codepoint.content_tag = .codepoint_grapheme; + try expectDecodedCellContent(manifest_types, cell_bits, @bitCast(codepoint), "codepoint", 'A'); + + var palette: page.Cell.CLayout.Zig = @bitCast(@as(u64, 0)); + palette.content_tag = .bg_color_palette; + palette.content = .{ .color_palette = .{ .data = 173 } }; + try expectDecodedCellContent(manifest_types, cell_bits, @bitCast(palette), "index", 173); + + var rgb: page.Cell.CLayout.Zig = @bitCast(@as(u64, 0)); + rgb.content_tag = .bg_color_rgb; + rgb.content = .{ .color_rgb = .{ .r = 0x12, .g = 0x34, .b = 0x56 } }; + const rgb_arm = activeCellContentArm(manifest_types, cell_bits, @bitCast(rgb)); + const content = extractManifestBits(@bitCast(rgb), cell_bits.get("content").?.object); + try std.testing.expectEqual(@as(u64, 0x12), extractManifestBits(content, rgb_arm.get("bits").?.object.get("r").?.object)); + try std.testing.expectEqual(@as(u64, 0x34), extractManifestBits(content, rgb_arm.get("bits").?.object.get("g").?.object)); + try std.testing.expectEqual(@as(u64, 0x56), extractManifestBits(content, rgb_arm.get("bits").?.object.get("b").?.object)); +} + +test "manifest uses public enum names" { + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{}); defer parsed.deinit(); + const manifest_types = parsed.value.object.get("types").?.object; + + const cell_content = manifest_types.get("GhosttyCellContentTag").?.object.get("values").?.object; + try std.testing.expect(cell_content.contains("TAG_MAX_VALUE")); + try std.testing.expect(!cell_content.contains("MAX_VALUE")); + + const sgr_values = manifest_types.get("GhosttySgrAttributeTag").?.object.get("values").?.object; + try std.testing.expectEqual(@as(i64, 9), sgr_values.get("UNDERLINE_COLOR_256").?.integer); + try std.testing.expectEqual(@as(i64, 23), sgr_values.get("BG_8").?.integer); + try std.testing.expect(!sgr_values.contains("256_UNDERLINE_COLOR")); + + const sgr_arms = manifest_types.get("GhosttySgrAttribute").?.object + .get("fields").?.object.get("value").?.object.get("arms").?.object; + try std.testing.expectEqualStrings("underline_color_256", sgr_arms.get("UNDERLINE_COLOR_256").?.string); + try std.testing.expectEqualStrings("bg_8", sgr_arms.get("BG_8").?.string); + + const terminal_values = manifest_types.get("GhosttyTerminalOption").?.object.get("values").?.object; + try std.testing.expectEqual(@as(i64, 6), terminal_values.get("SIZE").?.integer); + try std.testing.expect(!terminal_values.contains("SIZE_CB")); + + const osc_values = manifest_types.get("GhosttyOscCommandType").?.object.get("values").?.object; + try std.testing.expectEqual(@as(i64, 22), osc_values.get("KITTY_TEXT_SIZING").?.integer); + try std.testing.expectEqual(@as(i64, 23), osc_values.get("KITTY_CLIPBOARD_PROTOCOL").?.integer); + try std.testing.expectEqual(@as(i64, 24), osc_values.get("KITTY_DND_PROTOCOL").?.integer); + try std.testing.expectEqual(@as(i64, 25), osc_values.get("CONTEXT_SIGNAL").?.integer); + try std.testing.expectEqual(@as(i64, 26), osc_values.get("KITTY_DESKTOP_NOTIFICATION").?.integer); + try std.testing.expect(osc_values.contains("TYPE_MAX_VALUE")); + try std.testing.expect(!osc_values.contains("MAX_VALUE")); + + const key_values = manifest_types.get("GhosttyKey").?.object.get("values").?.object; + try std.testing.expect(key_values.contains("A")); + try std.testing.expect(!key_values.contains("KEY_A")); - var it = parsed.value.object.iterator(); - while (it.next()) |entry| { - const struct_info = entry.value_ptr.object; - const size = struct_info.get("size").?.integer; - try std.testing.expect(size > 0); + const mode_values = manifest_types.get("GhosttyModeReportState").?.object.get("values").?.object; + try std.testing.expectEqual(@as(i64, 0), mode_values.get("NOT_RECOGNIZED").?.integer); + try std.testing.expectEqual(@as(i64, 4), mode_values.get("PERMANENTLY_RESET").?.integer); +} + +test "manifest named references resolve" { + const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{}); + defer parsed.deinit(); + const manifest_types = parsed.value.object.get("types").?.object; + + var type_iterator = manifest_types.iterator(); + while (type_iterator.next()) |type_entry| { + const descriptor = type_entry.value_ptr.object; + if (descriptor.get("bits")) |bits_value| { + try expectManifestBitsValid( + manifest_types, + bits_value.object, + @intCast(descriptor.get("size").?.integer * 8), + ); + } + const fields_value = descriptor.get("fields") orelse continue; + var field_iterator = fields_value.object.iterator(); + while (field_iterator.next()) |field_entry| { + const field = field_entry.value_ptr.object; + const field_type = field.get("type").?.string; + if (!Json.isBuiltinType(field_type)) + try std.testing.expect(manifest_types.contains(field_type)); + + if (field.get("elem")) |elem_value| { + const elem = elem_value.string; + if (!Json.isBuiltinType(elem)) + try std.testing.expect(manifest_types.contains(elem)); + } + + if (field.get("arms")) |arms_value| { + const union_descriptor = manifest_types.get(field_type).?.object; + const union_fields = union_descriptor.get("fields").?.object; + const tag_field_name = field.get("tag").?.string; + const tag_type_name = fields_value.object.get(tag_field_name).?.object.get("type").?.string; + const tag_values = manifest_types.get(tag_type_name).?.object.get("values").?.object; + var arm_iterator = arms_value.object.iterator(); + while (arm_iterator.next()) |arm_entry| { + try std.testing.expect(tag_values.contains(arm_entry.key_ptr.*)); + if (arm_entry.value_ptr.* == .null) continue; + try std.testing.expect(union_fields.contains(arm_entry.value_ptr.string)); + } + } + } + } +} + +fn expectPackedArmField( + arm: std.json.ObjectMap, + manifest_name: []const u8, + comptime T: type, + comptime zig_name: []const u8, + expected_type: []const u8, +) !void { + try std.testing.expectEqualStrings("packed", arm.get("kind").?.string); + try std.testing.expectEqual(@as(i64, @bitSizeOf(T)), arm.get("width").?.integer); + const bit = arm.get("bits").?.object.get(manifest_name).?.object; + try std.testing.expectEqual(@as(i64, @bitOffsetOf(T, zig_name)), bit.get("lsb").?.integer); + try std.testing.expectEqual(@as(i64, @bitSizeOf(@FieldType(T, zig_name))), bit.get("width").?.integer); + try std.testing.expectEqualStrings(expected_type, bit.get("type").?.string); +} + +fn extractManifestBits(value: u64, bit: std.json.ObjectMap) u64 { + const lsb: u6 = @intCast(bit.get("lsb").?.integer); + const width: u7 = @intCast(bit.get("width").?.integer); + const mask = if (width == 64) + std.math.maxInt(u64) + else + (@as(u64, 1) << @intCast(width)) - 1; + return (value >> lsb) & mask; +} + +fn activeCellContentArm( + manifest_types: std.json.ObjectMap, + cell_bits: std.json.ObjectMap, + raw: u64, +) std.json.ObjectMap { + const content_tag = cell_bits.get("content_tag").?.object; + const value = extractManifestBits(raw, content_tag); + const enum_values = manifest_types.get(content_tag.get("type").?.string).?.object + .get("values").?.object; + var iterator = enum_values.iterator(); + while (iterator.next()) |entry| { + if (entry.value_ptr.integer == value) + return cell_bits.get("content").?.object.get("arms").?.object + .get(entry.key_ptr.*).?.object; + } + unreachable; +} + +fn expectDecodedCellContent( + manifest_types: std.json.ObjectMap, + cell_bits: std.json.ObjectMap, + raw: u64, + field_name: []const u8, + expected: u64, +) !void { + const arm = activeCellContentArm(manifest_types, cell_bits, raw); + const content = extractManifestBits(raw, cell_bits.get("content").?.object); + try std.testing.expectEqual( + expected, + extractManifestBits(content, arm.get("bits").?.object.get(field_name).?.object), + ); +} + +fn expectManifestBitsValid( + manifest_types: std.json.ObjectMap, + bits: std.json.ObjectMap, + container_width: usize, +) !void { + var iterator = bits.iterator(); + while (iterator.next()) |entry| { + const bit = entry.value_ptr.object; + const lsb: usize = @intCast(bit.get("lsb").?.integer); + const width: usize = @intCast(bit.get("width").?.integer); + try std.testing.expect(lsb + width <= container_width); + + if (bit.get("type")) |type_value| { + const type_name = type_value.string; + try std.testing.expect(Json.isBuiltinType(type_name) or manifest_types.contains(type_name)); + continue; + } + + const kind = bit.get("kind").?.string; + if (std.mem.eql(u8, kind, "packed")) { + try expectManifestBitsValid(manifest_types, bit.get("bits").?.object, width); + continue; + } + + try std.testing.expectEqualStrings("union", kind); + const tag_name = bit.get("tag").?.string; + const tag = bits.get(tag_name).?.object; + const enum_values = manifest_types.get(tag.get("type").?.string).?.object + .get("values").?.object; + var arm_iterator = bit.get("arms").?.object.iterator(); + while (arm_iterator.next()) |arm_entry| { + try std.testing.expect(enum_values.contains(arm_entry.key_ptr.*)); + if (arm_entry.value_ptr.* == .null) continue; + const arm = arm_entry.value_ptr.object; + const arm_width: usize = @intCast(arm.get("width").?.integer); + try std.testing.expect(arm_width <= width); + try expectManifestBitsValid(manifest_types, arm.get("bits").?.object, arm_width); + } } } |
