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/kitty | |
| parent | 90e947a6e26e02f10ec7f1694c4eb5b78a86406b (diff) | |
chore: upgrade libghostty and preserve terminal behavior (#3906)
Diffstat (limited to 'vendor/libghostty-vt/src/terminal/kitty')
19 files changed, 13268 insertions, 937 deletions
diff --git a/vendor/libghostty-vt/src/terminal/kitty/clipboard.zig b/vendor/libghostty-vt/src/terminal/kitty/clipboard.zig new file mode 100644 index 00000000..32cf8b90 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/clipboard.zig @@ -0,0 +1,82 @@ +//! Kitty clipboard protocol (OSC 5522). +//! +//! This implements the protocol semantics on top of the raw OSC capture: +//! src/terminal/osc/parsers/kitty_clipboard_protocol.zig: +//! +//! The behavior here is modeled on the kitty reference implementation +//! (kitty/clipboard.py) rather than only the prose spec, since the two +//! disagree in places. Notable reference behaviors we reproduce: +//! +//! * Malformed metadata (any record without '=', including an empty +//! metadata section) and an unknown or missing `type` silently drop +//! the request with no response. +//! * All base64 (payloads and the `mime`, `name`, and `pw` metadata +//! values) is strict RFC 4648 per the spec's "Encoding of payloads" +//! section: characters outside the standard alphabet (including +//! whitespace) and incorrect padding are rejected, never silently +//! skipped. An invalid value on `wdata` or `walias` aborts an +//! in-flight write with EINVAL; an invalid `read` is dropped with +//! no response since reads have no error status. +//! * Decoded metadata and MIME-list payloads must be valid UTF-8. An +//! invalid value on `wdata` or `walias`, or a `walias` without a +//! target MIME type, aborts an in-flight write with EINVAL. +//! * The `wdata` payloads for one MIME type form a single base64 +//! stream split at arbitrary packet boundaries; only the +//! concatenation must be correctly padded. Like kitty (which +//! resets its streaming decoder on EOF), a packet ending exactly +//! at terminal padding restarts the stream, so independently +//! encoded chunks also work. +//! * `mime`, `name`, and `pw` metadata values are base64-encoded UTF-8; +//! everything else is verbatim. Unknown keys are ignored. +//! * `id` is sanitized by stripping characters outside [a-zA-Z0-9-_+.] +//! and truncating to 512 bytes, then echoed verbatim in every +//! response packet (omitted when empty). +//! * A `type=write` silently replaces any in-flight transaction. A +//! commit (`type=wdata` without a MIME type) with no in-flight +//! transaction is silently ignored. +//! * Responses never send a payload section for an empty payload, +//! except the targets ('.') listing DATA packet which is always sent. +//! +//! Specification: https://sw.kovidgoyal.net/kitty/clipboard/ + +const oscpkg = @import("../osc.zig"); +const protocol = @import("../osc/parsers/kitty_clipboard_protocol.zig"); +const command = @import("clipboard_command.zig"); +const write = @import("clipboard_write.zig"); +const response = @import("clipboard_response.zig"); +const grants = @import("clipboard_grants.zig"); + +pub const OSC = protocol.OSC; +pub const Operation = protocol.Operation; +pub const Status = protocol.Status; +pub const Terminator = oscpkg.Terminator; + +pub const Metadata = command.Metadata; +pub const Payload = command.Payload; +pub const readPromptExempt = command.readPromptExempt; +pub const max_id_len = command.max_id_len; +pub const max_pw_len = command.max_pw_len; +pub const max_mime_len = command.max_mime_len; +pub const max_name_len = command.max_name_len; + +pub const Content = write.Content; +pub const WriteState = write.WriteState; +pub const max_write_size = write.max_write_size; +pub const max_write_mimes = write.max_write_mimes; +pub const max_write_aliases = write.max_write_aliases; + +pub const Response = response.Response; +pub const ReadSuccess = response.ReadSuccess; +pub const PasteEvent = response.PasteEvent; +pub const read_chunk_size = response.read_chunk_size; +pub const max_read_mimes = response.max_read_mimes; +pub const max_listing_mimes = response.max_listing_mimes; +pub const targets_mime = response.targets_mime; + +pub const Grants = grants.Grants; +pub const otp_len = grants.otp_len; +pub const generateOtp = grants.generateOtp; + +test { + @import("std").testing.refAllDecls(@This()); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/clipboard_command.zig b/vendor/libghostty-vt/src/terminal/kitty/clipboard_command.zig new file mode 100644 index 00000000..67bc26f0 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/clipboard_command.zig @@ -0,0 +1,502 @@ +//! Kitty clipboard protocol (OSC 5522) request decoding. +//! +//! OSC 5522 format: `<OSC>5522;metadata;payload<ST>` +//! +//! Per the spec: "metadata is a colon separated list of key-value +//! pairs and payload is base64 encoded data." +//! +//! This contains the logic for parsing this. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const simd = @import("../../simd/main.zig"); +const clipboard = @import("../clipboard.zig"); +const protocol = @import("../osc/parsers/kitty_clipboard_protocol.zig"); + +const Operation = protocol.Operation; + +/// Maximum id length, nothing specified but this is the limit used +/// in Kitty's source so we'll match it. +pub const max_id_len = 512; + +/// Maximum decoded password length. Kitty has no limit. Passwords are +/// UUID-sized in practice so anything longer simply never matches a +/// stored grant anyway. +pub const max_pw_len = 128; + +/// Maximum decoded MIME type length. Kitty has no limit but real MIME +/// types are tiny; anything longer drops the packet. +pub const max_mime_len = 256; + +/// Maximum decoded name length. Kitty has no limit but names are shown +/// in permission prompts so anything longer drops the packet. +pub const max_name_len = 256; + +/// The decoded, validated metadata of one OSC 5522 sequence. +/// +/// All slice values are allocated from the allocator given to parse and +/// are sized to their contents. Callers are expected to pass an arena +/// scoped to handling the packet. There is no deinit. +pub const Metadata = struct { + op: Operation, + + /// The clipboard this operation targets. Per the spec: "To read + /// from the primary selection instead of the clipboard, add the + /// key `loc=primary` to the metadata section." Any other value + /// means the clipboard, so only standard and primary are possible + /// here. + loc: clipboard.Location = .standard, + + /// Sanitized id: invalid characters stripped, truncated to + /// max_id_len. Empty means no id. + id: []const u8 = "", + + /// Decoded mime metadata value. Empty means absent; kitty treats an + /// empty mime the same as a missing one everywhere it matters (a + /// wdata packet with either commits the transaction). + mime: []const u8 = "", + + /// Decoded password. Empty means absent. Per the spec: + /// "Specifying a password without a human friendly name is + /// equivalent to not specifying a password and the terminal must + /// treat the request as though it had no password." + pw: []const u8 = "", + + /// Decoded human friendly name of the requesting program, shown in + /// permission prompts. Empty means absent. Its presence opts into + /// password grants. + name: []const u8 = "", + + /// Parse the metadata field. The raw value is expected to be exactly + /// the metadata (prefix and payload and separators stripped out). + /// + /// A null result means the packet should be silently dropped. An + /// InvalidValue error means a decoded textual value was not valid + /// UTF-8 or exceeded a local safety limit. Callers use the raw + /// operation to decide whether that invalid value aborts an in-flight + /// write transaction. + pub fn parse( + alloc: Allocator, + raw: []const u8, + ) error{ OutOfMemory, InvalidValue }!?Metadata { + const fields = Raw.parse(raw) orelse return null; + var result: Metadata = .{ + .op = Operation.init(fields.op orelse return null) orelse return null, + .loc = if (std.mem.eql(u8, fields.loc, "primary")) + .primary + else + .standard, + .id = try sanitizeId(alloc, fields.id), + }; + + result.mime = decodeValue( + alloc, + fields.mime, + max_mime_len, + ) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Overflow, + error.InvalidBase64, + error.InvalidUtf8, + => return error.InvalidValue, + }; + result.pw = decodeValue( + alloc, + fields.pw, + max_pw_len, + ) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.InvalidBase64, error.InvalidUtf8 => return error.InvalidValue, + // An over-long password behaves as if none was given: it can + // never match a stored grant. + error.Overflow => "", + }; + result.name = decodeValue( + alloc, + fields.name, + max_name_len, + ) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Overflow, + error.InvalidBase64, + error.InvalidUtf8, + => return error.InvalidValue, + }; + return result; + } + + /// Return the last recognized operation from syntactically valid raw + /// metadata. This intentionally does not decode any values, so callers + /// can still classify an InvalidValue parse error. + pub fn operation(raw: []const u8) ?Operation { + const fields = Raw.parse(raw) orelse return null; + return Operation.init(fields.op orelse return null); + } + + const Raw = struct { + op: ?[]const u8 = null, + loc: []const u8 = "", + id: []const u8 = "", + mime: []const u8 = "", + pw: []const u8 = "", + name: []const u8 = "", + + fn parse(raw: []const u8) ?Raw { + var result: Raw = .{}; + + // This visits every record even though an empty raw string + // yields one empty record. Validating the complete structure + // before decoding also ensures the last duplicate value wins. + var it = std.mem.splitScalar(u8, raw, ':'); + while (it.next()) |record| { + const eql_idx = std.mem.indexOfScalar(u8, record, '=') orelse return null; + const key = record[0..eql_idx]; + const value = record[eql_idx + 1 ..]; + + if (std.mem.eql(u8, key, "type")) { + result.op = value; + } else if (std.mem.eql(u8, key, "loc")) { + result.loc = value; + } else if (std.mem.eql(u8, key, "id")) { + result.id = value; + } else if (std.mem.eql(u8, key, "mime")) { + result.mime = value; + } else if (std.mem.eql(u8, key, "pw")) { + result.pw = value; + } else if (std.mem.eql(u8, key, "name")) { + result.name = value; + } + // Unknown keys are ignored. + } + + return result; + } + }; + + /// Sanitize the ID according to the spec: + /// + /// Valid ids must include only characters from the set: [a-zA-Z0-9-_+.]. + /// Any other characters must be stripped out from the id by the terminal + /// emulator before retransmitting it. + fn sanitizeId(alloc: Allocator, value: []const u8) Allocator.Error![]const u8 { + var list: std.ArrayListUnmanaged(u8) = .empty; + defer list.deinit(alloc); + for (value) |c| { + switch (c) { + 'a'...'z', 'A'...'Z', '0'...'9', '-', '_', '+', '.' => {}, + else => continue, + } + if (list.items.len >= max_id_len) break; + try list.append(alloc, c); + } + return try list.toOwnedSlice(alloc); + } + + /// Base64-decode a metadata value. Per the spec these values "are + /// UTF-8 strings that are base64 encoded", so the decoded result + /// must be valid UTF-8, and the encoding is strict RFC 4648 with + /// required padding per the spec's "Encoding of payloads" section. + fn decodeValue(alloc: Allocator, value: []const u8, max_len: usize) error{ + OutOfMemory, + Overflow, + InvalidBase64, + InvalidUtf8, + }![]const u8 { + const Encoder = std.base64.standard.Encoder; + + // Avoid hostile large payloads. + if (value.len > Encoder.calcSize(max_len)) return error.Overflow; + + // Decode + const buf = try alloc.alloc(u8, simd.base64.maxLen(value)); + errdefer alloc.free(buf); + const decoded = simd.base64.decodeStrict( + value, + buf, + .required, + ) catch return error.InvalidBase64; + + // Must be valid UTF-8 + if (!std.unicode.utf8ValidateSlice(decoded)) return error.InvalidUtf8; + if (decoded.len > max_len) return error.Overflow; + return decoded; + } +}; + +/// A decoded base64 payload of one OSC 5522 sequence, e.g. the MIME +/// type list of a read request or the alias list of a walias packet. +/// The data slice aliases the allocated buf. +pub const Payload = struct { + buf: []u8, + data: []const u8, + + /// Decode a base64 payload into freshly allocated memory. The + /// encoding is strict RFC 4648 with required padding per the + /// spec's "Encoding of payloads" section; how an invalid payload + /// is reported (or not) depends on the packet type. + pub fn init( + alloc: Allocator, + payload: []const u8, + ) error{ OutOfMemory, Invalid }!Payload { + const buf = try alloc.alloc(u8, simd.base64.maxLen(payload)); + errdefer alloc.free(buf); + const data = simd.base64.decodeStrict( + payload, + buf, + .required, + ) catch return error.Invalid; + return .{ .buf = buf, .data = data }; + } + + pub fn deinit(self: *const Payload, alloc: Allocator) void { + alloc.free(self.buf); + } + + pub fn isValidUtf8(self: *const Payload) bool { + return std.unicode.utf8ValidateSlice(self.data); + } + + /// Iterate the whitespace-separated MIME types of the payload. + /// Matches Python str.split() used by kitty. + pub fn mimeIterator(self: *const Payload) std.mem.TokenIterator(u8, .any) { + return std.mem.tokenizeAny( + u8, + self.data, + &std.ascii.whitespace, + ); + } +}; + +/// Whether a read request with this many data MIME types (the targets +/// type '.' excluded) is exempt from the user permission prompt. +pub fn readPromptExempt(data_mimes: usize) bool { + return data_mimes == 0; +} + +test "metadata: empty is dropped" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + try testing.expect((try Metadata.parse(arena.allocator(), "")) == null); +} + +test "metadata: record without = is dropped" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + try testing.expect((try Metadata.parse(arena.allocator(), "type=read:bare")) == null); + try testing.expect((try Metadata.parse(arena.allocator(), "bare:type=read")) == null); +} + +test "metadata: missing or unknown type is dropped" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + try testing.expect((try Metadata.parse(arena.allocator(), "loc=primary")) == null); + try testing.expect((try Metadata.parse(arena.allocator(), "type=bobr")) == null); + try testing.expect((try Metadata.parse(arena.allocator(), "type=")) == null); +} + +test "metadata: duplicate keys keep the last occurrence" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + try testing.expectEqual( + Operation.read, + (try Metadata.parse(arena.allocator(), "type=bobr:type=read")).?.op, + ); + try testing.expect((try Metadata.parse(arena.allocator(), "type=read:type=bobr")) == null); +} + +test "metadata: basic read" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const meta = (try Metadata.parse(arena.allocator(), "type=read")).?; + try testing.expectEqual(Operation.read, meta.op); + try testing.expect(meta.loc == .standard); + try testing.expectEqual(@as(usize, 0), meta.id.len); +} + +test "metadata: unknown keys ignored" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const meta = (try Metadata.parse(arena.allocator(), "type=read:bobr=kurwa")).?; + try testing.expectEqual(Operation.read, meta.op); +} + +test "metadata: loc" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + try testing.expect((try Metadata.parse(arena.allocator(), "type=read:loc=primary")).?.loc == .primary); + // Anything other than "primary" means the clipboard; it is not an + // error. + try testing.expect((try Metadata.parse(arena.allocator(), "type=read:loc=bobr")).?.loc == .standard); +} + +test "metadata: id sanitized" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + { + const meta = (try Metadata.parse(arena.allocator(), "type=read:id=abc-123_x.Y+z")).?; + try testing.expectEqualStrings("abc-123_x.Y+z", meta.id); + } + { + // Invalid characters are stripped, not rejected. + const meta = (try Metadata.parse(arena.allocator(), "type=read:id=*4 2*")).?; + try testing.expectEqualStrings("42", meta.id); + } +} + +test "metadata: id truncated to max" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const raw = "type=read:id=" ++ "a" ** (max_id_len + 100); + const meta = (try Metadata.parse(arena.allocator(), raw)).?; + try testing.expectEqual(@as(usize, max_id_len), meta.id.len); +} + +test "metadata: mime decoded" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + // "text/plain" + const meta = (try Metadata.parse(arena.allocator(), "type=wdata:mime=dGV4dC9wbGFpbg==")).?; + try testing.expectEqualStrings("text/plain", meta.mime); +} + +test "metadata: invalid mime base64 reported" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + // Invalid base64 in a metadata value aborts an in-flight write + // per the spec, so like invalid UTF-8 it is reported rather than + // silently dropping the packet. Unpadded or whitespace-laced + // values are invalid too: metadata values use the same strict + // encoding as payloads. + const cases = [_][]const u8{ + "type=wdata:mime=!!!", + // "text/plain" without its padding. + "type=wdata:mime=dGV4dC9wbGFpbg", + // "text/plain" with its final byte replaced by '!'. + "type=wdata:mime=dGV4dC9wbGFpbg=!", + // A newline inside otherwise valid base64. + "type=wdata:mime=dGV4dC9w\nbGFpbg==", + }; + for (cases) |case| { + try testing.expectError( + error.InvalidValue, + Metadata.parse(arena.allocator(), case), + ); + try testing.expectEqual( + Operation.wdata, + Metadata.operation(case).?, + ); + } +} + +test "metadata: invalid mime utf8 reported" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + // base64 of 0xff 0xfe + try testing.expectError( + error.InvalidValue, + Metadata.parse(arena.allocator(), "type=wdata:mime=//4="), + ); + try testing.expectEqual( + Operation.wdata, + Metadata.operation("type=wdata:mime=//4=").?, + ); +} + +test "metadata: pw and name" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + // pw="secret", name="app" + const meta = (try Metadata.parse(arena.allocator(), "type=read:pw=c2VjcmV0:name=YXBw")).?; + try testing.expectEqualStrings("secret", meta.pw); + try testing.expectEqualStrings("app", meta.name); +} + +test "metadata: over-long name reported" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const Encoder = std.base64.standard.Encoder; + const long = "n" ** (max_name_len + 1); + var buf: [Encoder.calcSize(long.len)]u8 = undefined; + const raw = try std.mem.concat(arena.allocator(), u8, &.{ + "type=read:name=", + Encoder.encode(&buf, long), + }); + try testing.expectError( + error.InvalidValue, + Metadata.parse(arena.allocator(), raw), + ); +} + +test "metadata: empty name" { + const testing = std.testing; + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const meta = (try Metadata.parse(arena.allocator(), "type=read:pw=c2VjcmV0:name=")).?; + try testing.expectEqual(@as(usize, 0), meta.name.len); +} + +test "read prompt exemption: only requests without data types" { + const testing = std.testing; + + // A targets-only ('.') read parses to zero data MIME types and is + // served without a prompt; any data type, even alongside the + // targets listing, still prompts. + try testing.expect(readPromptExempt(0)); + try testing.expect(!readPromptExempt(1)); +} + +test "payload: mime iterator" { + const testing = std.testing; + // base64 of "text/plain text/html\ntext/uri-list" + const payload = try Payload.init( + testing.allocator, + "dGV4dC9wbGFpbiAgdGV4dC9odG1sCnRleHQvdXJpLWxpc3Q=", + ); + defer payload.deinit(testing.allocator); + var it = payload.mimeIterator(); + try testing.expectEqualStrings("text/plain", it.next().?); + try testing.expectEqualStrings("text/html", it.next().?); + try testing.expectEqualStrings("text/uri-list", it.next().?); + try testing.expect(it.next() == null); +} + +test "payload: invalid base64" { + const testing = std.testing; + const cases = [_][]const u8{ + "!!!", + // "text/plain" without its padding: payloads use the strict + // encoding, so missing padding is rejected. + "dGV4dC9wbGFpbg", + // A newline inside otherwise valid base64. + "dGV4dC9w\nbGFpbg==", + }; + for (cases) |case| { + try testing.expectError( + error.Invalid, + Payload.init(testing.allocator, case), + ); + } +} + +test "payload: decoded text must be valid utf8" { + const testing = std.testing; + // Valid base64 encoding of a single 0xff byte. + const payload = try Payload.init(testing.allocator, "/w=="); + defer payload.deinit(testing.allocator); + try testing.expect(!payload.isValidUtf8()); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/clipboard_grants.zig b/vendor/libghostty-vt/src/terminal/kitty/clipboard_grants.zig new file mode 100644 index 00000000..59b9bef7 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/clipboard_grants.zig @@ -0,0 +1,238 @@ +//! Kitty clipboard protocol (OSC 5522) session password grants: +//! requests carrying a granted password skip the permission prompt, and +//! paste events mint one-time passwords. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const clipboard_command = @import("clipboard_command.zig"); +const sys = @import("../sys.zig"); + +const max_pw_len = clipboard_command.max_pw_len; + +/// Session password grants, used to skip permission prompts for +/// requests carrying a known pw. Callers can choose to scope these +/// however they want, e.g. Kitty does it per window and the spec +/// doesn't demand anything. +pub const Grants = struct { + entries: std.ArrayListUnmanaged(Entry) = .empty, + + const max_entries = 32; + + pub const Direction = enum { read, write }; + + const Entry = struct { + /// Owned by the allocator passed to grant. + pw: []const u8, + read: bool = false, + write: bool = false, + one_time: bool = false, + }; + + pub fn deinit(self: *Grants, alloc: Allocator) void { + for (self.entries.items) |entry| alloc.free(entry.pw); + self.entries.deinit(alloc); + } + + /// Record a grant for pw. An existing grant for the same password + /// gains the new direction. + pub fn grant( + self: *Grants, + alloc: Allocator, + pw: []const u8, + dir: Direction, + one_time: bool, + ) Allocator.Error!void { + if (pw.len == 0 or pw.len > max_pw_len) return; + + const entry: *Entry = entry: { + if (self.findIndex(pw)) |idx| { + const entry = &self.entries.items[idx]; + entry.one_time = entry.one_time and one_time; + break :entry entry; + } + + // Evict the oldest grant once full. + if (self.entries.items.len >= max_entries) { + const oldest = self.entries.orderedRemove(0); + alloc.free(oldest.pw); + } + + const owned = try alloc.dupe(u8, pw); + errdefer alloc.free(owned); + try self.entries.append(alloc, .{ + .pw = owned, + .one_time = one_time, + }); + break :entry &self.entries.items[self.entries.items.len - 1]; + }; + + switch (dir) { + .read => entry.read = true, + .write => entry.write = true, + } + } + + /// Check whether pw grants the given direction. A one-time grant is + /// consumed by this check even when the direction doesn't match, + /// matching kitty's pop-on-check behavior. + pub fn use( + self: *Grants, + alloc: Allocator, + pw: []const u8, + dir: Direction, + ) bool { + if (pw.len == 0) return false; + const idx = self.findIndex(pw) orelse return false; + const entry = &self.entries.items[idx]; + const allowed = switch (dir) { + .read => entry.read, + .write => entry.write, + }; + if (entry.one_time) { + const removed = self.entries.swapRemove(idx); + alloc.free(removed.pw); + } + return allowed; + } + + fn findIndex(self: *const Grants, pw: []const u8) ?usize { + for (self.entries.items, 0..) |*entry, idx| { + if (std.mem.eql(u8, entry.pw, pw)) return idx; + } + return null; + } +}; + +/// The length of a one-time password generated for paste events. +pub const otp_len = 22; + +/// The one-time password alphabet. This matches kitty (alphanumeric +/// without easily-confused characters), but the spec doesn't demand +/// this. +pub const otp_alphabet = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; + +/// Generate a one-time password for a paste event. +/// +/// The password is a secret: a program that learns it can read the +/// clipboard without a prompt. Entropy comes from `sys.random_secure` +/// if set, otherwise from the Io; see `sys.randomSecure`. +pub fn generateOtp(io: std.Io) std.Io.RandomSecureError![otp_len]u8 { + var result: [otp_len]u8 = undefined; + var len: usize = 0; + while (len < result.len) { + var raw: [2 * otp_len]u8 = undefined; + try sys.randomSecure(io, &raw); + const limit = (std.math.maxInt(u8) + 1) / otp_alphabet.len * otp_alphabet.len; + for (raw) |byte| { + if (byte >= limit) continue; + result[len] = otp_alphabet[byte % otp_alphabet.len]; + len += 1; + if (len == result.len) break; + } + } + + return result; +} + +test "grants: basic grant and use" { + const testing = std.testing; + const alloc = testing.allocator; + + var grants: Grants = .{}; + defer grants.deinit(alloc); + try testing.expect(!grants.use(alloc, "pw1", .read)); + + try grants.grant(alloc, "pw1", .read, false); + try testing.expect(grants.use(alloc, "pw1", .read)); + // Persistent grants survive use. + try testing.expect(grants.use(alloc, "pw1", .read)); + try testing.expect(!grants.use(alloc, "pw1", .write)); +} + +test "grants: one-time consumed on check" { + const testing = std.testing; + const alloc = testing.allocator; + + var grants: Grants = .{}; + defer grants.deinit(alloc); + try grants.grant(alloc, "otp", .read, true); + try testing.expect(grants.use(alloc, "otp", .read)); + try testing.expect(!grants.use(alloc, "otp", .read)); +} + +test "grants: one-time consumed even on direction mismatch" { + const testing = std.testing; + const alloc = testing.allocator; + + var grants: Grants = .{}; + defer grants.deinit(alloc); + try grants.grant(alloc, "otp", .read, true); + try testing.expect(!grants.use(alloc, "otp", .write)); + try testing.expect(!grants.use(alloc, "otp", .read)); +} + +test "grants: directions are independent" { + const testing = std.testing; + const alloc = testing.allocator; + + var grants: Grants = .{}; + defer grants.deinit(alloc); + try grants.grant(alloc, "pw", .read, false); + try grants.grant(alloc, "pw", .write, false); + try testing.expect(grants.use(alloc, "pw", .read)); + try testing.expect(grants.use(alloc, "pw", .write)); +} + +test "grants: capacity evicts the oldest" { + const testing = std.testing; + const alloc = testing.allocator; + + var grants: Grants = .{}; + defer grants.deinit(alloc); + + var buf: [8]u8 = undefined; + for (0..Grants.max_entries + 1) |i| { + const pw = try std.fmt.bufPrint(&buf, "pw{}", .{i}); + try grants.grant(alloc, pw, .read, false); + } + + // The oldest grant was evicted; the newest survives. + try testing.expect(!grants.use(alloc, "pw0", .read)); + const newest = try std.fmt.bufPrint(&buf, "pw{}", .{Grants.max_entries}); + try testing.expect(grants.use(alloc, newest, .read)); +} + +test "generateOtp: length and alphabet with a real Io" { + const testing = std.testing; + + const otp = try generateOtp(testing.io); + try testing.expectEqual(otp_len, otp.len); + for (otp) |c| try testing.expect(std.mem.indexOfScalar(u8, otp_alphabet, c) != null); + + // Two passwords don't collide (a repeat would mean no entropy). + const other = try generateOtp(testing.io); + try testing.expect(!std.mem.eql(u8, &otp, &other)); +} + +test "generateOtp: no entropy is an error, never a weak password" { + const testing = std.testing; + try testing.expectError(error.EntropyUnavailable, generateOtp(std.Io.failing)); +} + +test "generateOtp: sys override supplies entropy without an Io source" { + const testing = std.testing; + const S = struct { + var counter: u8 = 0; + fn fill(buffer: []u8) sys.RandomSecureError!void { + for (buffer) |*b| { + b.* = counter; + counter +%= 1; + } + } + }; + sys.random_secure = &S.fill; + defer sys.random_secure = null; + + const otp = try generateOtp(std.Io.failing); + for (otp) |c| try testing.expect(std.mem.indexOfScalar(u8, otp_alphabet, c) != null); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/clipboard_response.zig b/vendor/libghostty-vt/src/terminal/kitty/clipboard_response.zig new file mode 100644 index 00000000..50bbbc67 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/clipboard_response.zig @@ -0,0 +1,469 @@ +//! Kitty clipboard protocol (OSC 5522) response encoding. + +const std = @import("std"); +const clipboard = @import("../clipboard.zig"); +const oscpkg = @import("../osc.zig"); +const protocol = @import("../osc/parsers/kitty_clipboard_protocol.zig"); + +const b64 = std.base64.standard.Encoder; +const Content = clipboard.Content; +const Operation = protocol.Operation; +const Status = protocol.Status; +const Terminator = oscpkg.Terminator; + +/// Maximum raw (pre-base64) bytes per DATA packet in read responses. +/// This is specified by the protocol. +pub const read_chunk_size = 4096; + +/// Maximum requested MIME types served by a single read request. +/// Requests beyond this simply see no DATA packets for the extras, +/// which is how the protocol communicates an unavailable type anyway. +pub const max_read_mimes = 4; + +/// The special MIME type that requests the list of available types. +pub const targets_mime = "."; + +/// Maximum MIME types reported in a paste event's targets listing. +pub const max_listing_mimes = 16; + +/// A single response packet. +pub const Response = struct { + op: Operation, + status: Status, + primary: bool = false, + id: []const u8 = "", + mime: ?[]const u8 = null, + pw: ?[]const u8 = null, + /// The raw payload; the encoder base64-encodes it. An empty payload + /// emits no payload section at all (no ';'). + payload: []const u8 = "", + terminator: Terminator = .st, + + /// Encode the response. Errors may result in partially written data + /// so it is up to callers to buffer it if they need to. + pub fn encode( + self: *const Response, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + try self.encodeMetadata(writer); + if (self.payload.len > 0) { + try writer.writeAll(";"); + try b64.encodeWriter(writer, self.payload); + } + try writer.writeAll(self.terminator.string()); + } + + /// Encode the escape prefix and metadata section only: everything + /// up to (and not including) the payload section and terminator. + fn encodeMetadata( + self: *const Response, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + // The exact order of fields here matches what Kitty does. + try writer.print("\x1b]5522;type={t}:status={t}", .{ self.op, self.status }); + if (self.primary) try writer.writeAll(":loc=primary"); + if (self.id.len > 0) try writer.print(":id={s}", .{self.id}); + if (self.mime) |mime| { + try writer.writeAll(":mime="); + try b64.encodeWriter(writer, mime); + } + if (self.pw) |pw| { + try writer.writeAll(":pw="); + try b64.encodeWriter(writer, pw); + } + } +}; + +/// Encode a full successful read response: the OK packet, the targets +/// listing if requested, DATA chunks for each served representation, +/// and the final DONE packet. This is also the shape of an unsolicited +/// paste event (list=true, pw set to the one-time password). +pub const ReadSuccess = struct { + primary: bool = false, + id: []const u8 = "", + + /// One-time password echoed in every packet. Only used for + /// terminal-initiated paste events. + pw: ?[]const u8 = null, + + /// True when the targets ('.') listing was requested. + list: bool = false, + + /// The MIME types available on the clipboard, reported by the + /// targets listing. Kitty reports these space-separated in one + /// packet with a trailing newline when non-empty. + available: []const []const u8 = &.{}, + + /// The representations to serve, in request order. Each entry's + /// data is chunked into DATA packets under its own MIME type. An + /// entry with empty data produces no packets, which is how the + /// protocol communicates an unavailable type. + contents: []const Content = &.{}, + + terminator: Terminator = .st, + + pub fn encode( + self: *const ReadSuccess, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + // Initial read response + try (Response{ + .op = .read, + .status = .OK, + .primary = self.primary, + .id = self.id, + .pw = self.pw, + .terminator = self.terminator, + }).encode(writer); + + // Listing of mimes if requested + if (self.list) try self.encodeListing(writer); + + // Encoding of each mime-type + content + for (self.contents) |content| { + var i: usize = 0; + while (i < content.data.len) { + const n = @min(content.data.len - i, read_chunk_size); + try (Response{ + .op = .read, + .status = .DATA, + .id = self.id, + .mime = content.mime, + .pw = self.pw, + .payload = content.data[i..][0..n], + .terminator = self.terminator, + }).encode(writer); + i += n; + } + } + + // Trailing done. + try (Response{ + .op = .read, + .status = .DONE, + .id = self.id, + .pw = self.pw, + .terminator = self.terminator, + }).encode(writer); + } + + /// Encode the targets ('.') listing packet. The listing gets a + /// trailing newline when non-empty. + fn encodeListing( + self: *const ReadSuccess, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + const listing: Response = .{ + .op = .read, + .status = .DATA, + .id = self.id, + .mime = targets_mime, + .pw = self.pw, + .terminator = self.terminator, + }; + try listing.encodeMetadata(writer); + if (self.available.len > 0) { + try writer.writeAll(";"); + + // Join the types into one chunk before encoding. The + // listing is a DATA packet, so it shares the pre-encoding + // chunk size bound of any other data packet; types that + // don't fit are dropped (a listing that large doesn't + // happen in practice). + var raw: [read_chunk_size]u8 = undefined; + var fixed: std.Io.Writer = .fixed(&raw); + for (self.available, 0..) |mime, i| { + const sep: usize = if (i > 0) 1 else 0; + if (fixed.end + sep + mime.len + "\n".len > raw.len) break; + if (i > 0) fixed.writeAll(" ") catch unreachable; + fixed.writeAll(mime) catch unreachable; + } + fixed.writeAll("\n") catch unreachable; + try b64.encodeWriter(writer, fixed.buffered()); + } + try writer.writeAll(self.terminator.string()); + } +}; + +/// An unsolicited Kitty paste event (mode 5522): a read response that +/// lists the clipboard's available MIME types and carries the one-time +/// password the program uses for its follow-up read. +pub const PasteEvent = struct { + /// True if the paste came from the primary selection, reported as + /// `loc=primary` on the OK packet. + primary: bool = false, + + /// The one-time password, echoed in every packet. + pw: []const u8, + + /// The MIME types available on the clipboard. + available: []const []const u8, + + terminator: Terminator = .st, + + pub fn encode( + self: *const PasteEvent, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + try (ReadSuccess{ + .primary = self.primary, + .pw = self.pw, + .list = true, + .available = self.available, + .terminator = self.terminator, + }).encode(writer); + } +}; + +test "response: basic status packet" { + const testing = std.testing; + + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Response{ .op = .write, .status = .DONE }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=write:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "response: id echo and terminator" { + const testing = std.testing; + + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Response{ + .op = .write, + .status = .EPERM, + .id = "42", + .terminator = .bel, + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=write:status=EPERM:id=42\x07", + writer.buffered(), + ); +} + +test "response: key order type,status,loc,id,mime,pw and payload" { + const testing = std.testing; + + var buf: [256]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Response{ + .op = .read, + .status = .DATA, + .primary = true, + .id = "x", + .mime = "text/plain", + .pw = "otp", + .payload = "Ghostty", + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=DATA:loc=primary:id=x" ++ + ":mime=dGV4dC9wbGFpbg==:pw=b3Rw;R2hvc3R0eQ==\x1b\\", + writer.buffered(), + ); +} + +test "read success: empty request is OK then DONE" { + const testing = std.testing; + + var buf: [256]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ .id = "7" }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK:id=7\x1b\\" ++ + "\x1b]5522;type=read:status=DONE:id=7\x1b\\", + writer.buffered(), + ); +} + +test "read success: targets listing with text" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ .list = true, .available = &.{"text/plain"} }).encode(&writer); + // "." => "Lg==", "text/plain\n" => "dGV4dC9wbGFpbgo=" + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==;dGV4dC9wbGFpbgo=\x1b\\" ++ + "\x1b]5522;type=read:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "read success: targets listing joins multiple types" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ + .list = true, + .available = &.{ "text/plain", "image/png" }, + }).encode(&writer); + // Payload is base64 of "text/plain image/png\n". + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==;dGV4dC9wbGFpbiBpbWFnZS9wbmcK\x1b\\" ++ + "\x1b]5522;type=read:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "read success: empty targets listing packet still sent" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ .list = true }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==\x1b\\" ++ + "\x1b]5522;type=read:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "read success: data chunks under requested mime" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ + .contents = &.{.{ .mime = "text/plain", .data = "Ghostty" }}, + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=dGV4dC9wbGFpbg==;R2hvc3R0eQ==\x1b\\" ++ + "\x1b]5522;type=read:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "read success: each representation carries its own data" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ + .contents = &.{ + .{ .mime = "text/plain", .data = "hello" }, + .{ .mime = "image/png", .data = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" }, + }, + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=dGV4dC9wbGFpbg==;aGVsbG8=\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=aW1hZ2UvcG5n;iVBORw0KGgo=\x1b\\" ++ + "\x1b]5522;type=read:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "read success: chunking at read_chunk_size" { + const testing = std.testing; + const alloc = testing.allocator; + + const data = "z" ** (read_chunk_size + 1); + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + try (ReadSuccess{ + .contents = &.{.{ .mime = "text/plain", .data = data }}, + }).encode(&aw.writer); + + // OK + 2 DATA packets + DONE = 4 packets. + const count = std.mem.count(u8, aw.written(), "\x1b]5522;"); + try testing.expectEqual(@as(usize, 4), count); + + // The first chunk is exactly read_chunk_size bytes, base64 encoded + // with padding. + const Encoder = std.base64.standard.Encoder; + var chunk_buf: [Encoder.calcSize(read_chunk_size)]u8 = undefined; + const first = Encoder.encode(&chunk_buf, data[0..read_chunk_size]); + try testing.expect(std.mem.indexOf(u8, aw.written(), first) != null); +} + +test "read success: no data packets for empty clipboard" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ + .contents = &.{.{ .mime = "text/plain", .data = "" }}, + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK\x1b\\" ++ + "\x1b]5522;type=read:status=DONE\x1b\\", + writer.buffered(), + ); +} + +test "read success: paste event carries pw in every packet" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (ReadSuccess{ + .list = true, + .pw = "otp", + .available = &.{"text/plain"}, + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK:pw=b3Rw\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==:pw=b3Rw;dGV4dC9wbGFpbgo=\x1b\\" ++ + "\x1b]5522;type=read:status=DONE:pw=b3Rw\x1b\\", + writer.buffered(), + ); +} + +test "paste event: pw in every packet, listing of every type" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (PasteEvent{ + .pw = "otp", + .available = &.{ "text/plain", "image/png" }, + }).encode(&writer); + // Payload is base64 of "text/plain image/png\n". + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK:pw=b3Rw\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==:pw=b3Rw;dGV4dC9wbGFpbiBpbWFnZS9wbmcK\x1b\\" ++ + "\x1b]5522;type=read:status=DONE:pw=b3Rw\x1b\\", + writer.buffered(), + ); +} + +test "paste event: primary is reported only on the OK packet" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (PasteEvent{ + .primary = true, + .pw = "otp", + .available = &.{"text/plain"}, + .terminator = .bel, + }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK:loc=primary:pw=b3Rw\x07" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==:pw=b3Rw;dGV4dC9wbGFpbgo=\x07" ++ + "\x1b]5522;type=read:status=DONE:pw=b3Rw\x07", + writer.buffered(), + ); +} + +test "paste event: empty listing packet is still sent" { + const testing = std.testing; + + var buf: [512]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (PasteEvent{ .pw = "otp", .available = &.{} }).encode(&writer); + try testing.expectEqualStrings( + "\x1b]5522;type=read:status=OK:pw=b3Rw\x1b\\" ++ + "\x1b]5522;type=read:status=DATA:mime=Lg==:pw=b3Rw\x1b\\" ++ + "\x1b]5522;type=read:status=DONE:pw=b3Rw\x1b\\", + writer.buffered(), + ); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/clipboard_write.zig b/vendor/libghostty-vt/src/terminal/kitty/clipboard_write.zig new file mode 100644 index 00000000..5951dcbe --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/clipboard_write.zig @@ -0,0 +1,698 @@ +//! Kitty clipboard protocol (OSC 5522) write transactions: the +//! stateful accumulation of wdata chunks and walias aliases until the +//! commit packet arrives. See clipboard.zig for the protocol overview. + +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const simd = @import("../../simd/main.zig"); +const clipboard = @import("../clipboard.zig"); +const clipboard_command = @import("clipboard_command.zig"); + +const Metadata = clipboard_command.Metadata; +const Payload = clipboard_command.Payload; +const max_mime_len = clipboard_command.max_mime_len; + +const log = std.log.scoped(.kitty_clipboard); + +/// Default maximum total decoded bytes accumulated by one write +/// transaction. Embedders can override this per-transaction via +/// WriteState.Options (Ghostty exposes it as the +/// `clipboard-write-limit-bytes` configuration). +pub const max_write_size = 64 * 1024 * 1024; + +/// Maximum MIME types and aliases per write transaction. +pub const max_write_mimes = 64; +pub const max_write_aliases = 64; + +/// One MIME representation of committed clipboard data. This is the +/// same type the clipboard write effect consumes so committed contents +/// can be passed through directly. +pub const Content = clipboard.Content; + +/// The state of one in-flight write transaction: a single `type=write` +/// plus all the `wdata` chunks and `walias` aliases until completion +/// or error. +pub const WriteState = struct { + arena: std.heap.ArenaAllocator, + loc: clipboard.Location, + id: []const u8, + pw: []const u8, + name: []const u8, + spool: std.ArrayListUnmanaged(u8) = .empty, + entries: std.ArrayListUnmanaged(Entry) = .empty, + aliases: std.ArrayListUnmanaged(Alias) = .empty, + + /// Maximum total decoded bytes this transaction will accumulate. + /// Captured at init so a change to the configured limit doesn't + /// apply to a transaction already in flight. + max_size: usize, + + /// Index into entries currently receiving data. + current: ?usize = null, + + /// Decodes the concatenated payload stream of the entry currently + /// receiving data. Per the spec's "Encoding of payloads" section, + /// individual wdata packet payloads split one base64 stream at + /// arbitrary boundaries; only the concatenation per MIME type must + /// be valid, correctly padded base64. + decoder: simd.base64.Streaming = .{}, + + pub const Options = struct { + /// Maximum total decoded bytes accumulated by the transaction. + max_size: usize = max_write_size, + }; + + const Entry = struct { + /// Owned by the transaction arena. + mime: []const u8, + start: usize = 0, + len: usize = 0, + }; + + const Alias = struct { + /// Owned by the transaction arena. + alias: []const u8, + target: []const u8, + }; + + /// Begin a transaction from a type=write packet. + pub fn init( + alloc: Allocator, + meta: *const Metadata, + opts: Options, + ) Allocator.Error!WriteState { + assert(meta.op == .write); + var arena: std.heap.ArenaAllocator = .init(alloc); + errdefer arena.deinit(); + const id = try arena.allocator().dupe(u8, meta.id); + const pw = try arena.allocator().dupe(u8, meta.pw); + const name = try arena.allocator().dupe(u8, meta.name); + return .{ + .arena = arena, + .loc = meta.loc, + .id = id, + .pw = pw, + .name = name, + .max_size = opts.max_size, + }; + } + + pub fn deinit(self: *WriteState, alloc: Allocator) void { + self.spool.deinit(alloc); + self.entries.deinit(alloc); + self.aliases.deinit(alloc); + self.arena.deinit(); + } + + /// Accumulate one wdata chunk carrying data for meta.mime (which + /// must be non-empty; an empty mime is a commit, not data). + /// + /// Returns error.TooLarge when the transaction exceeds max_size + /// and error.Invalid when the payload stream is not valid base64. + /// The caller must fail the whole transaction with EFBIG or EINVAL + /// respectively and abort it, as required by the protocol. + pub fn data( + self: *WriteState, + alloc: Allocator, + meta: *const Metadata, + payload: []const u8, + ) error{ OutOfMemory, TooLarge, Invalid }!void { + assert(meta.op == .wdata); + assert(meta.mime.len > 0); + // Switch the receiving entry if this chunk is for a different + // MIME type than the last one. + entry: { + if (self.current) |idx| { + const entry = &self.entries.items[idx]; + if (std.mem.eql(u8, entry.mime, meta.mime)) { + break :entry; + } + + // Finalize the previous region. Its concatenated + // stream must have ended on a complete base64 group, + // otherwise the data was not correctly padded. + try self.finishCurrent(); + entry.len = self.spool.items.len - entry.start; + } + + // Re-using an earlier MIME type starts a fresh region, + // overwriting the previous mapping. + for (self.entries.items, 0..) |*entry, idx| { + if (std.mem.eql(u8, entry.mime, meta.mime)) { + entry.start = self.spool.items.len; + entry.len = 0; + self.current = idx; + break :entry; + } + } + + if (self.entries.items.len >= max_write_mimes) { + log.warn( + "clipboard write has too many MIME types, ignoring mime={s}", + .{meta.mime}, + ); + self.current = null; + return; + } + + try self.entries.append(alloc, .{ + .mime = try self.arena.allocator().dupe(u8, meta.mime), + .start = self.spool.items.len, + }); + self.current = self.entries.items.len - 1; + } + + // The payloads for one MIME region concatenate into a single + // strict base64 stream, decoded directly into the spool's + // unused capacity. Invalid data aborts the transaction; per + // the spec it must not be silently discarded "since that + // turns corrupted data into apparently valid data". + try self.spool.ensureUnusedCapacity(alloc, self.decoder.maxLen(payload)); + const decoded = self.decoder.feed( + payload, + self.spool.unusedCapacitySlice(), + ) catch return error.Invalid; + + // The limit covers all decoded data in the transaction. Going + // over it aborts the entire write; partial clipboard contents + // must never reach the embedder. + const remaining = self.max_size -| self.spool.items.len; + if (decoded.len > remaining) return error.TooLarge; + self.spool.items.len += decoded.len; + } + + /// Finish the decode stream of the entry currently receiving + /// data. Returns error.Invalid when the stream ends mid-group, + /// i.e. the concatenated payload was not correctly padded. + fn finishCurrent(self: *WriteState) error{Invalid}!void { + self.decoder.finish() catch return error.Invalid; + } + + /// Register aliases from a walias packet: meta.mime is the target + /// (the type that carries data) and the payload is a base64-encoded, + /// whitespace-separated list of aliases. Returns error.Invalid for + /// an undecodable payload, which aborts the transaction with EINVAL. + pub fn alias( + self: *WriteState, + alloc: Allocator, + meta: *const Metadata, + payload: []const u8, + ) error{ OutOfMemory, Invalid }!void { + assert(meta.op == .walias); + assert(meta.mime.len > 0); + const decoded = try Payload.init(alloc, payload); + defer decoded.deinit(alloc); + if (!decoded.isValidUtf8()) return error.Invalid; + var it = decoded.mimeIterator(); + + // Copy the target only if at least one valid alias exists. + const target: []const u8 = target: { + while (it.next()) |name| { + if (name.len > max_mime_len) continue; + break :target try self.arena.allocator().dupe(u8, meta.mime); + } + + // If we didn't find a target then ignore it. + return; + }; + + // Rewind so the alias that satisfied the check above is + // associated too. + it.reset(); + + // Associate the aliases + while (it.next()) |name| { + if (name.len > max_mime_len) continue; + + // A repeated alias overwrites its previous target. + for (self.aliases.items) |*a| { + if (std.mem.eql(u8, a.alias, name)) { + a.target = target; + break; + } + } else { + if (self.aliases.items.len >= max_write_aliases) { + log.warn("clipboard write has too many aliases, ignoring", .{}); + return; + } + + try self.aliases.append(alloc, .{ + .alias = try self.arena.allocator().dupe(u8, name), + .target = target, + }); + } + } + } + + /// The result of a committed transaction. All slices borrow the + /// WriteState's memory and are valid until it is deinited. + pub const Committed = struct { + loc: clipboard.Location, + id: []const u8, + pw: []const u8, + name: []const u8, + contents: []const Content, + + pub fn deinit(self: *const Committed, alloc: Allocator) void { + alloc.free(self.contents); + } + }; + + /// Commit the transaction (a wdata packet without a MIME type). + /// The caller must use the result, call Committed.deinit, and then + /// deinit this state. Returns error.Invalid when the last region's + /// concatenated payload was not correctly padded; the caller must + /// fail the transaction with EINVAL and abort it. + pub fn commit( + self: *WriteState, + alloc: Allocator, + ) error{ OutOfMemory, Invalid }!Committed { + // Finalize the region receiving data. + if (self.current) |idx| { + try self.finishCurrent(); + const entry = &self.entries.items[idx]; + entry.len = self.spool.items.len - entry.start; + self.current = null; + } + + // Resolve the final MIME map: entries in arrival order, then + // aliases applied sequentially against the evolving map so + // chained aliases work like kitty's dict iteration. An alias + // whose target has no mapping is dropped; an alias colliding + // with an existing name overwrites it. + var contents: std.ArrayListUnmanaged(Content) = .empty; + defer contents.deinit(alloc); + try contents.ensureTotalCapacity( + alloc, + self.entries.items.len + self.aliases.items.len, + ); + + for (self.entries.items) |*entry| { + contents.appendAssumeCapacity(.{ + .mime = entry.mime, + .data = self.spool.items[entry.start..][0..entry.len], + }); + } + + for (self.aliases.items) |*a| { + const target: Content = target: { + for (contents.items) |c| { + if (std.mem.eql(u8, c.mime, a.target)) { + break :target c; + } + } + continue; + }; + + for (contents.items) |*c| { + if (std.mem.eql(u8, c.mime, a.alias)) { + c.data = target.data; + break; + } + } else { + contents.appendAssumeCapacity(.{ + .mime = a.alias, + .data = target.data, + }); + } + } + + return .{ + .loc = self.loc, + .id = self.id, + .pw = self.pw, + .name = self.name, + .contents = try contents.toOwnedSlice(alloc), + }; + } +}; + +test "write: basic transaction" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write, .id = "42" }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "R2hvc3R0eQ=="); // "Ghostty" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqualStrings("42", committed.id); + try testing.expect(committed.loc == .standard); + try testing.expectEqual(@as(usize, 1), committed.contents.len); + try testing.expectEqualStrings("text/plain", committed.contents[0].mime); + try testing.expectEqualStrings("Ghostty", committed.contents[0].data); +} + +test "write: chunked data accumulates" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "SGVsbG8="); // "Hello" + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "V29ybGQ="); // "World" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqualStrings("HelloWorld", committed.contents[0].data); +} + +test "write: multiple mimes in order" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "YQ=="); // "a" + try state.data(alloc, &.{ .op = .wdata, .mime = "text/html" }, "Yg=="); // "b" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqual(@as(usize, 2), committed.contents.len); + try testing.expectEqualStrings("text/plain", committed.contents[0].mime); + try testing.expectEqualStrings("a", committed.contents[0].data); + try testing.expectEqualStrings("text/html", committed.contents[1].mime); + try testing.expectEqualStrings("b", committed.contents[1].data); +} + +test "write: reused mime overwrites" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "YQ=="); // "a" + try state.data(alloc, &.{ .op = .wdata, .mime = "text/html" }, "Yg=="); // "b" + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "Yw=="); // "c" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqual(@as(usize, 2), committed.contents.len); + // Position preserved, data replaced. + try testing.expectEqualStrings("text/plain", committed.contents[0].mime); + try testing.expectEqualStrings("c", committed.contents[0].data); +} + +test "write: invalid base64 chunk aborts the transaction" { + const testing = std.testing; + const alloc = testing.allocator; + + // Invalid characters anywhere in the stream are error.Invalid, + // which the handlers turn into an EINVAL abort. These mirror + // kitty's own tests for the spec change. + const invalid_payloads = [_][]const u8{ + "!!!", + "SGVs!!!bG8=", + "\nZGF0YSB3aXRoIGEgbmV3bGluZQ==", + }; + for (invalid_payloads) |payload| { + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + try testing.expectError(error.Invalid, state.data( + alloc, + &.{ .op = .wdata, .mime = "text/plain" }, + payload, + )); + } + + // Also after an earlier valid chunk for the same MIME type. + { + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "Z29vZA=="); // "good" + try testing.expectError(error.Invalid, state.data( + alloc, + &.{ .op = .wdata, .mime = "text/plain" }, + "SGVs!!!bG8=", + )); + } +} + +test "write: chunks split one base64 stream at arbitrary boundaries" { + const testing = std.testing; + const alloc = testing.allocator; + + // The concatenation of all payloads per MIME type is the base64 + // stream; individual packets need not be a multiple of four bytes. + const encoded = "c29tZSBkYXRh"; // "some data" + const splits = [_][]const usize{ + &.{ 3, 7 }, + &.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, + }; + for (splits) |split| { + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + var prev: usize = 0; + for (split) |end| { + try state.data( + alloc, + &.{ .op = .wdata, .mime = "text/plain" }, + encoded[prev..end], + ); + prev = end; + } + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, encoded[prev..]); + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqualStrings("some data", committed.contents[0].data); + } +} + +test "write: incorrectly padded stream aborts at commit" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + // "Hello" without its final padding byte: every chunk decodes, + // but the stream ends mid-group so the commit reports it. + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "SGVsbG8"); + try testing.expectError(error.Invalid, state.commit(alloc)); +} + +test "write: incorrectly padded stream aborts at MIME switch" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "SGVsbG8"); + try testing.expectError(error.Invalid, state.data( + alloc, + &.{ .op = .wdata, .mime = "text/html" }, + "PGI+aGk8L2I+", + )); +} + +test "write: independently padded chunks accumulate" { + const testing = std.testing; + const alloc = testing.allocator; + + // A packet payload ending exactly at terminal padding resets the + // stream, so clients that base64-encode every chunk independently + // keep working (matching kitty, which resets its streaming + // decoder on EOF). Padding followed by more data within a single + // packet stays invalid. + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "Z29vZA=="); // "good" + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "bW9yZQ=="); // "more" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqualStrings("goodmore", committed.contents[0].data); +} + +test "write: data after padding within one chunk aborts" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try testing.expectError(error.Invalid, state.data( + alloc, + &.{ .op = .wdata, .mime = "text/plain" }, + "Z29vZA==bW9yZQ==", + )); +} + +test "write: aliases resolve at commit" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "R2hvc3R0eQ=="); // "Ghostty" + + // Alias "TEXT UTF8_STRING" -> text/plain. + const alias_meta: Metadata = .{ .op = .walias, .mime = "text/plain" }; + try state.alias(alloc, &alias_meta, "VEVYVCBVVEY4X1NUUklORw=="); + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqual(@as(usize, 3), committed.contents.len); + try testing.expectEqualStrings("TEXT", committed.contents[1].mime); + try testing.expectEqualStrings("Ghostty", committed.contents[1].data); + try testing.expectEqualStrings("UTF8_STRING", committed.contents[2].mime); + try testing.expectEqualStrings("Ghostty", committed.contents[2].data); +} + +test "write: alias payload must be valid utf8" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + const alias_meta: Metadata = .{ .op = .walias, .mime = "text/plain" }; + // Valid base64 encoding of a single 0xff byte. + try testing.expectError( + error.Invalid, + state.alias(alloc, &alias_meta, "/w=="), + ); +} + +test "write: default limit when unset" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + try testing.expectEqual(@as(usize, max_write_size), state.max_size); +} + +test "write: text over limit rejects transaction" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{ .max_size = 8 }); + defer state.deinit(alloc); + + try testing.expectError(error.TooLarge, state.data( + alloc, + &.{ .op = .wdata, .mime = "text/plain" }, + "SGVsbG9Xb3JsZA==", // "HelloWorld" + )); +} + +test "write: text crossing limit across chunks rejects transaction" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{ .max_size = 8 }); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "SGVsbG8="); // "Hello" + try testing.expectError(error.TooLarge, state.data( + alloc, + &.{ .op = .wdata, .mime = "text/plain" }, + "V29ybGQ=", // "World" + )); +} + +test "write: data exactly at limit is accepted" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{ .max_size = 5 }); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "SGVsbG8="); // "Hello" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqualStrings("Hello", committed.contents[0].data); +} + +test "write: non-text under limit is unaffected" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{ .max_size = 8 }); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "image/png" }, "iVBORw=="); // "\x89PNG" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqualStrings("\x89PNG", committed.contents[0].data); +} + +test "write: non-text over limit rejects transaction" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{ .max_size = 8 }); + defer state.deinit(alloc); + + try testing.expectError(error.TooLarge, state.data( + alloc, + &.{ .op = .wdata, .mime = "image/png" }, + "SGVsbG9Xb3JsZA==", // "HelloWorld" + )); +} + +test "write: total data across MIME types is limited" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{ .max_size = 8 }); + defer state.deinit(alloc); + + try state.data(alloc, &.{ .op = .wdata, .mime = "text/plain" }, "SGVsbG8="); // "Hello" + + try testing.expectError(error.TooLarge, state.data( + alloc, + &.{ .op = .wdata, .mime = "image/png" }, + "V29ybGQ=", // "World" + )); +} + +test "write: alias without data target is dropped" { + const testing = std.testing; + const alloc = testing.allocator; + + const begin_meta: Metadata = .{ .op = .write }; + var state: WriteState = try .init(alloc, &begin_meta, .{}); + defer state.deinit(alloc); + + const alias_meta: Metadata = .{ .op = .walias, .mime = "text/plain" }; + try state.alias(alloc, &alias_meta, "VEVYVA=="); // "TEXT" + + const committed = try state.commit(alloc); + defer committed.deinit(alloc); + try testing.expectEqual(@as(usize, 0), committed.contents.len); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/dnd.zig b/vendor/libghostty-vt/src/terminal/kitty/dnd.zig new file mode 100644 index 00000000..3142a415 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/dnd.zig @@ -0,0 +1,69 @@ +//! Kitty drag and drop protocol (OSC 72). +//! +//! Specification: https://sw.kovidgoyal.net/kitty/dnd-protocol/ +//! +//! The protocol lets a program running in the terminal participate in +//! native OS drag and drop. A client registers to accept drops (t=a); +//! the terminal then forwards native drag movement (t=m) and drops +//! (t=M) to it and serves the dropped data on request (t=r), instead +//! of the traditional behavior of pasting dropped paths or text. +//! +//! ## Divergences +//! +//! These will be fixed in the future: +//! +//! * Dropped data is captured eagerly at drop time from a curated +//! set of representations the embedder can serve (typically +//! text/uri-list and text/plain), rather than fetched from the OS +//! on demand. Consequently the native drag session concludes at +//! drop time and the client's concluding operation (t=r with +//! x=y=Y=0) only frees the held data, and kitty's 128-entry +//! request queue and EMFILE overflow handling are unnecessary +//! because requests are served synchronously in order. +//! * Every client is treated as local: machine IDs (t=a:x=1) are +//! accepted and ignored, responses never carry the X=1 remote +//! marker, and remote file transfer requests (t=r with y or Y +//! keys) are answered with EINVAL. A remote client (e.g. over +//! ssh) can still receive text drops; only file-content transfer +//! is unavailable. +//! * The terminal never initiates drags (drag out): enabling and +//! disabling offers (t=o:x=1, t=o:x=2) are accepted and ignored, +//! and since the terminal never sends a drag start request a +//! conforming client never offers a drag. Direct offers (t=o:x=0) +//! and drag data/start commands (t=p, t=P) are refused with EPERM. +//! +//! These are on purpose forever: +//! +//! * Responses echo the requesting command's terminator (ST or BEL) +//! per ghostty convention; kitty always uses ST. Terminal- +//! initiated events always use ST. + +const dnd_command = @import("dnd_command.zig"); +const dnd_response = @import("dnd_response.zig"); +const dnd_drop = @import("dnd_drop.zig"); + +pub const EventType = dnd_command.EventType; +pub const Metadata = dnd_command.Metadata; +pub const Operation = dnd_command.Operation; +pub const Operations = dnd_command.Operations; +pub const Request = dnd_command.Request; +pub const Chunking = dnd_command.Chunking; + +pub const Errno = dnd_response.Errno; +pub const RequestKeys = dnd_response.RequestKeys; +pub const encode = dnd_response.encode; +pub const encodeError = dnd_response.encodeError; + +pub const State = dnd_drop.State; +pub const Item = dnd_drop.State.Item; +pub const MoveEvent = dnd_drop.State.MoveEvent; +pub const max_mime_list_bytes = dnd_drop.max_mime_list_bytes; +pub const handleCommand = dnd_drop.handleCommand; +pub const Event = dnd_drop.Event; + +test { + _ = dnd_command; + _ = dnd_response; + _ = dnd_drop; + _ = @import("dnd_test.zig"); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/dnd_command.zig b/vendor/libghostty-vt/src/terminal/kitty/dnd_command.zig new file mode 100644 index 00000000..b5f63d02 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/dnd_command.zig @@ -0,0 +1,436 @@ +const std = @import("std"); + +/// Decoded OSC 72 metadata. +pub const Metadata = struct { + /// Event type (`t`). Null when the metadata had no `t` key; such + /// commands parse successfully but are ignored, matching kitty. + type: ?EventType = null, + + /// Chunking flag (`m`): true when more chunks follow. + more: bool = false, + + /// Multiplexer client ID (`i`), echoed in every response so a + /// terminal multiplexer can route responses to the correct client. + client_id: u32 = 0, + + /// Operation (`o`): meaning depends on the event type, commonly + /// 0=none/reject, 1=copy, 2=move, 3=copy or move. + operation: u32 = 0, + + /// `x`, `y`, `X`, `Y` keys. + cell_x: i32 = 0, + cell_y: i32 = 0, + pixel_x: i32 = 0, + pixel_y: i32 = 0, + + /// Parse raw OSC 72 metadata (the part before the first `;`). + /// Returns null when malformed; callers should ignore the command, + /// matching kitty which rejects the entire command on any error. + pub fn parse(raw: []const u8) ?Metadata { + var result: Metadata = .{}; + var pos: usize = 0; + // The continue expression consumes the ':' separating a field + // from the next; the body advances past the field itself. + while (pos < raw.len) : (pos += 1) { + // Single-character key. + const key = raw[pos]; + pos += 1; + switch (key) { + 't', 'm', 'i', 'o', 'x', 'y', 'X', 'Y' => {}, + else => return null, + } + + // '=' separator. + if (pos >= raw.len) return null; + if (raw[pos] != '=') return null; + pos += 1; + + // Value. + if (pos >= raw.len) return null; + switch (key) { + 't' => { + result.type = std.enums.fromInt( + EventType, + raw[pos], + ) orelse return null; + pos += 1; + }, + + 'm', 'i', 'o' => { + const v = parseUnsigned(raw, &pos) orelse return null; + switch (key) { + 'm' => result.more = v != 0, + 'i' => result.client_id = v, + 'o' => result.operation = v, + else => unreachable, + } + }, + + 'x', 'y', 'X', 'Y' => { + const negative = raw[pos] == '-'; + if (negative) pos += 1; + const unsigned = parseUnsigned(raw, &pos) orelse return null; + // Matches kitty's cast of the u32 magnitude to i32, + // which wraps rather than erroring on overflow. + const magnitude: i32 = @bitCast(unsigned); + const v = if (negative) 0 -% magnitude else magnitude; + switch (key) { + 'x' => result.cell_x = v, + 'y' => result.cell_y = v, + 'X' => result.pixel_x = v, + 'Y' => result.pixel_y = v, + else => unreachable, + } + }, + + else => unreachable, + } + + // Values are separated by ':'. + if (pos >= raw.len) break; + if (raw[pos] != ':') return null; + } + + return result; + } + + /// Parse an unsigned decimal value at `pos`, advancing it. At most + /// 10 digits and at most maxInt(u32), matching kitty. Returns null + /// when there are no digits or the value is too large. + fn parseUnsigned(raw: []const u8, pos: *usize) ?u32 { + const start = pos.*; + var acc: u64 = 0; + var i = start; + while (i < raw.len and i < start + 10) : (i += 1) { + const d = raw[i] -% '0'; + if (d > 9) break; + acc = acc * 10 + d; + } + if (i == start) return null; + pos.* = i; + return std.math.cast(u32, acc) orelse null; + } +}; + +/// The event type, i.e. values for the `t` metadata key. A single OSC 72 +/// code is used for both directions of the protocol, so most types have +/// one meaning when received by the terminal from a client and another +/// when sent by the terminal to a client. +/// +/// The `drop` and `request_response` types are only ever sent by the +/// terminal; kitty parses but ignores them when received and we do the +/// same. +pub const EventType = enum(u8) { + /// 'a': (recv) client registers to accept drops. With x=1 the payload + /// is the client's machine ID for remote drop support instead. + register = 'a', + + /// 'A': (recv) client unregisters from accepting drops. + unregister = 'A', + + /// 'm': (recv) client reports acceptance status for the drag currently + /// over the terminal: `o` is the chosen operation and the payload is + /// the accepted MIME list. (send) pointer moved over the terminal + /// during a drag, or with x=-1,y=-1 the drag left the window. + status = 'm', + + /// 'M': (send only) items were dropped onto the terminal. + drop = 'M', + + /// 'r': (recv) client requests drop data, or with x=y=Y=0 concludes + /// the drop with `o` as the performed operation. (send) drop data + /// response chunks. + request = 'r', + + /// 'R': (send only) error response to a data request. + request_error = 'R', + + /// 'o': (recv) drag source control: x=1 enables offering drags (payload + /// optionally the client machine ID), x=2 disables, x=0 offers a MIME + /// list for a new drag. (send) request that the client start a drag at + /// the given position. + offer = 'o', + + /// 'p': (recv) pre-sent data for an offered drag: x>=0 is a 0-based + /// MIME index, x<0 attaches drag image -x. + present = 'p', + + /// 'P': (recv) x=-1 starts the offered drag, x>=0 changes the drag + /// image mid-drag. + start_drag = 'P', + + /// 'e': (recv) drag data for MIME index `y` of an in-progress drag. + /// (send) drag status events (accepted, dropped, finished, ...). + drag_event = 'e', + + /// 'E': (recv) client aborts the whole drag (y=-1) or reports an error + /// for MIME index `y`. (send) drag start response (OK or error). + drag_error = 'E', + + /// 'k': (recv) remote file data for a drag. (send) request for remote + /// file data. + remote_data = 'k', + + /// 'q': (recv) query protocol support. (send) the query response. + query = 'q', +}; + +/// A drop operation. Values match the protocol's `o` key. +pub const Operation = enum(u2) { + none = 0, + copy = 1, + move = 2, + + /// Convert a protocol `o` value the way kitty does: anything other + /// than copy or move means none. + pub fn fromProtocol(v: u32) Operation { + return switch (v) { + 1 => .copy, + 2 => .move, + else => .none, + }; + } +}; + +/// The set of operations allowed by a drag source, sent as a bitmask in +/// the `o` key of move and drop events. +pub const Operations = packed struct(u2) { + copy: bool = false, + move: bool = false, + + pub fn protocolValue(self: Operations) u2 { + return @bitCast(self); + } +}; + +/// A decoded `t=r` data request. The request form is disambiguated by +/// which keys are non-zero, mirroring kitty's drop_process_queue. +pub const Request = union(enum) { + /// x=y=Y=0: the drop is concluded with the given operation. + conclude: Operation, + + /// Y=0, y=0, x!=0: request data for the 1-based MIME index x. + mime: i32, + + /// Y=0, y!=0: request the contents of the y'th (1-based) file in the + /// text/uri-list MIME at 1-based index x. Remote drops only. + uri: struct { + mime_idx: i32, + uri_idx: i32, + }, + + /// Y!=0: request entry x (1-based) of directory handle Y, or close + /// the handle when x=0. Remote drops only. + dir: struct { + handle: i32, + entry: i32, + }, + + pub fn init(meta: Metadata) Request { + if (meta.pixel_y != 0) return .{ .dir = .{ + .handle = meta.pixel_y, + .entry = meta.cell_x, + } }; + if (meta.cell_y != 0) return .{ .uri = .{ + .mime_idx = meta.cell_x, + .uri_idx = meta.cell_y, + } }; + if (meta.cell_x != 0) return .{ .mime = meta.cell_x }; + return .{ .conclude = .fromProtocol(meta.operation) }; + } +}; + +/// Chunk reassembly state. +/// +/// While a chunked command is in progress, the metadata of the first +/// chunk is reused for all subsequent chunks; only the `more` flag is +/// taken from each continuation. +pub const Chunking = struct { + active: bool = false, + metadata: Metadata = .{}, + + /// Returns the effective metadata for a received chunk and updates + /// the reassembly state. + pub fn apply(self: *Chunking, meta: Metadata) Metadata { + if (self.active) { + var copy = self.metadata; + copy.more = meta.more; + self.active = meta.more; + return copy; + } + + if (meta.more) { + self.active = true; + self.metadata = meta; + } + + return meta; + } +}; + +test "Metadata: empty" { + const testing = std.testing; + const meta = Metadata.parse("").?; + try testing.expect(meta.type == null); + try testing.expect(!meta.more); + try testing.expectEqual(@as(u32, 0), meta.client_id); +} + +test "Metadata: all keys" { + const testing = std.testing; + const meta = Metadata.parse("t=m:m=1:i=3:o=2:x=10:y=5:X=320:Y=200").?; + try testing.expectEqual(EventType.status, meta.type.?); + try testing.expect(meta.more); + try testing.expectEqual(@as(u32, 3), meta.client_id); + try testing.expectEqual(@as(u32, 2), meta.operation); + try testing.expectEqual(@as(i32, 10), meta.cell_x); + try testing.expectEqual(@as(i32, 5), meta.cell_y); + try testing.expectEqual(@as(i32, 320), meta.pixel_x); + try testing.expectEqual(@as(i32, 200), meta.pixel_y); +} + +test "Metadata: all event types" { + const testing = std.testing; + const cases = .{ + .{ "t=a", EventType.register }, + .{ "t=A", EventType.unregister }, + .{ "t=m", EventType.status }, + .{ "t=M", EventType.drop }, + .{ "t=r", EventType.request }, + .{ "t=R", EventType.request_error }, + .{ "t=o", EventType.offer }, + .{ "t=p", EventType.present }, + .{ "t=P", EventType.start_drag }, + .{ "t=e", EventType.drag_event }, + .{ "t=E", EventType.drag_error }, + .{ "t=k", EventType.remote_data }, + .{ "t=q", EventType.query }, + }; + inline for (cases) |case| { + try testing.expectEqual(case[1], Metadata.parse(case[0]).?.type.?); + } +} + +test "Metadata: case-sensitive coordinate keys" { + const testing = std.testing; + const meta = Metadata.parse("x=10:Y=200").?; + try testing.expectEqual(@as(i32, 10), meta.cell_x); + try testing.expectEqual(@as(i32, 0), meta.cell_y); + try testing.expectEqual(@as(i32, 0), meta.pixel_x); + try testing.expectEqual(@as(i32, 200), meta.pixel_y); +} + +test "Metadata: negative coordinates" { + const testing = std.testing; + const meta = Metadata.parse("t=m:x=-1:y=-1").?; + try testing.expectEqual(@as(i32, -1), meta.cell_x); + try testing.expectEqual(@as(i32, -1), meta.cell_y); +} + +test "Metadata: malformed inputs rejected" { + const testing = std.testing; + // Unknown event type. + try testing.expect(Metadata.parse("t=z") == null); + // Unknown key. + try testing.expect(Metadata.parse("z=1") == null); + // Missing '=' mid-stream. + try testing.expect(Metadata.parse("x10") == null); + // No digits. + try testing.expect(Metadata.parse("x=notanumber") == null); + try testing.expect(Metadata.parse("x=-") == null); + // Too large. + try testing.expect(Metadata.parse("i=4294967296") == null); + try testing.expect(Metadata.parse("i=99999999999") == null); + // Garbage after value. + try testing.expect(Metadata.parse("x=1z") == null); + // No whitespace tolerance, matching kitty. + try testing.expect(Metadata.parse("t=a: x=1") == null); + try testing.expect(Metadata.parse("t = a") == null); + // Truncated mid-construct, matching kitty's final-state check. + // Nothing state-changing may be parsed out of these: e.g. "t=r:x=" + // must not be treated as a drop conclusion. + try testing.expect(Metadata.parse("t") == null); + try testing.expect(Metadata.parse("t=") == null); + try testing.expect(Metadata.parse("x=") == null); + try testing.expect(Metadata.parse("t=r:x=") == null); + try testing.expect(Metadata.parse("x=1:t=") == null); +} + +test "Metadata: trailing separator accepted" { + const testing = std.testing; + + // Kitty's state machine accepts the metadata ending right after a + // value separator. + const meta = Metadata.parse("t=a:").?; + try testing.expectEqual(EventType.register, meta.type.?); +} + +test "Metadata: u32 boundary accepted" { + const testing = std.testing; + const meta = Metadata.parse("i=4294967295").?; + try testing.expectEqual(@as(u32, std.math.maxInt(u32)), meta.client_id); +} + +test "Request: classification" { + const testing = std.testing; + + // Conclude. + { + const r: Request = .init(Metadata.parse("t=r:o=2").?); + try testing.expectEqual(Operation.move, r.conclude); + } + // Conclude with unknown operation is none (canceled). + { + const r: Request = .init(Metadata.parse("t=r:o=9").?); + try testing.expectEqual(Operation.none, r.conclude); + } + // MIME data request. + { + const r: Request = .init(Metadata.parse("t=r:x=2").?); + try testing.expectEqual(@as(i32, 2), r.mime); + } + // URI file request. + { + const r: Request = .init(Metadata.parse("t=r:x=1:y=3").?); + try testing.expectEqual(@as(i32, 1), r.uri.mime_idx); + try testing.expectEqual(@as(i32, 3), r.uri.uri_idx); + } + // Directory handle request. + { + const r: Request = .init(Metadata.parse("t=r:Y=2:x=1").?); + try testing.expectEqual(@as(i32, 2), r.dir.handle); + try testing.expectEqual(@as(i32, 1), r.dir.entry); + } +} + +test "Chunking: reassembly reuses first chunk metadata" { + const testing = std.testing; + var chunking: Chunking = .{}; + + // First chunk starts reassembly. + const first = chunking.apply(Metadata.parse("t=m:o=1:m=1").?); + try testing.expect(chunking.active); + try testing.expectEqual(EventType.status, first.type.?); + try testing.expect(first.more); + + // Continuation metadata is ignored except for `more`. + const second = chunking.apply(Metadata.parse("t=q:o=2:m=1").?); + try testing.expect(chunking.active); + try testing.expectEqual(EventType.status, second.type.?); + try testing.expectEqual(@as(u32, 1), second.operation); + try testing.expect(second.more); + + // Final chunk ends reassembly. + const last = chunking.apply(Metadata.parse("t=q:m=0").?); + try testing.expect(!chunking.active); + try testing.expectEqual(EventType.status, last.type.?); + try testing.expect(!last.more); +} + +test "Chunking: unchunked commands pass through" { + const testing = std.testing; + var chunking: Chunking = .{}; + const meta = chunking.apply(Metadata.parse("t=q").?); + try testing.expect(!chunking.active); + try testing.expectEqual(EventType.query, meta.type.?); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/dnd_drop.zig b/vendor/libghostty-vt/src/terminal/kitty/dnd_drop.zig new file mode 100644 index 00000000..e3c7ee5c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/dnd_drop.zig @@ -0,0 +1,715 @@ +//! Kitty drag and drop protocol (OSC 72) state machine. + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +const assert = @import("../../quirks.zig").inlineAssert; +const osc = @import("../osc.zig"); +const command = @import("dnd_command.zig"); +const response = @import("dnd_response.zig"); + +const Metadata = command.Metadata; +const Operation = command.Operation; +const Operations = command.Operations; + +const log = std.log.scoped(.kitty_dnd); + +/// Maximum accumulated size of a client-sent MIME list (the accepted +/// list of a `t=m` status update). Matches kitty's MIME_LIST_SIZE_CAP. +pub const max_mime_list_bytes = 1024 * 1024; + +/// Process one OSC 72 command received from the client, writing any +/// responses to the writer. Returns the state change the embedder may +/// need to act on, if any. +pub fn handleCommand( + slot: *?*State, + alloc: Allocator, + writer: *std.Io.Writer, + v: osc.Command.KittyDndProtocol, +) (Allocator.Error || std.Io.Writer.Error)!?Event { + const raw = Metadata.parse(v.metadata) orelse { + log.debug("dropping malformed OSC 72 metadata", .{}); + return null; + }; + + // Chunk reassembly lives in the state, so before registration + // each command stands alone. The only legitimately chunked + // command before registration is t=a itself, which seeds the + // reassembly on its first chunk below. + const continuation = if (slot.*) |state| state.chunking.active else false; + const meta = if (slot.*) |state| state.chunking.apply(raw) else raw; + const payload = v.payload orelse ""; + const t = meta.type orelse return null; + + switch (t) { + .register => { + // x=1 declares the client's machine ID for remote drop + // support. We don't support remote drop yet, so accept and ignore. + if (meta.cell_x == 1) return null; + + // Setup our state if we haven't already + const state = slot.* orelse state: { + const state = try State.create(alloc); + slot.* = state; + _ = state.chunking.apply(raw); + break :state state; + }; + + // Update the client ID on every registration + state.drop.client_id = meta.client_id; + + return try state.register( + alloc, + payload, + continuation, + meta.more, + ); + }, + + .unregister => { + const state = slot.* orelse return null; + state.destroy(alloc); + slot.* = null; + return .registration; + }, + + .status => { + const state = slot.* orelse return null; + return try state.acceptStatus(alloc, meta, payload); + }, + + .request => return try dataRequest( + slot.*, + alloc, + writer, + meta, + v.terminator, + ), + + // Drag source control. Enabling (x=1, with an optional + // machine ID payload) and disabling (x=2) offers are + // accepted and ignored since the terminal never requests a + // drag start. Offering a MIME list (x=0) for a new drag is + // refused since drag-out is not implemented. + .offer => if (meta.cell_x == 0) try refuseDragOut( + writer, + meta, + v.terminator, + ), + + // Drag-out data and start commands. A conforming client + // never sends these because the terminal never requests a + // drag start, but refuse them properly if one does. + .present, .start_drag => try refuseDragOut( + writer, + meta, + v.terminator, + ), + + // Responses to drag-out requests the terminal never makes. + .drag_event, .drag_error, .remote_data => {}, + + .query => try response.encode( + writer, + "t=q", + meta.client_id, + "", + .plain, + v.terminator, + ), + + // Only ever sent by the terminal. Ignore. + .drop, .request_error => {}, + } + + return null; +} + +/// Handle a t=r data request or drop conclusion from the client. +/// Requests from an unregistered client (no state) get the same +/// errors kitty sends from its zeroed drop state. +fn dataRequest( + state: ?*State, + alloc: Allocator, + writer: *std.Io.Writer, + meta: Metadata, + terminator: osc.Terminator, +) (Allocator.Error || std.Io.Writer.Error)!?Event { + // Responses echo the registration's client ID, matching kitty. + const client_id = if (state) |s| s.drop.client_id else 0; + + switch (command.Request.init(meta)) { + .conclude => |op| { + // The client is done with the drop: free the held data and + // report the operation it performed. Kitty hands that to + // the still-open OS drag session; ours ended at drop time + // (see dnd.zig), so the embedder decides what to do with + // it. A conclusion with no drop in progress is a no-op. + const s = state orelse return null; + const dropped = s.drop.dropped; + s.resetDrop(alloc); + return if (dropped) Event.concluded(op) else null; + }, + + .mime => |idx| { + const keys: response.RequestKeys = .{ .x = idx }; + const items = (if (state) |s| s.drop.items else null) orelse { + try response.encodeError( + writer, + .drop, + keys, + client_id, + .ENOENT, + "no drop data available", + terminator, + ); + return null; + }; + if (idx < 1 or @as(usize, @intCast(idx)) > items.len) { + try response.encodeError( + writer, + .drop, + keys, + client_id, + .ENOENT, + "drop data request index out of bounds", + terminator, + ); + return null; + } + + var header_buf: [32]u8 = undefined; + const header = std.fmt.bufPrint( + &header_buf, + "t=r{f}", + .{keys}, + ) catch unreachable; + + // The data chunks followed by the empty end-of-data + // message, which is how the client detects completion. + // An empty item is just the end-of-data message alone; + // clients treat a duplicate as a second completion. + const item = items[@intCast(idx - 1)]; + if (item.data.len > 0) try response.encode( + writer, + header, + client_id, + item.data, + .base64, + terminator, + ); + try response.encode(writer, header, client_id, "", .base64, terminator); + return null; + }, + + // Remote drop transfers (URI file contents and directory + // handles). We never advertise remote support (no X=1 + // marker), so a conforming client never sends these. + .uri => |uri| try response.encodeError( + writer, + .drop, + .{ .x = uri.mime_idx, .y = uri.uri_idx }, + client_id, + .EINVAL, + "remote drop data is not supported", + terminator, + ), + .dir => |dir| try response.encodeError( + writer, + .drop, + .{ .x = dir.entry, .Y = dir.handle }, + client_id, + .EINVAL, + "remote drop data is not supported", + terminator, + ), + } + + return null; +} + +/// Refuse a drag-out command with an error, since ghostty does not +/// implement the terminal side of client-initiated drags yet. +fn refuseDragOut( + writer: *std.Io.Writer, + meta: Metadata, + terminator: osc.Terminator, +) std.Io.Writer.Error!void { + try response.encodeError( + writer, + .drag, + .{}, + meta.client_id, + .EPERM, + "drag out is not supported by this terminal", + terminator, + ); +} + +/// A protocol state change an embedder may need to act on, returned by +/// `handleCommand` and delivered through the stream handler's +/// `drag_and_drop` effect. This is a flat enum so it can cross a C API +/// unchanged; any details are read back from `Terminal.kitty_dnd`. +pub const Event = enum { + /// The client registered (t=a), re-registered, or unregistered + /// (t=A) to accept drops. An embedder may want to use this + /// to setup the proper mime types to accept (e.g. on macOS) + /// or not (unregistered). + registration, + + /// The client answered the drag currently over the terminal. + /// `State.clientAccepted` has the answer. Embedders can refresh the + /// OS drag feedback immediately rather than on the next move. + acceptance, + + /// The client concluded a drop, performing no operation (it + /// canceled), a copy, or a move. The held drop data has been freed. + concluded_none, + concluded_copy, + concluded_move, + + /// The conclusion event for a performed operation. + pub fn concluded(op: Operation) Event { + return switch (op) { + .none => .concluded_none, + .copy => .concluded_copy, + .move => .concluded_move, + }; + } +}; + +/// The per-terminal drop target state. +/// +/// The primary entrypoint is `handleCommand` which takes a `*?*State` +/// slot that it can heap allocate into when DnD activates and free when +/// it deactivates. +/// +/// The normal lifecycle: +/// +/// 1. The stream handler feeds every OSC 72 command received from the +/// client to `handleCommand`. The client registers (t=a), which +/// allocates the state into the slot and yields a `registration` +/// event so the embedder can register any declared MIME types +/// with the OS. Until then `handleCommand` only answers stateless +/// commands (queries, error responses). +/// 2. A native drag enters or moves over the terminal. When the slot +/// is non-null, the embedder calls `dragMove` with the pointer +/// position, the operations the drag source allows, and the MIME +/// types it can serve if dropped. This sends the client a t=m +/// move event; when the slot is null the embedder should handle +/// the drag as it would without the protocol. +/// 3. The client answers with its acceptance (t=m:o=N), recorded by +/// `handleCommand` which yields an `acceptance` event. The +/// embedder reads `clientAccepted` then and on subsequent moves +/// to give the OS drag session its feedback. +/// 4. The drag either leaves, and the embedder calls `dragLeave` to +/// send the t=m leave event, or drops: the embedder captures the +/// representations it advertised and calls `dragDrop`, which +/// copies and holds them and sends the client a t=M drop event. A +/// new drag entering before the client concludes discards the +/// held drop. +/// 5. The client requests data (t=r:x=N), which `handleCommand` +/// serves from the held copies, and then concludes the drop +/// (t=r:o=N), which frees them and yields a `concluded_*` event +/// naming the operation the client performed. +/// 6. The client unregisters (t=A) and `handleCommand` frees the +/// state, yielding a final `registration` event, or the terminal +/// is deinitialized and calls `destroy`. +/// +/// All calls must use the allocator the state was created with (the +/// terminal's) and require the same synchronization as any other +/// terminal mutation. +pub const State = struct { + /// Chunk reassembly for client commands. This is the only part of + /// the state cleared by a terminal reset (RIS), matching kitty. + chunking: command.Chunking = .{}, + + /// Drop target state for the registered client. + drop: DropTarget = .{}, + + pub const DropTarget = struct { + /// Multiplexer client ID from registration, echoed in every + /// drop-side message the terminal sends. + client_id: u32 = 0, + + /// The MIME list the client registered with (the t=a payload), + /// space-separated as received and accumulated across chunks. + /// Only needed by embedders that must register types with the + /// OS ahead of a drag; kitty frees it after doing so, we keep + /// it so the `registration` event can be acted on from here. + registered_mimes: std.ArrayListUnmanaged(u8) = .empty, + + /// True while the pointer of a native drag is over the terminal. + hovered: bool = false, + + /// True after the native drop until the client concludes it. + dropped: bool = false, + + /// The client's response to the current drag, null until the + /// client has responded. `none` means the client rejected it. + accepted: ?Operation = null, + + /// True while a chunked t=m acceptance is being accumulated. + accept_in_progress: bool = false, + + /// The client's accepted MIME list: space-separated while + /// accumulating, converted to NUL-separated (with a trailing + /// NUL) once complete, matching kitty's in-place conversion. + accepted_mimes: std.ArrayListUnmanaged(u8) = .empty, + + /// The MIME types of the current native drag, in the order + /// that data request indices refer to. + offered: ?Offered = null, + + /// The data captured at drop time, parallel to `offered`. + items: ?[]const Item = null, + }; + + /// One dropped representation: a MIME type and its data. + pub const Item = struct { + mime: []const u8, + data: []const u8, + }; + + /// The MIME list of the current drag plus the pre-joined move-event + /// payload ("mime1 mime2 " with a trailing space after every entry, + /// matching kitty) so per-move encoding is allocation-free. + const Offered = struct { + mimes: []const []const u8, + payload: []const u8, + + fn init(alloc: Allocator, mimes: []const []const u8) Allocator.Error!Offered { + const copies = try alloc.alloc([]const u8, mimes.len); + errdefer alloc.free(copies); + + var payload_len: usize = 0; + for (mimes) |m| payload_len += m.len + 1; + + const payload = try alloc.alloc(u8, payload_len); + errdefer alloc.free(payload); + + var offset: usize = 0; + for (mimes, copies) |m, *copy| { + @memcpy(payload[offset..][0..m.len], m); + payload[offset + m.len] = ' '; + copy.* = payload[offset..][0..m.len]; + offset += m.len + 1; + } + + return .{ .mimes = copies, .payload = payload }; + } + + fn deinit(self: *const Offered, alloc: Allocator) void { + alloc.free(self.mimes); + alloc.free(self.payload); + } + + fn eql(self: *const Offered, mimes: []const []const u8) bool { + if (self.mimes.len != mimes.len) return false; + for (self.mimes, mimes) |a, b| { + if (!std.mem.eql(u8, a, b)) return false; + } + return true; + } + }; + + /// The maximum number of dropped items. Embedders provide a small + /// curated set of representations (see dnd.zig), so this is a + /// generous bound that keeps the MIME list assembly on the stack. + pub const max_items = 16; + + /// Allocate a fresh state. Done by `handleCommand` on registration. + fn create(alloc: Allocator) Allocator.Error!*State { + const state = try alloc.create(State); + state.* = .{}; + return state; + } + + /// Free the state and everything it holds. + pub fn destroy(self: *State, alloc: Allocator) void { + self.deinit(alloc); + alloc.destroy(self); + } + + fn deinit(self: *State, alloc: Allocator) void { + self.freeDragData(alloc); + self.drop.accepted_mimes.deinit(alloc); + self.drop.registered_mimes.deinit(alloc); + } + + /// Iterate the MIME types the client registered with, in order. + /// Empty when the client declared none, which is the common case. + /// The list is only needed to register exotic types with the OS, + /// such as macOS pasteboard stuff. + pub fn registeredMimes(self: *const State) std.mem.TokenIterator(u8, .scalar) { + return std.mem.tokenizeScalar( + u8, + self.drop.registered_mimes.items, + ' ', + ); + } + + /// Record one chunk of a registration's MIME list. + /// + /// `continuation` is true for every chunk but the first of a chunked + /// registration. Returns the registration event once the list is complete. + fn register( + self: *State, + alloc: Allocator, + payload: []const u8, + continuation: bool, + more: bool, + ) Allocator.Error!?Event { + const list = &self.drop.registered_mimes; + if (!continuation) list.clearRetainingCapacity(); + + // Matching kitty, an over-cap chunk is dropped and does not + // complete the registration. + if (list.items.len + payload.len > max_mime_list_bytes) return null; + try list.appendSlice(alloc, payload); + + return if (more) null else .registration; + } + + /// The client's acceptance response for the drag currently over the + /// terminal, for OS drag feedback. Null when the client hasn't + /// responded yet (embedders should fall back to their default, + /// typically copy) or `none` when the client rejected the drag. + pub fn clientAccepted(self: *const State) ?Operation { + if (self.drop.accept_in_progress) return null; + return self.drop.accepted; + } + + /// Free the per-drag data (offered MIME list and held drop items). + fn freeDragData(self: *State, alloc: Allocator) void { + if (self.drop.offered) |*offered| { + offered.deinit(alloc); + self.drop.offered = null; + } + if (self.drop.items) |items| { + for (items) |item| { + alloc.free(item.mime); + alloc.free(item.data); + } + alloc.free(items); + self.drop.items = null; + } + } + + /// Clear the per-drag state while preserving the registration, + /// mirroring kitty's reset_drop. Called when a new drag enters and + /// when a drop concludes. + fn resetDrop(self: *State, alloc: Allocator) void { + self.freeDragData(alloc); + self.drop.accepted_mimes.clearAndFree(alloc); + self.drop.hovered = false; + self.drop.dropped = false; + self.drop.accepted = null; + self.drop.accept_in_progress = false; + } + + /// Handle a t=m acceptance status update from the client, mirroring + /// kitty's drop_set_status. + fn acceptStatus( + self: *State, + alloc: Allocator, + meta: Metadata, + payload: []const u8, + ) Allocator.Error!?Event { + const d = &self.drop; + if (!d.accept_in_progress) { + d.accepted_mimes.clearRetainingCapacity(); + d.accept_in_progress = true; + d.accepted = .fromProtocol(meta.operation); + } + + if (payload.len > 0) { + // Matching kitty, an over-cap list stops accumulating and + // never finalizes, leaving the acceptance unanswered. + if (d.accepted_mimes.items.len + payload.len > max_mime_list_bytes) return null; + try d.accepted_mimes.appendSlice(alloc, payload); + } + + if (meta.more) return null; + d.accept_in_progress = false; + if (d.accepted_mimes.items.len > 0) { + for (d.accepted_mimes.items) |*c| { + if (c.* == ' ') c.* = 0; + } + try d.accepted_mimes.append(alloc, 0); + } + return .acceptance; + } + + /// A native drag position report from the embedder. + pub const MoveEvent = struct { + /// Grid cell under the pointer, zero-based from the top-left. + cell_x: u32, + cell_y: u32, + + /// Pointer position in pixels relative to the top-left of the + /// terminal's content area. + pixel_x: i32, + pixel_y: i32, + + /// The operations the drag source allows. + operations: Operations, + }; + + /// Report a native drag moving over the terminal, sending a t=m + /// move event to the client. `mimes` is the list of MIME types the + /// terminal can provide for this drag, in the order data request + /// indices will refer to. + pub fn dragMove( + self: *State, + alloc: Allocator, + writer: *std.Io.Writer, + ev: MoveEvent, + mimes: []const []const u8, + ) (Allocator.Error || std.Io.Writer.Error)!void { + try self.moveEvent( + alloc, + writer, + ev, + mimes, + false, + ); + } + + /// Report a native drop onto the terminal. The items' data is + /// copied and held so the client's data requests can be served; it + /// is freed when the client concludes the drop, a new drag enters, + /// or the client unregisters. + /// + /// Sends a t=M drop event listing the items' MIME types. + pub fn dragDrop( + self: *State, + alloc: Allocator, + writer: *std.Io.Writer, + ev: MoveEvent, + items: []const Item, + ) (Allocator.Error || std.Io.Writer.Error)!void { + // Copy the items so they can be served after this call returns. + // Items beyond the cap are dropped so the held list always + // matches the advertised MIME list. + const accepted_items = items[0..@min(items.len, max_items)]; + const copies = try alloc.alloc(Item, accepted_items.len); + errdefer alloc.free(copies); + var copied: usize = 0; + errdefer for (copies[0..copied]) |item| { + alloc.free(item.mime); + alloc.free(item.data); + }; + for (accepted_items, copies) |item, *copy| { + const mime = try alloc.dupe(u8, item.mime); + errdefer alloc.free(mime); + const data = try alloc.dupe(u8, item.data); + copy.* = .{ .mime = mime, .data = data }; + copied += 1; + } + + // The move handling below resets per-drag state when this drop + // arrives without a preceding move, so the items are attached + // after it runs. Collect the MIME list first. + var mimes_buf: [max_items][]const u8 = undefined; + const mimes = mimes_buf[0..copies.len]; + for (mimes, copies) |*m, item| m.* = item.mime; + + try self.moveEvent( + alloc, + writer, + ev, + mimes, + true, + ); + + assert(self.drop.items == null); + self.drop.items = copies; + } + + /// Report the native drag leaving the terminal, sending the t=m + /// leave event (x=-1, y=-1). + /// + /// Ignored after a drop: some toolkits emit a leave notification + /// for the drop itself, and the held data must survive until the + /// client concludes. + pub fn dragLeave( + self: *State, + alloc: Allocator, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + if (self.drop.dropped) return; + const hovered = self.drop.hovered; + self.drop.hovered = false; + if (self.drop.offered) |*offered| { + offered.deinit(alloc); + self.drop.offered = null; + } + + // Only a client that saw the drag enter gets the leave event, + // matching kitty which notifies hovered windows only. + if (!hovered) return; + + try response.encode( + writer, + "t=m:x=-1:y=-1", + self.drop.client_id, + "", + .plain, + .st, + ); + } + + /// Shared implementation of move and drop events, mirroring kitty's + /// drop_move_on_child. + fn moveEvent( + self: *State, + alloc: Allocator, + writer: *std.Io.Writer, + ev: MoveEvent, + mimes: []const []const u8, + is_drop: bool, + ) (Allocator.Error || std.Io.Writer.Error)!void { + if (!self.drop.hovered) { + self.resetDrop(alloc); + self.drop.hovered = true; + } + if (is_drop) { + self.drop.dropped = true; + self.drop.hovered = false; + } + + // (Re)build the offered MIME list when it changed. + if (self.drop.offered == null or !self.drop.offered.?.eql(mimes)) { + if (self.drop.offered) |*offered| offered.deinit(alloc); + self.drop.offered = null; + self.drop.offered = try Offered.init(alloc, mimes); + } + + var header_buf: [96]u8 = undefined; + const header = std.fmt.bufPrint( + &header_buf, + "t={c}:x={d}:y={d}:X={d}:Y={d}:o={d}", + .{ + @as(u8, if (is_drop) 'M' else 'm'), + ev.cell_x, + ev.cell_y, + ev.pixel_x, + ev.pixel_y, + ev.operations.protocolValue(), + }, + ) catch unreachable; + + // The MIME list is sent with every move event, matching kitty + // (the spec suggests only the first, but kitty always sends it + // and clients depend on that). + try response.encode( + writer, + header, + self.drop.client_id, + self.drop.offered.?.payload, + .plain, + .st, + ); + } +}; diff --git a/vendor/libghostty-vt/src/terminal/kitty/dnd_response.zig b/vendor/libghostty-vt/src/terminal/kitty/dnd_response.zig new file mode 100644 index 00000000..1f7584f1 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/dnd_response.zig @@ -0,0 +1,248 @@ +const std = @import("std"); +const Terminator = @import("../osc.zig").Terminator; + +/// The maximum raw bytes per base64-encoded chunk, chosen by kitty so a +/// chunk is exactly 4096 base64 characters (the protocol's chunk limit). +pub const max_chunk_raw = 3072; + +/// The maximum bytes per plain-text (non-base64) chunk. +pub const max_chunk_plain = 4096; + +/// Error names used in protocol error payloads. The wire encoding is +/// the tag name itself. This matches kitty's get_errno_name vocabulary, +/// which extends the spec's list with EISDIR, ENOSPC, and OK. +pub const Errno = enum { + OK, + EPERM, + ENOENT, + EIO, + EINVAL, + EMFILE, + ENOMEM, + EFBIG, + EISDIR, + ENOSPC, + EUNKNOWN, +}; + +/// The payload encoding for a message. +pub const Encoding = enum { + /// Payload bytes are sent as-is (MIME lists, error strings). + plain, + + /// Payload bytes are base64-encoded (all binary data). + base64, +}; + +/// The `x`/`y`/`Y` keys of the data request currently being answered, +/// echoed in responses and errors so the client can match them up. Only +/// non-zero keys are written, matching kitty's drop_append_request_keys. +pub const RequestKeys = struct { + x: i32 = 0, + y: i32 = 0, + Y: i32 = 0, + + pub fn format(self: RequestKeys, writer: *std.Io.Writer) !void { + if (self.x != 0) try writer.print(":x={d}", .{self.x}); + if (self.y != 0) try writer.print(":y={d}", .{self.y}); + if (self.Y != 0) try writer.print(":Y={d}", .{self.Y}); + } +}; + +/// Encode a complete protocol message: one bare OSC when `data` is +/// empty, otherwise one complete OSC per chunk of `data`, each +/// repeating the header. The final chunk carries `m=0`, earlier +/// chunks `m=1`. +/// +/// `header` is the metadata without the OSC introducer, e.g. "t=q" or +/// "t=m:x=5:y=3". The client ID is appended as `:i=N` when non-zero. +pub fn encode( + writer: *std.Io.Writer, + header: []const u8, + client_id: u32, + data: []const u8, + encoding: Encoding, + terminator: Terminator, +) std.Io.Writer.Error!void { + // The client ID is part of the repeated header. + var id_buf: [16]u8 = undefined; + const id: []const u8 = if (client_id != 0) std.fmt.bufPrint( + &id_buf, + ":i={d}", + .{client_id}, + ) catch unreachable else ""; + + if (data.len == 0) { + try writer.print("\x1b]72;{s}{s}{s}", .{ + header, + id, + terminator.string(), + }); + return; + } + + const limit: usize = switch (encoding) { + .base64 => max_chunk_raw, + .plain => max_chunk_plain, + }; + + var offset: usize = 0; + while (offset < data.len) { + const chunk_len = @min(data.len - offset, limit); + const chunk = data[offset .. offset + chunk_len]; + offset += chunk_len; + const last: u8 = if (offset >= data.len) '0' else '1'; + + try writer.print("\x1b]72;{s}{s}:m={c};", .{ header, id, last }); + switch (encoding) { + .plain => try writer.writeAll(chunk), + .base64 => { + var b64_buf: [std.base64.standard.Encoder.calcSize(max_chunk_raw)]u8 = undefined; + try writer.writeAll(std.base64.standard.Encoder.encode( + &b64_buf, + chunk, + )); + }, + } + try writer.writeAll(terminator.string()); + } +} + +/// Encode an error response. `kind` selects the header: t=R for drop +/// data request errors, t=E for drag offer errors. The payload is +/// "NAME" or "NAME:description", sent plain (not base64). +pub fn encodeError( + writer: *std.Io.Writer, + kind: enum { drop, drag }, + keys: RequestKeys, + client_id: u32, + errno: Errno, + desc: []const u8, + terminator: Terminator, +) std.Io.Writer.Error!void { + var header_buf: [64]u8 = undefined; + const header = std.fmt.bufPrint(&header_buf, "t={c}{f}", .{ + @as(u8, switch (kind) { + .drop => 'R', + .drag => 'E', + }), + keys, + }) catch unreachable; + + // Description strings are short static messages; size the buffer + // for the longest error name plus a generous description. + var payload_buf: [256]u8 = undefined; + const payload = if (desc.len > 0) std.fmt.bufPrint( + &payload_buf, + "{t}:{s}", + .{ errno, desc }, + ) catch unreachable else @tagName(errno); + + try encode(writer, header, client_id, payload, .plain, terminator); +} + +test "encode: bare message" { + const testing = std.testing; + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, "t=q", 0, "", .plain, .st); + try testing.expectEqualStrings("\x1b]72;t=q\x1b\\", writer.buffered()); +} + +test "encode: bare message with client id" { + const testing = std.testing; + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, "t=q", 7, "", .plain, .st); + try testing.expectEqualStrings("\x1b]72;t=q:i=7\x1b\\", writer.buffered()); +} + +test "encode: plain payload single chunk" { + const testing = std.testing; + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, "t=m:x=1:y=2", 0, "text/plain ", .plain, .st); + try testing.expectEqualStrings( + "\x1b]72;t=m:x=1:y=2:m=0;text/plain \x1b\\", + writer.buffered(), + ); +} + +test "encode: base64 payload chunking" { + const testing = std.testing; + const alloc = testing.allocator; + + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + + // Exactly one byte more than a chunk to force two chunks. + const data = [_]u8{'A'} ** (max_chunk_raw + 1); + try encode(&aw.writer, "t=r:x=1", 3, &data, .base64, .st); + + const out = aw.written(); + + // First chunk: full header, m=1, 4096 base64 chars. + const prefix = "\x1b]72;t=r:x=1:i=3:m=1;"; + try testing.expect(std.mem.startsWith(u8, out, prefix)); + const first_end = std.mem.indexOf(u8, out, "\x1b\\").?; + try testing.expectEqual(@as(usize, prefix.len + 4096), first_end); + + // Second chunk: m=0 with the single remaining byte. + const rest = out[first_end + 2 ..]; + try testing.expect(std.mem.startsWith(u8, rest, "\x1b]72;t=r:x=1:i=3:m=0;")); + + // Decodes back to the original data. + var decoded: std.ArrayList(u8) = .empty; + defer decoded.deinit(alloc); + var it = std.mem.splitSequence(u8, out, "\x1b\\"); + while (it.next()) |osc| { + if (osc.len == 0) continue; + const payload_start = std.mem.indexOfScalar(u8, osc, ';').?; + const payload = osc[std.mem.indexOfScalarPos(u8, osc, payload_start + 1, ';').? + 1 ..]; + const n = try std.base64.standard.Decoder.calcSizeForSlice(payload); + const start = decoded.items.len; + try decoded.resize(alloc, start + n); + try std.base64.standard.Decoder.decode(decoded.items[start..], payload); + } + try testing.expectEqualSlices(u8, &data, decoded.items); +} + +test "encodeError: with and without description" { + const testing = std.testing; + var buf: [256]u8 = undefined; + + { + var writer: std.Io.Writer = .fixed(&buf); + try encodeError(&writer, .drop, .{ .x = 2 }, 0, .ENOENT, "drop data request index out of bounds", .st); + try testing.expectEqualStrings( + "\x1b]72;t=R:x=2:m=0;ENOENT:drop data request index out of bounds\x1b\\", + writer.buffered(), + ); + } + { + var writer: std.Io.Writer = .fixed(&buf); + try encodeError(&writer, .drag, .{}, 5, .EPERM, "", .st); + try testing.expectEqualStrings( + "\x1b]72;t=E:i=5:m=0;EPERM\x1b\\", + writer.buffered(), + ); + } +} + +test "RequestKeys: only non-zero keys written" { + const testing = std.testing; + var buf: [64]u8 = undefined; + + { + const s = try std.fmt.bufPrint(&buf, "{f}", .{RequestKeys{}}); + try testing.expectEqualStrings("", s); + } + { + const s = try std.fmt.bufPrint(&buf, "{f}", .{RequestKeys{ .x = 1, .y = 2, .Y = 3 }}); + try testing.expectEqualStrings(":x=1:y=2:Y=3", s); + } + { + const s = try std.fmt.bufPrint(&buf, "{f}", .{RequestKeys{ .Y = 4 }}); + try testing.expectEqualStrings(":Y=4", s); + } +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/dnd_test.zig b/vendor/libghostty-vt/src/terminal/kitty/dnd_test.zig new file mode 100644 index 00000000..c78ce00f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/dnd_test.zig @@ -0,0 +1,626 @@ +//! End-to-end tests for the OSC 72 protocol state machine, validating +//! wire behavior against kitty's implementation (using kitty_tests/dnd.py as +//! an oracle for the expected bytes). +//! +//! It isn't normal for us to have dedicated test files but in this case +//! the dnd protocol is complicated enough that I wanted full e2e covering +//! the full machine. + +const std = @import("std"); +const testing = std.testing; + +const osc = @import("../osc.zig"); +const dnd = @import("dnd.zig"); + +/// A test harness holding the lazily allocated protocol state and an +/// output collector. +const Harness = struct { + state: ?*dnd.State = null, + output: std.Io.Writer.Allocating, + + fn init() Harness { + return .{ .output = .init(testing.allocator) }; + } + + fn deinit(self: *Harness) void { + if (self.state) |state| state.destroy(testing.allocator); + self.output.deinit(); + } + + /// The registered state; asserts a client has registered. + fn registered(self: *Harness) *dnd.State { + return self.state.?; + } + + /// Feed one client command, as it would arrive from the OSC parser, + /// returning the event the stream handler would pass to its effect. + fn command(self: *Harness, metadata: []const u8, payload: ?[]const u8) !?dnd.Event { + return try dnd.handleCommand(&self.state, testing.allocator, &self.output.writer, .{ + .metadata = metadata, + .payload = payload, + .terminator = .st, + }); + } + + /// Consume and return the collected output. + fn consume(self: *Harness) []const u8 { + const written = self.output.written(); + return written; + } + + fn clear(self: *Harness) void { + self.output.clearRetainingCapacity(); + } + + fn expectOutput(self: *Harness, expected: []const u8) !void { + try testing.expectEqualStrings(expected, self.output.written()); + self.clear(); + } +}; + +test "dnd: query response" { + var h: Harness = .init(); + defer h.deinit(); + + // Works without any registration, matching kitty, and allocates + // nothing. + _ = try h.command("t=q", null); + try h.expectOutput("\x1b]72;t=q\x1b\\"); + try testing.expect(h.state == null); +} + +test "dnd: query response echoes client id" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=q:i=31", null); + try h.expectOutput("\x1b]72;t=q:i=31\x1b\\"); +} + +test "dnd: register and unregister" { + var h: Harness = .init(); + defer h.deinit(); + + try testing.expect(h.state == null); + + // Registration allocates the state and reports it, with the + // declared MIME list readable from the state. + try testing.expect((try h.command("t=a", "text/plain text/uri-list")).? == .registration); + try h.expectOutput(""); + { + var it = h.registered().registeredMimes(); + try testing.expectEqualStrings("text/plain", it.next().?); + try testing.expectEqualStrings("text/uri-list", it.next().?); + try testing.expect(it.next() == null); + } + + // Machine ID declaration is accepted and ignored. + try testing.expect((try h.command("t=a:x=1", "1:deadbeef")) == null); + try h.expectOutput(""); + try testing.expect(h.state != null); + + // Re-registration replaces the list. + try testing.expect((try h.command("t=a", "image/png")).? == .registration); + { + var it = h.registered().registeredMimes(); + try testing.expectEqualStrings("image/png", it.next().?); + try testing.expect(it.next() == null); + } + + // Registering without a list is the common case. + try testing.expect((try h.command("t=a", null)).? == .registration); + { + var it = h.registered().registeredMimes(); + try testing.expect(it.next() == null); + } + + // Unregistration frees it and reports the change. + try testing.expect((try h.command("t=A", null)).? == .registration); + try h.expectOutput(""); + try testing.expect(h.state == null); + + // Unregistering again changes nothing. + try testing.expect((try h.command("t=A", null)) == null); + try h.expectOutput(""); + try testing.expect(h.state == null); +} + +test "dnd: no state before registration" { + var h: Harness = .init(); + defer h.deinit(); + + // State-dependent commands from an unregistered client allocate + // nothing; a data request gets the error kitty sends from its + // zeroed state. + _ = try h.command("t=m:o=1", "text/plain"); + _ = try h.command("t=r", null); + try h.expectOutput(""); + _ = try h.command("t=r:x=1", null); + try h.expectOutput( + "\x1b]72;t=R:x=1:m=0;ENOENT:no drop data available\x1b\\", + ); + try testing.expect(h.state == null); +} + +test "dnd: move event carries position, operations, and mime list" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", "text/plain"); + + try h.registered().dragMove(testing.allocator, &h.output.writer, .{ + .cell_x = 5, + .cell_y = 3, + .pixel_x = 100, + .pixel_y = 60, + .operations = .{ .copy = true }, + }, &.{ "text/plain", "text/uri-list" }); + + // Note the trailing space after every MIME entry, matching kitty. + try h.expectOutput( + "\x1b]72;t=m:x=5:y=3:X=100:Y=60:o=1:m=0;text/plain text/uri-list \x1b\\", + ); +} + +test "dnd: move event echoes registration client id" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a:i=7", ""); + try h.registered().dragMove(testing.allocator, &h.output.writer, .{ + .cell_x = 1, + .cell_y = 2, + .pixel_x = 8, + .pixel_y = 16, + .operations = .{ .copy = true, .move = true }, + }, &.{"text/plain"}); + try h.expectOutput("\x1b]72;t=m:x=1:y=2:X=8:Y=16:o=3:i=7:m=0;text/plain \x1b\\"); +} + +test "dnd: re-registration updates client id in place" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a:i=7", ""); + const state = h.registered(); + _ = try h.command("t=a:i=9", ""); + // Same allocation, new client ID. + try testing.expect(h.state.? == state); + try testing.expectEqual(@as(u32, 9), state.drop.client_id); +} + +test "dnd: mime list sent on every move" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + const ev: dnd.MoveEvent = .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }; + try h.registered().dragMove(testing.allocator, &h.output.writer, ev, &.{"text/plain"}); + h.clear(); + + // Kitty resends the list even when unchanged; clients depend on it. + try h.registered().dragMove(testing.allocator, &h.output.writer, ev, &.{"text/plain"}); + try h.expectOutput("\x1b]72;t=m:x=0:y=0:X=0:Y=0:o=1:m=0;text/plain \x1b\\"); +} + +test "dnd: leave event" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + try h.registered().dragMove(testing.allocator, &h.output.writer, .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }, &.{"text/plain"}); + h.clear(); + + try h.registered().dragLeave(testing.allocator, &h.output.writer); + try h.expectOutput("\x1b]72;t=m:x=-1:y=-1\x1b\\"); +} + +test "dnd: client acceptance recorded" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + try testing.expect(h.registered().clientAccepted() == null); + + try testing.expect((try h.command("t=m:o=1", "text/plain")).? == .acceptance); + try h.expectOutput(""); + try testing.expectEqual(dnd.Operation.copy, h.registered().clientAccepted().?); + + // Rejection. + try testing.expect((try h.command("t=m:o=0", "")).? == .acceptance); + try testing.expectEqual(dnd.Operation.none, h.registered().clientAccepted().?); +} + +test "dnd: chunked client acceptance" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + + // Chunked accept: continuation metadata is ignored, the acceptance + // is pending until the final chunk. + try testing.expect((try h.command("t=m:o=2:m=1", "text/pl")) == null); + try testing.expect(h.registered().clientAccepted() == null); + try testing.expect((try h.command("t=m:m=1", "ain text")) == null); + try testing.expect((try h.command("t=m:m=0", "/html")).? == .acceptance); + try testing.expectEqual(dnd.Operation.move, h.registered().clientAccepted().?); + + // The accumulated list was converted to NUL-separated entries. + try testing.expectEqualSlices( + u8, + "text/plain\x00text/html\x00", + h.registered().drop.accepted_mimes.items, + ); +} + +test "dnd: drop and data serving round trip" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", "text/plain text/uri-list"); + + const ev: dnd.MoveEvent = .{ + .cell_x = 4, + .cell_y = 2, + .pixel_x = 40, + .pixel_y = 20, + .operations = .{ .copy = true }, + }; + try h.registered().dragDrop(testing.allocator, &h.output.writer, ev, &.{ + .{ .mime = "text/uri-list", .data = "file:///tmp/a.txt\r\n" }, + .{ .mime = "text/plain", .data = "hello" }, + }); + try h.expectOutput( + "\x1b]72;t=M:x=4:y=2:X=40:Y=20:o=1:m=0;text/uri-list text/plain \x1b\\", + ); + + // Request the second MIME's data: base64 chunk plus the empty + // end-of-data message. + _ = try h.command("t=r:x=2", null); + try h.expectOutput( + "\x1b]72;t=r:x=2:m=0;aGVsbG8=\x1b\\" ++ "\x1b]72;t=r:x=2\x1b\\", + ); + + // Out-of-bounds request. + _ = try h.command("t=r:x=3", null); + try h.expectOutput( + "\x1b]72;t=R:x=3:m=0;ENOENT:drop data request index out of bounds\x1b\\", + ); + + // Conclude: the performed operation is reported, held data is + // freed, and further requests fail. + try testing.expectEqual(dnd.Event.concluded_copy, (try h.command("t=r:o=1", null)).?); + try h.expectOutput(""); + try testing.expect((try h.command("t=r:o=1", null)) == null); + _ = try h.command("t=r:x=1", null); + try h.expectOutput( + "\x1b]72;t=R:x=1:m=0;ENOENT:no drop data available\x1b\\", + ); +} + +test "dnd: empty item served as a single end-of-data message" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + try h.registered().dragDrop(testing.allocator, &h.output.writer, .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }, &.{.{ .mime = "text/plain", .data = "" }}); + h.clear(); + + // Kitty's oracle (test_empty_data) asserts exactly one message: + // the empty response is itself the end-of-data signal, and a + // duplicate would be a second completion to the client. + _ = try h.command("t=r:x=1", null); + try h.expectOutput("\x1b]72;t=r:x=1\x1b\\"); +} + +test "dnd: leave without hover sends nothing" { + var h: Harness = .init(); + defer h.deinit(); + + // Client registered but no move was ever forwarded (e.g. it + // registered mid-drag): kitty only notifies hovered windows. + _ = try h.command("t=a", ""); + try h.registered().dragLeave(testing.allocator, &h.output.writer); + try h.expectOutput(""); +} + +test "dnd: data request with no drop" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + _ = try h.command("t=r:x=1", null); + try h.expectOutput( + "\x1b]72;t=R:x=1:m=0;ENOENT:no drop data available\x1b\\", + ); +} + +test "dnd: leave after drop is ignored" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + try h.registered().dragDrop(testing.allocator, &h.output.writer, .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }, &.{.{ .mime = "text/plain", .data = "x" }}); + h.clear(); + + // Some toolkits emit a leave for the drop itself; the held data + // must survive so the client can still fetch it. + try h.registered().dragLeave(testing.allocator, &h.output.writer); + try h.expectOutput(""); + + _ = try h.command("t=r:x=1", null); + try h.expectOutput( + "\x1b]72;t=r:x=1:m=0;eA==\x1b\\" ++ "\x1b]72;t=r:x=1\x1b\\", + ); +} + +test "dnd: new drag resets held drop data" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + const ev: dnd.MoveEvent = .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }; + try h.registered().dragDrop(testing.allocator, &h.output.writer, ev, &.{ + .{ .mime = "text/plain", .data = "old" }, + }); + h.clear(); + + // A new drag entering resets the per-drag state including the held + // items from the unconcluded previous drop. + try h.registered().dragMove(testing.allocator, &h.output.writer, ev, &.{"text/plain"}); + h.clear(); + _ = try h.command("t=r:x=1", null); + try h.expectOutput( + "\x1b]72;t=R:x=1:m=0;ENOENT:no drop data available\x1b\\", + ); +} + +test "dnd: remote transfer requests refused" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + + // URI file content request. + _ = try h.command("t=r:x=1:y=2", null); + try h.expectOutput( + "\x1b]72;t=R:x=1:y=2:m=0;EINVAL:remote drop data is not supported\x1b\\", + ); + + // Directory handle request. + _ = try h.command("t=r:Y=2:x=1", null); + try h.expectOutput( + "\x1b]72;t=R:x=1:Y=2:m=0;EINVAL:remote drop data is not supported\x1b\\", + ); +} + +test "dnd: drag out refused" { + var h: Harness = .init(); + defer h.deinit(); + + // Enabling and disabling offers is accepted silently and allocates + // nothing. + _ = try h.command("t=o:x=1", null); + _ = try h.command("t=o:x=2", null); + try h.expectOutput(""); + try testing.expect(h.state == null); + + // Offering a drag is refused. + _ = try h.command("t=o:x=1", null); + _ = try h.command("t=o:o=3", "text/plain"); + try h.expectOutput( + "\x1b]72;t=E:m=0;EPERM:drag out is not supported by this terminal\x1b\\", + ); + + // Starting a drag is refused, echoing the command's client id. + _ = try h.command("t=P:x=-1:i=9", null); + try h.expectOutput( + "\x1b]72;t=E:i=9:m=0;EPERM:drag out is not supported by this terminal\x1b\\", + ); + try testing.expect(h.state == null); +} + +test "dnd: unregister frees held drop data" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + try h.registered().dragDrop(testing.allocator, &h.output.writer, .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }, &.{.{ .mime = "text/plain", .data = "x" }}); + h.clear(); + + // The testing allocator would report the held data as leaked if + // unregistration didn't free the whole state. + _ = try h.command("t=A", null); + try testing.expect(h.state == null); +} + +test "dnd: chunked registration reuses first chunk metadata" { + var h: Harness = .init(); + defer h.deinit(); + + // Registration split over two chunks: the first chunk allocates + // the state and seeds chunk reassembly, so the continuation (which + // carries a different type) is still treated as the registration. + try testing.expect((try h.command("t=a:i=4:m=1", "text/pla")) == null); + try testing.expect(h.state != null); + try testing.expect((try h.command("t=q:m=0", "in")).? == .registration); + try h.expectOutput(""); + try testing.expectEqual(@as(u32, 4), h.registered().drop.client_id); + { + var it = h.registered().registeredMimes(); + try testing.expectEqualStrings("text/plain", it.next().?); + } + + // A query after the chunked command completes works again. + _ = try h.command("t=q", null); + try h.expectOutput("\x1b]72;t=q\x1b\\"); +} + +test "dnd: malformed metadata ignored" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a:zz=1", ""); + try h.expectOutput(""); + try testing.expect(h.state == null); + + // Command with no type is ignored, matching kitty (the spec's + // default of t=a is not honored by the reference implementation). + _ = try h.command("x=1", ""); + try h.expectOutput(""); + try testing.expect(h.state == null); +} + +test "dnd: bel terminator echoed in responses" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try dnd.handleCommand(&h.state, testing.allocator, &h.output.writer, .{ + .metadata = "t=q", + .payload = null, + .terminator = .bel, + }); + try h.expectOutput("\x1b]72;t=q\x07"); +} + +test "dnd: kitten 0.47 conversation replay" { + // This replays a conversation recorded from the reference client + // (`kitten dnd --drop-anywhere=copy --drop text/plain:out.txt`, + // kitten 0.47.0) driven over a pty by a harness that sent exactly + // the bytes this engine produces. The kitten accepted the events, + // wrote the dropped payload to disk intact, and concluded; its + // client bytes are frozen here as an interop regression test. + var h: Harness = .init(); + defer h.deinit(); + + // Startup: register with MIME list and machine ID, then the test + // harness reset (unregister both directions, re-register). + _ = try h.command("t=a:m=0", "text/uri-list text/plain"); + _ = try h.command( + "t=a:x=1:m=0", + "1:5cff8247c477900a8727e2281fe890252f8848f87c224dd8dd7fb6303e94ddbd", + ); + _ = try h.command("t=A", null); + try testing.expect(h.state == null); + _ = try h.command("t=o:x=2", null); + _ = try h.command("t=a:m=0", "text/uri-list text/plain"); + _ = try h.command( + "t=a:x=1:m=0", + "1:5cff8247c477900a8727e2281fe890252f8848f87c224dd8dd7fb6303e94ddbd", + ); + try h.expectOutput(""); + try testing.expect(h.state != null); + + // Native drag moves over the terminal and drops. + const ev: dnd.MoveEvent = .{ + .cell_x = 2, + .cell_y = 1, + .pixel_x = 20, + .pixel_y = 18, + .operations = .{ .copy = true }, + }; + try h.registered().dragMove(testing.allocator, &h.output.writer, ev, &.{"text/plain"}); + try h.expectOutput("\x1b]72;t=m:x=2:y=1:X=20:Y=18:o=1:m=0;text/plain \x1b\\"); + + // The kitten accepts as a copy of text/plain. + _ = try h.command("t=m:o=1:m=0", "text/plain"); + try h.expectOutput(""); + try testing.expectEqual(dnd.Operation.copy, h.registered().clientAccepted().?); + + try h.registered().dragDrop(testing.allocator, &h.output.writer, ev, &.{ + .{ .mime = "text/plain", .data = "hello from ghostty\n" }, + }); + try h.expectOutput("\x1b]72;t=M:x=2:y=1:X=20:Y=18:o=1:m=0;text/plain \x1b\\"); + + // The kitten requests the data and concludes with a copy. + _ = try h.command("t=r:x=1", null); + try h.expectOutput( + "\x1b]72;t=r:x=1:m=0;aGVsbG8gZnJvbSBnaG9zdHR5Cg==\x1b\\" ++ + "\x1b]72;t=r:x=1\x1b\\", + ); + _ = try h.command("t=r:o=1", null); + try h.expectOutput(""); + try testing.expect(h.registered().drop.items == null); +} + +test "dnd: large data served in chunks" { + var h: Harness = .init(); + defer h.deinit(); + + _ = try h.command("t=a", ""); + + // 3073 bytes: one full chunk plus one byte. + const data = [_]u8{'Z'} ** 3073; + try h.registered().dragDrop(testing.allocator, &h.output.writer, .{ + .cell_x = 0, + .cell_y = 0, + .pixel_x = 0, + .pixel_y = 0, + .operations = .{ .copy = true }, + }, &.{.{ .mime = "application/octet-stream", .data = &data }}); + h.clear(); + + _ = try h.command("t=r:x=1", null); + const out = h.consume(); + + // First chunk is m=1 with 4096 base64 chars, second is m=0, and + // the final message is the bare end-of-data marker. + try testing.expect(std.mem.startsWith(u8, out, "\x1b]72;t=r:x=1:m=1;")); + try testing.expect(std.mem.indexOf(u8, out, "\x1b]72;t=r:x=1:m=0;") != null); + try testing.expect(std.mem.endsWith(u8, out, "\x1b]72;t=r:x=1\x1b\\")); + h.clear(); +} + +test "dnd: over-cap registration list never completes" { + var h: Harness = .init(); + defer h.deinit(); + + // Matching kitty, a chunk that would exceed the cap is dropped and + // the registration is not reported, though the client stays + // registered (the state exists). + const big = try testing.allocator.alloc(u8, dnd.max_mime_list_bytes + 1); + defer testing.allocator.free(big); + @memset(big, 'a'); + try testing.expect((try h.command("t=a", big)) == null); + try testing.expect(h.state != null); + { + var it = h.registered().registeredMimes(); + try testing.expect(it.next() == null); + } +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics.zig index 1f639fab..ef45ee8d 100644 --- a/vendor/libghostty-vt/src/terminal/kitty/graphics.zig +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics.zig @@ -3,11 +3,6 @@ //! Documentation: //! https://sw.kovidgoyal.net/kitty/graphics-protocol //! -//! Unimplemented features that are still todo: -//! - shared memory transmit -//! - virtual placement w/ unicode -//! - animation -//! //! Performance: //! The performance of this particular subsystem of Ghostty is not great. //! We can avoid a lot more allocations, we can replace some C code (which @@ -21,7 +16,10 @@ const command = @import("graphics_command.zig"); const exec = @import("graphics_exec.zig"); const image = @import("graphics_image.zig"); const storage = @import("graphics_storage.zig"); +pub const animation = @import("graphics_animation.zig"); +pub const pixel = @import("graphics_pixel.zig"); pub const unicode = @import("graphics_unicode.zig"); +pub const Animation = animation.Animation; pub const Command = command.Command; pub const CommandParser = command.Parser; pub const Image = image.Image; diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_animation.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_animation.zig new file mode 100644 index 00000000..0822a451 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_animation.zig @@ -0,0 +1,149 @@ +//! Kitty graphics protocol animation support. +//! +//! https://sw.kovidgoyal.net/kitty/graphics-protocol/#animation +//! +//! An animation is a set of frames attached to an existing image. +//! Frame 1 (the "root frame") is the image's own base data. Frames +//! 2..N are stored here. Unlike Kitty, which stores frames as delta +//! rectangles in a disk cache and composes them lazily, we compose +//! every frame eagerly into a full image-sized RGBA buffer at load +//! time. This trades some memory for a much simpler model: a frame is +//! always ready to display and there are no reference chains to +//! maintain, coalesce, or garbage collect. Frame storage is bounded +//! by the same byte limit as image storage. +//! +//! To keep composition to a single pixel format, an image is +//! converted to RGBA the first time an animation command composes +//! into it, and all transmitted frame data is converted to RGBA +//! before composition. Blending an opaque (alpha=255) source pixel +//! degenerates to a copy, so this loses no information relative to +//! Kitty's separate RGB/RGBA paths. The pixel-level primitives +//! (conversion, fill, rectangle composition) live in +//! graphics_pixel.zig. + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +/// The gap assigned to a newly created frame when the command doesn't +/// specify one (z omitted or z=0). Taken from Kitty (DEFAULT_GAP). +pub const default_gap_ms: u32 = 40; + +/// Animation state for a single image. Heap-allocated and owned by +/// the Image. This is created lazily by the first animation command that +/// needs it. +pub const Animation = struct { + /// The frames following the root frame: `frames.items[i]` is + /// protocol frame number `i + 2`. The root frame (frame 1) is the + /// image's base data and is not stored here. + frames: std.ArrayListUnmanaged(Frame) = .empty, + + /// The gap of the root frame in milliseconds. Zero means gapless: + /// the frame is skipped during playback. Kitty creates the root + /// frame with a zero gap; the client gives it one with a=a,r=1,z=N. + root_gap_ms: u32 = 0, + + /// The zero-based index of the frame currently displayed: 0 is + /// the root frame, i >= 1 is frames.items[i - 1]. + current_index: u32 = 0, + + /// Playback state. Every image starts stopped (client-driven). + state: State = .stopped, + + /// Maximum number of loops to play (0 = infinite). Set from the + /// a=a v key as v-1, per the protocol's off-by-one encoding. + max_loops: u32 = 0, + + /// Number of completed loops since playback started. + current_loop: u32 = 0, + + /// Timestamp in milliseconds (on the ticker's clock, see + /// ImageStorage.animationTick) when the current frame was shown. + /// Null means "not yet shown"; the next tick stamps it. + frame_shown_at_ms: ?u64 = null, + + pub const State = enum { + /// Not advancing; frames change only via a=a c=N (client-driven). + stopped, + /// Advancing, but playback parks on the last frame waiting + /// for more frames instead of looping (a=a s=2). + loading, + /// Advancing and looping (a=a s=3). + running, + }; + + pub const Frame = struct { + /// Fully composed pixel data, always image width * height * 4 + /// bytes of RGBA. + data: []u8, + + /// Milliseconds this frame is displayed before advancing. + /// Zero means gapless: skipped during playback. + gap_ms: u32, + }; + + pub fn deinit(self: *Animation, alloc: Allocator) void { + for (self.frames.items) |frame| alloc.free(frame.data); + self.frames.deinit(alloc); + } + + /// The total number of frames including the root frame. + pub fn frameCount(self: *const Animation) u32 { + return @intCast(self.frames.items.len + 1); + } + + /// The gap of the frame at the given zero-based index. + pub fn gapAt(self: *const Animation, index: u32) u32 { + if (index == 0) return self.root_gap_ms; + return self.frames.items[index - 1].gap_ms; + } + + /// Set the gap of the frame at the given zero-based index. + pub fn setGapAt(self: *Animation, index: u32, gap_ms: u32) void { + if (index == 0) { + self.root_gap_ms = gap_ms; + } else { + self.frames.items[index - 1].gap_ms = gap_ms; + } + } + + /// The sum of all frame gaps. An animation with a zero duration + /// (every frame gapless) never advances; this doubles as the + /// guard that keeps the gapless-skip loop in animationTick from + /// spinning forever, exactly like Kitty's animation_duration. + pub fn durationMs(self: *const Animation) u64 { + var total: u64 = self.root_gap_ms; + for (self.frames.items) |frame| total += frame.gap_ms; + return total; + } + + /// Bytes of frame data held by this animation, counted against + /// the image storage limit. + pub fn frameBytes(self: *const Animation) usize { + var total: usize = 0; + for (self.frames.items) |frame| total += frame.data.len; + return total; + } +}; + +test "animation gap helpers" { + const testing = std.testing; + const alloc = testing.allocator; + + var anim: Animation = .{}; + defer anim.deinit(alloc); + try anim.frames.append(alloc, .{ + .data = try alloc.alloc(u8, 4), + .gap_ms = 100, + }); + + try testing.expectEqual(@as(u32, 2), anim.frameCount()); + try testing.expectEqual(@as(u32, 0), anim.gapAt(0)); + try testing.expectEqual(@as(u32, 100), anim.gapAt(1)); + try testing.expectEqual(@as(u64, 100), anim.durationMs()); + try testing.expectEqual(@as(usize, 4), anim.frameBytes()); + + anim.setGapAt(0, 40); + anim.setGapAt(1, 60); + try testing.expectEqual(@as(u64, 100), anim.durationMs()); + try testing.expectEqual(@as(u32, 40), anim.root_gap_ms); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig index bc0ffb5b..e57ad174 100644 --- a/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig @@ -1,25 +1,61 @@ const std = @import("std"); const assert = @import("../../quirks.zig").inlineAssert; const Allocator = std.mem.Allocator; -const ArenaAllocator = std.heap.ArenaAllocator; const simd = @import("../../simd/main.zig"); const lib = @import("../lib.zig"); const log = std.log.scoped(.kitty_gfx); /// The key-value pairs for the control information for a command. The -/// keys are always single characters and the values are either single -/// characters or 32-bit unsigned integers. +/// recognized keys are always single ASCII letters and the values are either +/// single characters or 32-bit unsigned integers. Unknown non-letter keys are +/// ignored, matching how unknown letter keys are ignored when building a +/// command. /// -/// For the value of this: if the value is a single printable ASCII character -/// it is the ASCII code. Otherwise, it is parsed as a 32-bit unsigned integer. -const KV = std.AutoHashMapUnmanaged(u8, u32); +/// This is deliberately a dense value table plus a presence bitmap. There are +/// only 52 possible keys(technically KIP has fever than 52 possible .. at the moment of writing), so a lookup is one machine-word bit test followed by +/// an indexed load. The values are undefined until their presence bit is set. +/// +/// Other alternatives were considered and should probably be revisited in the +/// future. Some of them were: +/// A `[52]?u32` table is 416 bytes versus 216 bytes for this layout, and +/// its larger copies erased the smaller lookup code. +/// `std.EnumMap` added optional-return lowering, +/// `std.StaticBitSet(52)` kept the same size but generated larger code +/// for the packed mask. Passing the table by pointer removed the copies +/// but did not improve end-to-end throughput. Keep this representation +/// unless a new benchmark shows an improvement in the zig compilers codegen. +/// +/// For the value itself: if it is a single printable ASCII character it is the +/// ASCII code. Otherwise, it is parsed as a 32-bit unsigned integer. +const KV = struct { + values: [52]u32 = undefined, + present: u64 = 0, + + fn index(key: u8) ?u6 { + return switch (key) { + 'a'...'z' => @intCast(key - 'a'), + 'A'...'Z' => @intCast(26 + key - 'A'), + else => null, + }; + } + + fn get(self: *const KV, key: u8) ?u32 { + const idx = index(key) orelse return null; + if (self.present & (@as(u64, 1) << idx) == 0) return null; + return self.values[idx]; + } + + fn put(self: *KV, key: u8, value: u32) void { + const idx = index(key) orelse return; + self.values[idx] = value; + self.present |= @as(u64, 1) << idx; + } +}; /// Command parser parses the Kitty graphics protocol escape sequence. pub const Parser = struct { - /// The memory used by the parser is stored in an arena because it is - /// all freed at the end of the command. - arena: ArenaAllocator, + alloc: Allocator, /// This is the list of KV pairs that we're building up. kv: KV, @@ -60,10 +96,8 @@ pub const Parser = struct { /// Initialize the parser. The allocator given will be used for both /// temporary data and long-lived values such as the final image blob. pub fn init(alloc: Allocator, max_bytes: usize) Parser { - var arena = ArenaAllocator.init(alloc); - errdefer arena.deinit(); var result: Parser = .{ - .arena = arena, + .alloc = alloc, .data = .empty, .kv = .{}, .kv_temp_len = 0, @@ -82,9 +116,7 @@ pub const Parser = struct { } pub fn deinit(self: *Parser) void { - // We don't free the hash map because its in the arena - self.data.deinit(self.arena.child_allocator); - self.arena.deinit(); + self.data.deinit(self.alloc); } /// Parse a complete command string. @@ -144,7 +176,7 @@ pub const Parser = struct { .data => { if (self.data.items.len >= self.max_bytes) return error.OutOfMemory; - try self.data.append(self.arena.child_allocator, c); + try self.data.append(self.alloc, c); }, } } @@ -160,7 +192,7 @@ pub const Parser = struct { if (self.data.items.len + rem.len > self.max_bytes) { return error.OutOfMemory; } - try self.data.appendSlice(self.arena.child_allocator, rem); + try self.data.appendSlice(self.alloc, rem); return; } @@ -205,18 +237,18 @@ pub const Parser = struct { 'p' => .{ .display = try .parse(self.kv) }, 'd' => .{ .delete = try .parse(self.kv) }, 'f' => .{ .transmit_animation_frame = try .parse(self.kv) }, - 'a' => .{ .control_animation = try .parse(self.kv) }, - 'c' => .{ .compose_animation = try .parse(self.kv) }, + 'a' => .{ .control_animation = .parse(self.kv) }, + 'c' => .{ .compose_animation = .parse(self.kv) }, else => return error.InvalidFormat, }; - // Determine our quiet value + // Determine our quiet value. The spec specifies 0 and 1 but Kitty + // allows anything greater than 1 to suppress. const quiet: Command.Quiet = if (self.kv.get('q')) |v| quiet: { break :quiet switch (v) { 0 => .no, 1 => .ok, - 2 => .failures, - else => return error.InvalidFormat, + else => .failures, }; } else .no; @@ -269,8 +301,6 @@ pub const Parser = struct { } fn finishValue(self: *Parser, next_state: State) !void { - const alloc = self.arena.allocator(); - // We can move states right away, we don't use it. self.state = next_state; @@ -278,7 +308,7 @@ pub const Parser = struct { if (self.kv_temp_len == 1) { const c = self.kv_temp[0]; if (c < '0' or c > '9') { - try self.kv.put(alloc, self.kv_current, @intCast(c)); + self.kv.put(self.kv_current, @intCast(c)); self.kv_temp_len = 0; return; } @@ -291,7 +321,7 @@ pub const Parser = struct { 'z', 'H', 'V' => @bitCast(try std.fmt.parseInt(i32, self.kv_temp[0..self.kv_temp_len], 10)), else => try std.fmt.parseInt(u32, self.kv_temp[0..self.kv_temp_len], 10), }; - try self.kv.put(alloc, self.kv_current, v); + self.kv.put(self.kv_current, v); // Clear our temp buffer self.kv_temp_len = 0; @@ -303,6 +333,10 @@ pub const Response = struct { id: u32 = 0, image_number: u32 = 0, placement_id: u32 = 0, + /// The 1-based animation frame number, echoed as "r=" for the + /// animation frame actions. This is how clients learn the frame + /// number assigned to a newly created frame. + frame: u32 = 0, message: []const u8 = "OK", pub fn encode(self: Response, writer: *std.Io.Writer) !void { @@ -326,6 +360,10 @@ pub const Response = struct { if (prior) try writer.writeByte(',') else prior = true; try writer.print("p={}", .{self.placement_id}); } + if (self.frame > 0) { + if (prior) try writer.writeByte(',') else prior = true; + try writer.print("r={}", .{self.frame}); + } try writer.writeByte(';'); try writer.writeAll(self.message); try writer.writeAll("\x1b\\"); @@ -376,6 +414,53 @@ pub const Command = struct { transmit_animation_frame: AnimationFrameLoading, control_animation: AnimationControl, compose_animation: AnimationFrameComposition, + + pub const Identifiers = struct { + image_id: u32 = 0, + image_number: u32 = 0, + placement_id: u32 = 0, + }; + + /// Returns the image and placement identifiers for any action. + pub fn identifiers(self: Control) Identifiers { + return switch (self) { + .query, .transmit => |t| .{ + .image_id = t.image_id, + .image_number = t.image_number, + .placement_id = t.placement_id, + }, + .transmit_and_display => |t| .{ + .image_id = t.transmission.image_id, + .image_number = t.transmission.image_number, + .placement_id = t.transmission.placement_id, + }, + .display => |d| .{ + .image_id = d.image_id, + .image_number = d.image_number, + .placement_id = d.placement_id, + }, + .delete => |d| .{ + .image_id = d.image_id, + .image_number = d.image_number, + .placement_id = d.placement_id, + }, + .transmit_animation_frame => |f| .{ + .image_id = f.transmission.image_id, + .image_number = f.transmission.image_number, + .placement_id = f.transmission.placement_id, + }, + .control_animation => |a| .{ + .image_id = a.image_id, + .image_number = a.image_number, + .placement_id = a.placement_id, + }, + .compose_animation => |c| .{ + .image_id = c.image_id, + .image_number = c.image_number, + .placement_id = c.placement_id, + }, + }; + } }; /// Take ownership over the data in this command. If the returned value @@ -392,6 +477,7 @@ pub const Command = struct { .query => |t| t, .transmit => |t| t, .transmit_and_display => |t| t.transmission, + .transmit_animation_frame => |f| f.transmission, else => null, }; } @@ -412,6 +498,11 @@ pub const Command = struct { pub const Transmission = struct { format: Format = .rgba, // f + /// Set when "f" carried a value we don't recognize. Kitty rejects these + /// while handling the command so the EINVAL response can carry the image + /// id, so we defer to `LoadingImage.init`. `format` is meaningless when + /// this is set. + format_unknown: bool = false, medium: Medium = .direct, // t width: u32 = 0, // s height: u32 = 0, // v @@ -422,6 +513,7 @@ pub const Transmission = struct { placement_id: u32 = 0, // p compression: Compression = .none, // o more_chunks: bool = false, // m + usage: Usage = .default, // N pub const Format = lib.Enum(lib.target, &.{ "rgb", // 24 @@ -446,6 +538,19 @@ pub const Transmission = struct { "zlib_deflate", // z }); + /// Usage hints allow for optimising resource consumption strategies. + /// + /// https://sw.kovidgoyal.net/kitty/graphics-protocol/#usage-hints + pub const Usage = packed struct(u32) { + /// Image with this usage hint is assumed to be used for only a short + /// time, so may be evicted before other images if memory pressure is + /// encountered. + transient: bool = false, + _padding: u31 = 0, + + pub const default: Usage = .{}; + }; + pub fn formatBpp(format: Format) u8 { return switch (format) { .gray => 1, @@ -461,9 +566,13 @@ pub const Transmission = struct { if (kv.get('f')) |v| { result.format = switch (v) { 24 => .rgb, - 32 => .rgba, + 0, 32 => .rgba, 100 => .png, - else => return error.InvalidFormat, + else => unknown: { + // Defer returning an error until the image is processed. + result.format_unknown = true; + break :unknown .rgba; + }, }; } @@ -529,6 +638,10 @@ pub const Transmission = struct { } } + if (kv.get('N')) |v| { + result.usage = @bitCast(v); + } + return result; } }; @@ -606,19 +719,13 @@ pub const Display = struct { } if (kv.get('C')) |v| { - result.cursor_movement = switch (v) { - 0 => .after, - 1 => .none, - else => return error.InvalidFormat, - }; + // Kitty only tests this against 1 so any other value moves the cursor. + result.cursor_movement = if (v == 1) .none else .after; } if (kv.get('U')) |v| { - result.virtual_placement = switch (v) { - 0 => false, - 1 => true, - else => return error.InvalidFormat, - }; + // Kitty stores this in a bool, so any non-zero value is virtual. + result.virtual_placement = v != 0; } if (kv.get('z')) |v| { @@ -649,23 +756,51 @@ pub const Display = struct { }; pub const AnimationFrameLoading = struct { + /// Frame data is transmitted exactly like image data, so an a=f + /// command carries a full set of transmission keys: medium (t), + /// format (f), the frame rectangle size (s/v), chunking (m), etc. + /// The image id/number here identify the (existing) image the + /// frame belongs to. + transmission: Transmission = .{}, + + /// The left/top edge (pixels) of the rectangle within the frame + /// that the transmitted data updates. x: u32 = 0, // x y: u32 = 0, // y + + /// The 1-based frame number whose pixels serve as the base canvas + /// for a newly created frame. Zero means no base frame: the + /// canvas is filled with `background` instead. create_frame: u32 = 0, // c + + /// The 1-based frame number of an existing frame to edit. Zero + /// (or any value past the next frame number) creates a new frame. edit_frame: u32 = 0, // r - gap_ms: u32 = 0, // z + + /// The gap in milliseconds before the next frame is shown. For + /// new frames, zero selects the default gap and a negative value + /// creates a gapless (never displayed) frame. For edits, zero + /// leaves the gap unchanged. + gap_ms: i32 = 0, // z + composition_mode: CompositionMode = .alpha_blend, // X background: Background = .{}, // Y + /// The canvas background color as a 32-bit RGBA value where R is + /// the most significant byte (0xRRGGBBAA), e.g. Y=4278190335 + /// (0xff0000ff) is opaque red. Bit-cast from the little-endian + /// u32 value, so the field order is reversed from the byte order. pub const Background = packed struct(u32) { - r: u8 = 0, - g: u8 = 0, - b: u8 = 0, a: u8 = 0, + b: u8 = 0, + g: u8 = 0, + r: u8 = 0, }; - fn parse(kv: KV) !AnimationFrameLoading { - var result: AnimationFrameLoading = .{}; + fn parse(kv: KV) error{InvalidFormat}!AnimationFrameLoading { + var result: AnimationFrameLoading = .{ + .transmission = try .parse(kv), + }; if (kv.get('x')) |v| { result.x = v; @@ -684,15 +819,15 @@ pub const AnimationFrameLoading = struct { } if (kv.get('z')) |v| { - result.gap_ms = v; + // 'z' is one of the keys Parser.finishValue parses as an + // i32, so the u32 in the KV table is the bit pattern of + // that i32 and this reconstructs it exactly. + result.gap_ms = @bitCast(v); } + // Tested only against 1 like Kitty. if (kv.get('X')) |v| { - result.composition_mode = switch (v) { - 0 => .alpha_blend, - 1 => .overwrite, - else => return error.InvalidFormat, - }; + result.composition_mode = if (v == 1) .overwrite else .alpha_blend; } if (kv.get('Y')) |v| { @@ -704,25 +839,56 @@ pub const AnimationFrameLoading = struct { }; pub const AnimationFrameComposition = struct { - frame: u32 = 0, // c - edit_frame: u32 = 0, // r + image_id: u32 = 0, // i + image_number: u32 = 0, // I + placement_id: u32 = 0, // p + + /// The 1-based frame number being edited (the destination). + dest_frame: u32 = 0, // c + + /// The 1-based frame number whose pixels are composed onto the + /// destination (the source). + source_frame: u32 = 0, // r + + /// The left/top edge (pixels) of the destination rectangle. x: u32 = 0, // x y: u32 = 0, // y + + /// The size of the rectangle to compose. Zero selects the full + /// image width/height. width: u32 = 0, // w height: u32 = 0, // h + + /// The left/top edge (pixels) of the source rectangle. left_edge: u32 = 0, // X top_edge: u32 = 0, // Y + composition_mode: CompositionMode = .alpha_blend, // C - fn parse(kv: KV) !AnimationFrameComposition { + // Cannot fail: every key is stored as parsed, with no range + // validation (Kitty range-checks these while handling the + // command; see the comment above the execution-deferral tests). + fn parse(kv: KV) AnimationFrameComposition { var result: AnimationFrameComposition = .{}; + if (kv.get('i')) |v| { + result.image_id = v; + } + + if (kv.get('I')) |v| { + result.image_number = v; + } + + if (kv.get('p')) |v| { + result.placement_id = v; + } + if (kv.get('c')) |v| { - result.frame = v; + result.dest_frame = v; } if (kv.get('r')) |v| { - result.edit_frame = v; + result.source_frame = v; } if (kv.get('x')) |v| { @@ -750,11 +916,8 @@ pub const AnimationFrameComposition = struct { } if (kv.get('C')) |v| { - result.composition_mode = switch (v) { - 0 => .alpha_blend, - 1 => .overwrite, - else => return error.InvalidFormat, - }; + // Kitty tests this against zero for compose so any non-zero overwrites + result.composition_mode = if (v == 0) .alpha_blend else .overwrite; } return result; @@ -762,10 +925,24 @@ pub const AnimationFrameComposition = struct { }; pub const AnimationControl = struct { + image_id: u32 = 0, // i + image_number: u32 = 0, // I + placement_id: u32 = 0, // p action: AnimationAction = .invalid, // s + + /// The 1-based frame number whose gap is set from gap_ms. frame: u32 = 0, // r - gap_ms: u32 = 0, // z + + /// The new gap for `frame` in milliseconds. Zero is ignored and a + /// negative value makes the frame gapless. + gap_ms: i32 = 0, // z + + /// The 1-based frame number to make current (client-driven + /// animation). Zero is ignored. current_frame: u32 = 0, // c + + /// The loop count: zero is ignored, 1 loops forever, and any + /// larger value plays that many minus one loops. loops: u32 = 0, // v pub const AnimationAction = enum { @@ -775,16 +952,32 @@ pub const AnimationControl = struct { run, // 3 }; - fn parse(kv: KV) !AnimationControl { + // Cannot fail: every key is stored as parsed. Out-of-range values + // (frame numbers, states) are silently ignored during execution, + // matching Kitty. + fn parse(kv: KV) AnimationControl { var result: AnimationControl = .{}; + if (kv.get('i')) |v| { + result.image_id = v; + } + + if (kv.get('I')) |v| { + result.image_number = v; + } + + if (kv.get('p')) |v| { + result.placement_id = v; + } + if (kv.get('s')) |v| { + // Kitty ignores values it doesn't know, leaving the animation + // state untouched, which is what `.invalid` means here. result.action = switch (v) { - 0 => .invalid, 1 => .stop, 2 => .run_wait, 3 => .run, - else => return error.InvalidFormat, + else => .invalid, }; } @@ -793,7 +986,10 @@ pub const AnimationControl = struct { } if (kv.get('z')) |v| { - result.gap_ms = v; + // 'z' is one of the keys Parser.finishValue parses as an + // i32, so the u32 in the KV table is the bit pattern of + // that i32 and this reconstructs it exactly. + result.gap_ms = @bitCast(v); } if (kv.get('c')) |v| { @@ -808,180 +1004,218 @@ pub const AnimationControl = struct { } }; -pub const Delete = union(enum) { - // a/A - all: bool, - - // i/I - id: struct { - delete: bool = false, // uppercase - image_id: u32 = 0, // i - placement_id: u32 = 0, // p - }, - - // n/N - newest: struct { - delete: bool = false, // uppercase - image_number: u32 = 0, // I - placement_id: u32 = 0, // p - }, - - // c/C, - intersect_cursor: bool, - - // f/F - animation_frames: bool, - - // p/P - intersect_cell: struct { - delete: bool = false, // uppercase - x: u32 = 0, // x - y: u32 = 0, // y - }, - - // q/Q - intersect_cell_z: struct { - delete: bool = false, // uppercase - x: u32 = 0, // x - y: u32 = 0, // y - z: i32 = 0, // z - }, - - // r/R - range: struct { - delete: bool = false, // uppercase - first: u32 = 0, // x - last: u32 = 0, // y - }, - - // x/X - column: struct { - delete: bool = false, // uppercase - x: u32 = 0, // x - }, - - // y/Y - row: struct { - delete: bool = false, // uppercase - y: u32 = 0, // y - }, - - // z/Z - z: struct { - delete: bool = false, // uppercase - z: i32 = 0, // z - }, +pub const Delete = struct { + image_id: u32 = 0, // i + image_number: u32 = 0, // I + placement_id: u32 = 0, // p + action: Action, fn parse(kv: KV) !Delete { - const what: u8 = what: { - const value = kv.get('d') orelse break :what 'a'; - const c = std.math.cast(u8, value) orelse return error.InvalidFormat; - break :what c; + return .{ + .image_id = kv.get('i') orelse 0, + .image_number = kv.get('I') orelse 0, + .placement_id = kv.get('p') orelse 0, + .action = try .parse(kv), }; + } - return switch (what) { - 'a', 'A' => .{ .all = what == 'A' }, + pub const Action = union(enum) { + // a/A + all: bool, - 'i', 'I' => blk: { - var result: Delete = .{ .id = .{ .delete = what == 'I' } }; - if (kv.get('i')) |v| { - result.id.image_id = v; - } - if (kv.get('p')) |v| { - result.id.placement_id = v; - } + // i/I + id: struct { + delete: bool = false, // uppercase + image_id: u32 = 0, // i + placement_id: u32 = 0, // p + }, - break :blk result; - }, + // n/N + newest: struct { + delete: bool = false, // uppercase + image_number: u32 = 0, // I + placement_id: u32 = 0, // p + }, - 'n', 'N' => blk: { - var result: Delete = .{ .newest = .{ .delete = what == 'N' } }; - if (kv.get('I')) |v| { - result.newest.image_number = v; - } - if (kv.get('p')) |v| { - result.newest.placement_id = v; - } + // c/C, + intersect_cursor: bool, - break :blk result; - }, + // f/F + animation_frames: AnimationFrames, - 'c', 'C' => .{ .intersect_cursor = what == 'C' }, + // p/P + intersect_cell: struct { + delete: bool = false, // uppercase + x: u32 = 0, // x + y: u32 = 0, // y + }, - 'f', 'F' => .{ .animation_frames = what == 'F' }, + // q/Q + intersect_cell_z: struct { + delete: bool = false, // uppercase + x: u32 = 0, // x + y: u32 = 0, // y + z: i32 = 0, // z + }, - 'p', 'P' => blk: { - var result: Delete = .{ .intersect_cell = .{ .delete = what == 'P' } }; - if (kv.get('x')) |v| { - result.intersect_cell.x = v; - } - if (kv.get('y')) |v| { - result.intersect_cell.y = v; - } + // r/R + range: struct { + delete: bool = false, // uppercase + first: u32 = 0, // x + last: u32 = 0, // y + }, - break :blk result; - }, + // x/X + column: struct { + delete: bool = false, // uppercase + x: u32 = 0, // x + }, - 'q', 'Q' => blk: { - var result: Delete = .{ .intersect_cell_z = .{ .delete = what == 'Q' } }; - if (kv.get('x')) |v| { - result.intersect_cell_z.x = v; - } - if (kv.get('y')) |v| { - result.intersect_cell_z.y = v; - } - if (kv.get('z')) |v| { - // We can bitcast here because of how we parse it earlier. - result.intersect_cell_z.z = @bitCast(v); - } + // y/Y + row: struct { + delete: bool = false, // uppercase + y: u32 = 0, // y + }, - break :blk result; - }, + // z/Z + z: struct { + delete: bool = false, // uppercase + z: i32 = 0, // z + }, - 'r', 'R' => blk: { - const x = kv.get('x') orelse return error.InvalidFormat; - const y = kv.get('y') orelse return error.InvalidFormat; - if (x > y) return error.InvalidFormat; - break :blk .{ - .range = .{ - .delete = what == 'R', - .first = x, - .last = y, - }, - }; - }, + pub const AnimationFrames = struct { + delete: bool = false, // uppercase + image_id: u32 = 0, // i + image_number: u32 = 0, // I + frame: u32 = 0, // r + }; - 'x', 'X' => blk: { - var result: Delete = .{ .column = .{ .delete = what == 'X' } }; - if (kv.get('x')) |v| { - result.column.x = v; - } + fn parse(kv: KV) error{InvalidFormat}!Action { + const what: u8 = what: { + const value = kv.get('d') orelse break :what 'a'; + const c = std.math.cast(u8, value) orelse return error.InvalidFormat; + break :what c; + }; - break :blk result; - }, + return switch (what) { + 'a', 'A' => .{ .all = what == 'A' }, - 'y', 'Y' => blk: { - var result: Delete = .{ .row = .{ .delete = what == 'Y' } }; - if (kv.get('y')) |v| { - result.row.y = v; - } + 'i', 'I' => blk: { + var result: Action = .{ .id = .{ .delete = what == 'I' } }; + if (kv.get('i')) |v| { + result.id.image_id = v; + } + if (kv.get('p')) |v| { + result.id.placement_id = v; + } - break :blk result; - }, + break :blk result; + }, - 'z', 'Z' => blk: { - var result: Delete = .{ .z = .{ .delete = what == 'Z' } }; - if (kv.get('z')) |v| { - // We can bitcast here because of how we parse it earlier. - result.z.z = @bitCast(v); - } + 'n', 'N' => blk: { + var result: Action = .{ .newest = .{ .delete = what == 'N' } }; + if (kv.get('I')) |v| { + result.newest.image_number = v; + } + if (kv.get('p')) |v| { + result.newest.placement_id = v; + } - break :blk result; - }, + break :blk result; + }, - else => return error.InvalidFormat, - }; - } + 'c', 'C' => .{ .intersect_cursor = what == 'C' }, + + 'f', 'F' => blk: { + var result: Action = .{ .animation_frames = .{ .delete = what == 'F' } }; + if (kv.get('i')) |v| { + result.animation_frames.image_id = v; + } + if (kv.get('I')) |v| { + result.animation_frames.image_number = v; + } + if (kv.get('r')) |v| { + result.animation_frames.frame = v; + } + + break :blk result; + }, + + 'p', 'P' => blk: { + var result: Action = .{ .intersect_cell = .{ .delete = what == 'P' } }; + if (kv.get('x')) |v| { + result.intersect_cell.x = v; + } + if (kv.get('y')) |v| { + result.intersect_cell.y = v; + } + + break :blk result; + }, + + 'q', 'Q' => blk: { + var result: Action = .{ .intersect_cell_z = .{ .delete = what == 'Q' } }; + if (kv.get('x')) |v| { + result.intersect_cell_z.x = v; + } + if (kv.get('y')) |v| { + result.intersect_cell_z.y = v; + } + if (kv.get('z')) |v| { + // We can bitcast here because of how we parse it earlier. + result.intersect_cell_z.z = @bitCast(v); + } + + break :blk result; + }, + + 'r', 'R' => blk: { + // Both bounds default to zero when omitted and no + // validation is performed; an inverted or zero range + // simply matches no images. + var result: Action = .{ .range = .{ .delete = what == 'R' } }; + if (kv.get('x')) |v| { + result.range.first = v; + } + if (kv.get('y')) |v| { + result.range.last = v; + } + + break :blk result; + }, + + 'x', 'X' => blk: { + var result: Action = .{ .column = .{ .delete = what == 'X' } }; + if (kv.get('x')) |v| { + result.column.x = v; + } + + break :blk result; + }, + + 'y', 'Y' => blk: { + var result: Action = .{ .row = .{ .delete = what == 'Y' } }; + if (kv.get('y')) |v| { + result.row.y = v; + } + + break :blk result; + }, + + 'z', 'Z' => blk: { + var result: Action = .{ .z = .{ .delete = what == 'Z' } }; + if (kv.get('z')) |v| { + // We can bitcast here because of how we parse it earlier. + result.z.z = @bitCast(v); + } + + break :blk result; + }, + + else => return error.InvalidFormat, + }; + } + }; }; pub const CompositionMode = enum { @@ -1005,6 +1239,26 @@ test "transmission command" { try testing.expectEqual(Transmission.Format.rgb, v.format); try testing.expectEqual(@as(u32, 10), v.width); try testing.expectEqual(@as(u32, 20), v.height); + try testing.expectEqual(false, v.usage.transient); +} + +test "transmission command with transient hint" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc, 1024 * 1024); + defer p.deinit(); + + const input = "f=24,s=10,v=20,N=1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Format.rgb, v.format); + try testing.expectEqual(@as(u32, 10), v.width); + try testing.expectEqual(@as(u32, 20), v.height); + try testing.expectEqual(true, v.usage.transient); } test "feedSlice matches per-byte feed" { @@ -1142,7 +1396,7 @@ test "delete command" { defer command.deinit(alloc); try testing.expect(command.control == .delete); - const v = command.control.delete; + const v = command.control.delete.action; try testing.expect(v == .intersect_cell); const dv = v.intersect_cell; try testing.expect(!dv.delete); @@ -1183,6 +1437,24 @@ test "ignore unknown keys (long)" { try testing.expectEqual(@as(u32, 20), v.height); } +test "ignore unknown keys (non-letter)" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc, 1024 * 1024); + defer p.deinit(); + + const input = "f=24,s=10,v=20,!=1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Format.rgb, v.format); + try testing.expectEqual(@as(u32, 10), v.width); + try testing.expectEqual(@as(u32, 20), v.height); +} + test "ignore very long values" { const testing = std.testing; const alloc = testing.allocator; @@ -1342,7 +1614,7 @@ test "delete range command 1" { defer command.deinit(alloc); try testing.expect(command.control == .delete); - const v = command.control.delete; + const v = command.control.delete.action; try testing.expect(v == .range); const range = v.range; try testing.expect(!range.delete); @@ -1362,7 +1634,7 @@ test "delete range command 2" { defer command.deinit(alloc); try testing.expect(command.control == .delete); - const v = command.control.delete; + const v = command.control.delete.action; try testing.expect(v == .range); const range = v.range; try testing.expect(range.delete); @@ -1371,6 +1643,9 @@ test "delete range command 2" { } test "delete range command 3" { + // An inverted range is accepted; it simply matches no images. This + // matches kitty, which does no validation and filters with + // `x <= image_id <= y`. const testing = std.testing; const alloc = testing.allocator; var p = Parser.init(alloc, 1024 * 1024); @@ -1378,10 +1653,21 @@ test "delete range command 3" { const input = "a=d,d=R,x=5,y=4"; for (input) |c| try p.feed(c); - try testing.expectError(error.InvalidFormat, p.complete(alloc)); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete.action; + try testing.expect(v == .range); + const range = v.range; + try testing.expect(range.delete); + try testing.expectEqual(@as(u32, 5), range.first); + try testing.expectEqual(@as(u32, 4), range.last); } test "delete range command 4" { + // An omitted upper bound defaults to zero, which matches no images + // since image IDs are always non-zero. const testing = std.testing; const alloc = testing.allocator; var p = Parser.init(alloc, 1024 * 1024); @@ -1389,7 +1675,16 @@ test "delete range command 4" { const input = "a=d,d=R,x=5"; for (input) |c| try p.feed(c); - try testing.expectError(error.InvalidFormat, p.complete(alloc)); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete.action; + try testing.expect(v == .range); + const range = v.range; + try testing.expect(range.delete); + try testing.expectEqual(@as(u32, 5), range.first); + try testing.expectEqual(@as(u32, 0), range.last); } test "delete range command 5" { @@ -1400,5 +1695,178 @@ test "delete range command 5" { const input = "a=d,d=R,y=5"; for (input) |c| try p.feed(c); - try testing.expectError(error.InvalidFormat, p.complete(alloc)); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete.action; + try testing.expect(v == .range); + const range = v.range; + try testing.expect(range.delete); + try testing.expectEqual(@as(u32, 0), range.first); + try testing.expectEqual(@as(u32, 5), range.last); +} + +test "delete range command 6" { + // Both bounds omitted defaults to the empty range [0, 0]. + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc, 1024 * 1024); + defer p.deinit(); + + const input = "a=d,d=r"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete.action; + try testing.expect(v == .range); + const range = v.range; + try testing.expect(!range.delete); + try testing.expectEqual(@as(u32, 0), range.first); + try testing.expectEqual(@as(u32, 0), range.last); +} + +// Kitty range-checks non-flag keys while handling the command, not while +// parsing, so a bad value never drops the command (which would make a +// response impossible even when the client gave an id). The flag keys +// "a", "d", "t" and "o" are the exception. + +test "unknown format value is deferred to execution" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=t,f=42,i=31,s=1,v=1"); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + try testing.expect(command.control.transmit.format_unknown); + try testing.expectEqual(@as(u32, 31), command.control.transmit.image_id); +} + +test "zero format value is rgba" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=t,f=0,i=31,s=1,v=1"); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expect(!v.format_unknown); + try testing.expectEqual(Transmission.Format.rgba, v.format); +} + +test "known format values are not unknown" { + const testing = std.testing; + const alloc = testing.allocator; + + for ([_]struct { []const u8, Transmission.Format }{ + .{ "f=24", .rgb }, + .{ "f=32", .rgba }, + .{ "f=100", .png }, + }) |entry| { + const command = try Parser.parseString(alloc, entry[0]); + defer command.deinit(alloc); + + const v = command.control.transmit; + try testing.expect(!v.format_unknown); + try testing.expectEqual(entry[1], v.format); + } +} + +test "quiet value above two suppresses all responses" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=t,q=3,i=31,s=1,v=1"); + defer command.deinit(alloc); + + try testing.expectEqual(Command.Quiet.failures, command.quiet); +} + +test "cursor movement value above one moves the cursor" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=p,i=31,C=2"); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + try testing.expectEqual( + Display.CursorMovement.after, + command.control.display.cursor_movement, + ); +} + +test "virtual placement value above one is virtual" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=p,i=31,U=2"); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + try testing.expect(command.control.display.virtual_placement); +} + +test "animation frame composition value above one alpha blends" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=f,i=31,X=2"); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit_animation_frame); + try testing.expectEqual( + CompositionMode.alpha_blend, + command.control.transmit_animation_frame.composition_mode, + ); +} + +test "animation compose value above one overwrites" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=c,i=31,C=2"); + defer command.deinit(alloc); + + try testing.expect(command.control == .compose_animation); + try testing.expectEqual( + CompositionMode.overwrite, + command.control.compose_animation.composition_mode, + ); +} + +test "animation control action above three is ignored" { + const testing = std.testing; + const alloc = testing.allocator; + + const command = try Parser.parseString(alloc, "a=a,i=31,s=4"); + defer command.deinit(alloc); + + try testing.expect(command.control == .control_animation); + try testing.expectEqual( + AnimationControl.AnimationAction.invalid, + command.control.control_animation.action, + ); +} + +test "unknown flag key values still fail parsing" { + const testing = std.testing; + const alloc = testing.allocator; + + // Kitty rejects these while parsing too. See gen/apc_parsers.py. + for ([_][]const u8{ + "a=z,i=31", // action + "a=d,d=w,i=31", // delete action + "a=t,t=q,i=31", // transmission medium + "a=t,o=q,i=31", // compression + }) |input| { + try testing.expectError( + error.InvalidFormat, + Parser.parseString(alloc, input), + ); + } } diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig index 6c72ec4e..b1b968b2 100644 --- a/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig @@ -5,6 +5,8 @@ const Allocator = std.mem.Allocator; const Terminal = @import("../Terminal.zig"); const command = @import("graphics_command.zig"); const image = @import("graphics_image.zig"); +const animation = @import("graphics_animation.zig"); +const pixel = @import("graphics_pixel.zig"); const Command = command.Command; const Response = command.Response; const LoadingImage = image.LoadingImage; @@ -21,6 +23,7 @@ const log = std.log.scoped(.kitty_gfx); /// The allocator must be the same allocator that was used to build /// the command. pub fn execute( + io: std.Io, alloc: Allocator, terminal: *Terminal, cmd: *const Command, @@ -43,12 +46,32 @@ pub fn execute( // this can change. var quiet = cmd.quiet; + // The protocol makes i and I mutually exclusive for every action, so this + // must happen before dispatch and before an action can mutate storage. + // https://sw.kovidgoyal.net/kitty/graphics-protocol/#requesting-image-ids-from-the-terminal + const identifiers = cmd.control.identifiers(); + if (identifiers.image_id > 0 and identifiers.image_number > 0) { + const resp: Response = .{ + .id = identifiers.image_id, + .image_number = identifiers.image_number, + .placement_id = identifiers.placement_id, + .message = "EINVAL: image ID and number are mutually exclusive", + }; + log.warn("erroneous kitty graphics response: {s}", .{resp.message}); + + return switch (quiet) { + .no => resp, + .ok => resp, + .failures => null, + }; + } + const resp_: ?Response = switch (cmd.control) { - .query => query(alloc, terminal, cmd), - .display => display(alloc, terminal, cmd), - .delete => delete(alloc, terminal, cmd), + .query => query(io, alloc, terminal, cmd), + .display => display(io, alloc, terminal, cmd), + .delete => delete(io, alloc, terminal, cmd), - .transmit, .transmit_and_display => resp: { + .transmit, .transmit_and_display, .transmit_animation_frame => resp: { // If we're transmitting, then our `q` setting value is complicated. // The `q` setting inherits the value from the starting command // unless `q` is set >= 1 on this command. If it is, then we save @@ -65,13 +88,35 @@ pub fn execute( }, }; - break :resp transmit(alloc, terminal, cmd); + break :resp switch (cmd.control) { + .transmit_animation_frame => transmitAnimationFrame( + io, + alloc, + terminal, + cmd, + ), + else => transmit( + io, + alloc, + terminal, + cmd, + ), + }; }, - .transmit_animation_frame, - .control_animation, - .compose_animation, - => .{ .message = "ERROR: unimplemented action" }, + .control_animation => controlAnimation( + io, + alloc, + terminal, + cmd, + ), + + .compose_animation => composeAnimation( + io, + alloc, + terminal, + cmd, + ), }; // Handle the quiet settings @@ -89,12 +134,14 @@ pub fn execute( return null; } + /// Execute a "query" command. /// /// This command is used to attempt to load an image and respond with /// success/error but does not persist any of the command to the terminal /// state. fn query( + io: std.Io, alloc: Allocator, terminal: *const Terminal, cmd: *const Command, @@ -115,13 +162,21 @@ fn query( .placement_id = t.placement_id, }; - // Attempt to load the image. If we cannot, then set an appropriate error. + // A query must attempt a complete load, then discard the result without + // changing image storage. + // https://sw.kovidgoyal.net/kitty/graphics-protocol/#querying-support-and-available-transmission-mediums const storage = &terminal.screens.active.kitty_images; - var loading = LoadingImage.init(alloc, cmd, storage.image_limits) catch |err| { + var loading = LoadingImage.init(io, alloc, cmd, storage.image_limits) catch |err| { encodeError(&result, err); return result; }; - loading.deinit(alloc); + defer loading.deinit(alloc); + + var img = loading.complete(alloc) catch |err| { + encodeError(&result, err); + return result; + }; + img.deinit(alloc); return result; } @@ -131,21 +186,35 @@ fn query( /// This loads the image, validates it, and puts it into the terminal /// screen storage. It does not display the image. fn transmit( + io: std.Io, alloc: Allocator, terminal: *Terminal, cmd: *const Command, ) Response { const t = cmd.transmission().?; - var result: Response = .{ + const storage = &terminal.screens.active.kitty_images; + + var result: Response = if (storage.loading) |loading| loading: { + // Any transmit-like command received while a load is in progress + // is a continuation chunk of that load, and the load completes + // according to how it started. If an animation frame load (a=f) + // is in progress, this chunk belongs to it even when the client + // didn't repeat a=f on the chunk. + if (loading.frame != null) return transmitAnimationFrame( + io, + alloc, + terminal, + cmd, + ); + + break :loading loading.response; + } else .{ .id = t.image_id, .image_number = t.image_number, .placement_id = t.placement_id, }; - if (t.image_id > 0 and t.image_number > 0) { - return .{ .message = "EINVAL: image ID and number are mutually exclusive" }; - } - const load = loadAndAddImage(alloc, terminal, cmd) catch |err| { + const load = loadAndAddImage(io, alloc, terminal, cmd) catch |err| { encodeError(&result, err); return result; }; @@ -158,7 +227,7 @@ fn transmit( assert(!load.more); var d_copy = d; d_copy.image_id = load.image.id; - result = display(alloc, terminal, &.{ + result = display(io, alloc, terminal, &.{ .control = .{ .display = d_copy }, .quiet = cmd.quiet, }); @@ -169,7 +238,7 @@ fn transmit( // If the loaded image was assigned its ID automatically, not based // on a number or explicitly specified ID, then we don't respond. - if (load.image.implicit_id) return .{}; + if (load.image.metadata.implicit_id) return .{}; // After the image is added, set the ID in case it changed. // The resulting image number and placement ID never change. @@ -180,6 +249,7 @@ fn transmit( /// Display a previously transmitted image. fn display( + io: std.Io, alloc: Allocator, terminal: *Terminal, cmd: *const Command, @@ -198,6 +268,13 @@ fn display( .placement_id = d.placement_id, }; + // A virtual placement (U=1) cannot also be a relative placement. + // Kitty checks this before even looking up the image. + if (d.virtual_placement and d.parent_id > 0) { + result.message = "EINVAL: virtual placement cannot refer to a parent"; + return result; + } + // Verify the requested image exists if we have an ID const storage = &terminal.screens.active.kitty_images; const img_: ?Image = if (d.image_id != 0) @@ -215,42 +292,84 @@ fn display( // Location where the placement will go. const location: ImageStorage.Placement.Location = location: { // Virtual placements are not tracked - if (d.virtual_placement) { - if (d.parent_id > 0) { - result.message = "EINVAL: virtual placement cannot refer to a parent"; + if (d.virtual_placement) break :location .virtual; + + // No parent reference (P=): the placement is pinned to the + // cursor. The cursor is always tracked but we don't want + // this pin to move with the cursor. + if (d.parent_id == 0) { + const pin = terminal.screens.active.pages.trackPin( + terminal.screens.active.cursor.page_pin.*, + ) catch |err| { + log.warn("failed to create pin for Kitty graphics err={}", .{err}); + result.message = "EINVAL: failed to prepare terminal state"; return result; - } - - break :location .{ .virtual = {} }; + }; + break :location .{ .pin = pin }; } - // Track a new pin for our cursor. The cursor is always tracked but we - // don't want this one to move with the cursor. - const pin = terminal.screens.active.pages.trackPin( - terminal.screens.active.cursor.page_pin.*, + // A parent reference makes this a relative placement: it is + // positioned relative to the parent placement instead of the + // cursor. + + // The key of the placement being created, when it is + // addressable (an explicit placement ID). Needed for + // self-parent and cycle detection. + const child: ?ImageStorage.PlacementKey = if (d.placement_id > 0) .{ + .image_id = img.id, + .placement_id = .{ .tag = .external, .id = d.placement_id }, + } else null; + + const parent = storage.resolveParent( + io, + terminal.screens.active, + child, + d.parent_id, + d.parent_placement_id, ) catch |err| { - log.warn("failed to create pin for Kitty graphics err={}", .{err}); - result.message = "EINVAL: failed to prepare terminal state"; + result.message = switch (err) { + error.ParentImageNotFound => "ENOPARENT: parent image not found", + error.ParentPlacementNotFound => "ENOPARENT: parent placement not found", + error.SelfParent => "EINVAL: placement cannot be its own parent", + error.Cycle => "ECYCLE: parent chain creates a cycle", + error.TooDeep => "ETOODEEP: parent chain too deep", + error.AncestorNotFound => "ENOENT: parent chain ancestor not found", + }; return result; }; - break :location .{ .pin = pin }; + + break :location .{ .relative = .{ + .parent = parent, + .horizontal_offset = d.horizontal_offset, + .vertical_offset = d.vertical_offset, + } }; }; // Add the placement - const p: ImageStorage.Placement = .{ - .location = location, - .x_offset = d.x_offset, - .y_offset = d.y_offset, - .source_x = d.x, - .source_y = d.y, - .source_width = d.width, - .source_height = d.height, - .columns = d.columns, - .rows = d.rows, - .z = d.z, + const p: ImageStorage.Placement = placement: { + var p: ImageStorage.Placement = .{ + .location = location, + .x_offset = d.x_offset, + .y_offset = d.y_offset, + .source_x = d.x, + .source_y = d.y, + .source_width = d.width, + .source_height = d.height, + .columns = d.columns, + .rows = d.rows, + .z = d.z, + }; + + const cell_offset = p.cellOffset(terminal); + if (terminal.width_px / terminal.cols > 0) p.x_offset = cell_offset.x; + if (terminal.height_px / terminal.rows > 0) p.y_offset = cell_offset.y; + + break :placement p; }; storage.addPlacement( + io, alloc, + terminal.screens.active, img.id, result.placement_id, p, @@ -260,22 +379,54 @@ fn display( return result; }; - // Apply cursor movement setting. This only applies to pin placements. + // Apply cursor movement setting. This only applies to pin placements: + // relative placements never move the cursor regardless of C=, just + // like kitty. switch (p.location) { - .virtual => {}, + .virtual, .relative => {}, .pin => |pin| switch (d.cursor_movement) { .none => {}, .after => { // We use terminal.index to properly handle scroll regions. + const screen = terminal.screens.active; const size = p.gridSize(img, terminal); - for (0..size.rows) |_| terminal.index() catch |err| { + const target_x = @as(usize, pin.x) +| @as(usize, size.cols); + const wraps = target_x >= @as(usize, terminal.cols); + const requested_rows = + (@as(usize, size.rows) -| 1) +| @intFromBool(wraps); + + // The requested row count comes from the application and can + // be as large as u32. Calling terminal.index once for every + // row could therefore leave the terminal unresponsive for a + // very long time. + // + // First allow enough calls to reach the bottom of the scroll + // region. Each call after that scrolls the region by one row, + // so limit those extra calls to one screen. This follows + // Kitty's behavior while keeping the amount of work bounded. + const region = terminal.scrolling_region; + const rows_before_scroll: usize = if (screen.cursor.y >= region.top and + screen.cursor.y <= region.bottom and + screen.cursor.x >= region.left and + screen.cursor.x <= region.right) + @as(usize, region.bottom - screen.cursor.y) + else + 0; + const rows_to_move: usize = @min( + requested_rows, + rows_before_scroll +| @as(usize, terminal.rows), + ); + for (0..rows_to_move) |_| terminal.index() catch |err| { log.warn("failed to move cursor: {}", .{err}); break; }; - terminal.setCursorPos( - terminal.screens.active.cursor.y, - pin.x + size.cols + 1, + // Kitty wraps once when the movement reaches the right edge; + // otherwise it leaves the cursor immediately to the right of + // the placement. + screen.cursor.pending_wrap = false; + screen.cursorHorizontalAbsolute( + if (wraps) 0 else @intCast(target_x), ); }, }, @@ -284,20 +435,556 @@ fn display( return result; } +/// Transmit animation frame data (a=f). +/// +/// Frame data is loaded exactly like image data, including chunking +/// and every transmission medium, and once complete it is composed +/// into a frame of an existing image's animation. +fn transmitAnimationFrame( + io: std.Io, + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) Response { + const storage = &terminal.screens.active.kitty_images; + + // A chunk arriving while a load is in progress continues that load. + if (storage.loading) |loading| { + // If this is the first frame, then we treat it like a normal image + // because the first frame is just the image. + if (loading.frame == null) return transmit( + io, + alloc, + terminal, + cmd, + ); + + // Not the first frame, so continue loading similar to transmit + // but this is for a subsequent frame. + var result = loading.response; + loading.addData(alloc, cmd.data) catch |err| { + encodeError(&result, err); + return result; + }; + + // If more chunks are expected we don't respond yet. + const t = cmd.transmission().?; + if (t.more_chunks) return .{}; + + // Final chunk: copy the loading state out and free the + // pointer, mirroring loadAndAddImage. + var loading_copy = loading.*; + alloc.destroy(loading); + storage.loading = null; + defer loading_copy.deinit(alloc); + return completeAnimationFrame( + io, + alloc, + terminal, + &loading_copy, + ); + } + + // We are starting our load, either the first frame or a subsequent frame. + const f = cmd.control.transmit_animation_frame; + const t = f.transmission; + var result: Response = .{ + .id = t.image_id, + .image_number = t.image_number, + .placement_id = t.placement_id, + // Errors echo the client's frame number; on success this is + // replaced with the resolved (possibly newly assigned) one. + .frame = f.edit_frame, + }; + + // A frame can only be added to an existing image. + if (t.image_id == 0 and t.image_number == 0) { + result.message = "EINVAL: image ID or number required"; + return result; + } + const img = storage.imagePtrByIdOrNumber( + t.image_id, + t.image_number, + ) orelse { + result.message = "ENOENT: image not found"; + return result; + }; + result.id = img.id; + + var loading = LoadingImage.init( + io, + alloc, + cmd, + storage.image_limits, + ) catch |err| { + encodeError(&result, err); + return result; + }; + loading.frame = .{ + .cmd = f, + .image_generation = img.generation, + }; + loading.response.id = img.id; + + // Chunked: store the loading state and wait for the rest. The + // frame parameters above are saved with it; continuation chunks + // contribute only payload bytes. + if (t.more_chunks) { + const loading_ptr = alloc.create(LoadingImage) catch |err| { + loading.deinit(alloc); + encodeError(&result, err); + return result; + }; + loading_ptr.* = loading; + storage.loading = loading_ptr; + return .{}; + } + + defer loading.deinit(alloc); + return completeAnimationFrame( + io, + alloc, + terminal, + &loading, + ); +} + +/// Complete a fully loaded animation frame: validate it against its +/// image and compose it into the image's animation. +fn completeAnimationFrame( + io: std.Io, + alloc: Allocator, + terminal: *Terminal, + loading: *LoadingImage, +) Response { + const storage = &terminal.screens.active.kitty_images; + var result = loading.response; + const f = loading.frame.?.cmd; + + // Re-resolve the image: it may have been deleted, evicted, or + // replaced while the frame data was being transmitted. The saved + // generation pins the exact image the load started against. + var img = storage.imagePtrByIdOrNumber( + loading.image.id, + loading.image.number, + ) orelse { + result.message = "ENOENT: image not found"; + return result; + }; + if (img.generation != loading.frame.?.image_generation) { + result.message = "ENOENT: image not found"; + return result; + } + if (img.data.bytes() == null) { + result.message = "EINVAL: image data incomplete"; + return result; + } + + // Finish decoding the frame data: decompression, PNG decoding, + // and length validation all match image loading. + var frame_img = loading.complete(alloc) catch |err| { + encodeError(&result, err); + return result; + }; + defer frame_img.deinit(alloc); + + // The frame rectangle may not exceed the image's size. The x/y + // offsets are deliberately not validated: composition clips, + // matching Kitty. + if (frame_img.width > img.width or frame_img.height > img.height) { + result.message = "EINVAL: frame dimensions exceed image"; + return result; + } + + // All composition happens in RGBA; convert both sides as needed. + if (frame_img.format != .rgba) { + const rgba = pixel.rgbaFromFormat( + alloc, + frame_img.format, + frame_img.data.bytes().?, + ) catch |err| { + encodeError(&result, err); + return result; + }; + frame_img.data.deinit(alloc); + frame_img.data = .{ .complete = rgba }; + frame_img.format = .rgba; + } + storage.convertImageToRgba(io, alloc, img) catch |err| { + encodeError(&result, err); + return result; + }; + + const anim = ensureAnimation(alloc, img) catch |err| { + encodeError(&result, err); + return result; + }; + + // Resolve the frame number: r in 1..count edits that existing + // frame, anything else (including omitted) creates a new frame + // appended at count+1. The resolved number is echoed in the + // response so clients can learn assigned frame numbers. + const count: u32 = anim.frameCount(); + const number: u32 = number: { + const r = f.edit_frame; + if (r == 0 or r > count + 1) break :number count + 1; + break :number r; + }; + result.frame = number; + + const src = frame_img.data.bytes().?; + if (number == count + 1) { + // Creating a new frame. The gap defaults to 40ms when omitted + // and a negative gap creates a gapless (never shown) frame. + const gap: u32 = if (f.gap_ms > 0) + @intCast(f.gap_ms) + else if (f.gap_ms < 0) + 0 + else + animation.default_gap_ms; + + // The base canvas frame must exist before we reserve space. + if (f.create_frame > 0 and img.frameData(f.create_frame) == null) { + result.message = "EINVAL: base frame not found"; + return result; + } + + // Reserve room for the new frame, evicting other images if + // needed. Eviction can remove images (never this one), so we + // re-resolve our pointer afterwards to be safe. + const frame_len: usize = @as(usize, img.width) * img.height * 4; + const image_id = img.id; + storage.reserveAnimationBytes( + io, + alloc, + terminal.screens.active, + image_id, + frame_len, + ) catch { + result.message = "ENOSPC: animation frame storage full"; + return result; + }; + img = storage.imagePtrByIdOrNumber(image_id, 0).?; + + const canvas = alloc.alloc(u8, frame_len) catch { + storage.releaseAnimationBytes(frame_len); + result.message = "ENOMEM: out of memory"; + return result; + }; + if (f.create_frame > 0) { + @memcpy(canvas, img.frameData(f.create_frame).?); + } else { + pixel.fillBackground(canvas, f.background); + } + pixel.composeRect( + canvas, + img.width, + img.height, + src, + frame_img.width, + frame_img.height, + f.x, + f.y, + f.composition_mode, + ); + + anim.frames.append(alloc, .{ + .data = canvas, + .gap_ms = gap, + }) catch { + alloc.free(canvas); + storage.releaseAnimationBytes(frame_len); + result.message = "ENOMEM: out of memory"; + return result; + }; + + // A new frame never changes the displayed frame (playback + // reaches it later), but the storage content changed. + storage.markMutated(io); + } else { + // Editing an existing frame. A nonzero gap also updates the + // frame's gap; the 40ms default doesn't apply to edits. + // + // Unlike frame creation there is no byte reservation here: + // frames are always stored at full image size, so the edit + // composes into the existing buffer in place and storage + // usage cannot change. Kitty likewise exempts frame edits + // from its quota check. + if (f.gap_ms != 0) anim.setGapAt( + number - 1, + if (f.gap_ms > 0) @intCast(f.gap_ms) else 0, + ); + + // The frame data is owned by this storage, so the const cast + // is safe (same reasoning as the renderer's image uploads). + const dst = @constCast(img.frameData(number).?); + pixel.composeRect( + dst, + img.width, + img.height, + src, + frame_img.width, + frame_img.height, + f.x, + f.y, + f.composition_mode, + ); + + if (number - 1 == anim.current_index) { + // The displayed pixels changed; restart the frame's gap + // timer like Kitty's re-upload does. + anim.frame_shown_at_ms = null; + storage.markImageContentChanged(io, img); + } else { + storage.markMutated(io); + } + } + + return result; +} + +/// Control animation playback (a=a). +/// +/// Successful commands never respond. The only possible responses are +/// for a missing image or identifier. Invalid key values are silently +/// ignored, matching Kitty. +fn controlAnimation( + io: std.Io, + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) Response { + const a = cmd.control.control_animation; + const storage = &terminal.screens.active.kitty_images; + + var result: Response = .{ + .id = a.image_id, + .image_number = a.image_number, + .placement_id = a.placement_id, + }; + if (a.image_id == 0 and a.image_number == 0) { + result.message = "EINVAL: image ID or number required"; + return result; + } + const img = storage.imagePtrByIdOrNumber( + a.image_id, + a.image_number, + ) orelse { + result.message = "ENOENT: image not found"; + return result; + }; + + const anim = ensureAnimation(alloc, img) catch |err| { + encodeError(&result, err); + return result; + }; + + // The keys below are applied independently and in the same order as Kitty. + + // Set a frame's gap (r= together with z=). This is the only way + // to give the root frame a gap, since it is created gapless. + if (a.frame != 0 and a.frame <= anim.frameCount() and a.gap_ms != 0) { + anim.setGapAt( + a.frame - 1, + if (a.gap_ms > 0) @intCast(a.gap_ms) else 0, + ); + storage.markMutated(io); + } + + // Set the current frame (c=), the client-driven animation + // primitive. + if (a.current_frame != 0 and a.current_frame <= anim.frameCount() and + a.current_frame - 1 != anim.current_index) + { + anim.current_index = a.current_frame - 1; + anim.frame_shown_at_ms = null; + storage.markImageContentChanged(io, img); + } + + // Set the playback state (s=). Any state change resets the loop + // counter; leaving the stopped state restarts the gap timer. + if (a.action != .invalid) { + const old = anim.state; + anim.state = switch (a.action) { + .invalid => unreachable, + .stop => .stopped, + .run_wait => .loading, + .run => .running, + }; + if (old == .stopped and anim.state != .stopped) { + anim.frame_shown_at_ms = null; + } + anim.current_loop = 0; + storage.markMutated(io); + } + + // Set the loop count (v=), stored off by one per the protocol: + // v=1 loops forever, v=n plays n-1 loops. + if (a.loops != 0) { + anim.max_loops = a.loops - 1; + storage.markMutated(io); + } + + // Successful animation control commands never respond. + return .{}; +} + +/// Compose a rectangle of pixels from one animation frame onto +/// another (a=c). Frame 1 (the root frame) always exists, so this also works +/// on images without any animation state. +fn composeAnimation( + io: std.Io, + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) Response { + const c = cmd.control.compose_animation; + const storage = &terminal.screens.active.kitty_images; + + var result: Response = .{ + .id = c.image_id, + .image_number = c.image_number, + .placement_id = c.placement_id, + }; + if (c.image_id == 0 and c.image_number == 0) { + result.message = "EINVAL: image ID or number required"; + return result; + } + const img = storage.imagePtrByIdOrNumber( + c.image_id, + c.image_number, + ) orelse { + result.message = "ENOENT: image not found"; + return result; + }; + result.id = img.id; + if (img.data.bytes() == null) { + result.message = "EINVAL: image data incomplete"; + return result; + } + + // Both frames must exist. Note that r is the source frame and c + // the destination; the spec's reference table describes these + // backwards (see AnimationFrameComposition). + if (img.frameData(c.source_frame) == null) { + result.message = "ENOENT: source frame not found"; + return result; + } + if (img.frameData(c.dest_frame) == null) { + result.message = "ENOENT: destination frame not found"; + return result; + } + + // Rectangle validation is done in u64 so untrusted 32-bit values + // can't overflow. Out-of-bounds rectangles are errors here, + // unlike a=f which clips. + const width: u64 = if (c.width > 0) c.width else img.width; + const height: u64 = if (c.height > 0) c.height else img.height; + if (@as(u64, c.x) + width > img.width or + @as(u64, c.y) + height > img.height) + { + result.message = "EINVAL: destination rectangle out of bounds"; + return result; + } + if (@as(u64, c.left_edge) + width > img.width or + @as(u64, c.top_edge) + height > img.height) + { + result.message = "EINVAL: source rectangle out of bounds"; + return result; + } + + // Composing a frame onto itself requires non-overlapping + // rectangles. + if (c.source_frame == c.dest_frame) { + const x_overlaps = @max(c.left_edge, c.x) < @min(c.left_edge, c.x) + width; + const y_overlaps = @max(c.top_edge, c.y) < @min(c.top_edge, c.y) + height; + if (x_overlaps and y_overlaps) { + result.message = "EINVAL: source and destination rectangles overlap"; + return result; + } + } + + // All composition happens in RGBA. + storage.convertImageToRgba( + io, + alloc, + img, + ) catch |err| { + encodeError(&result, err); + return result; + }; + + // The frame data is owned by this storage, so the const cast is + // safe. The rectangles were validated disjoint above, so in-place + // composition within one frame is well-defined. + const src = img.frameData(c.source_frame).?; + const dst = @constCast(img.frameData(c.dest_frame).?); + pixel.composeCanvasRect( + dst, + src, + img.width, + @intCast(width), + @intCast(height), + c.left_edge, + c.top_edge, + c.x, + c.y, + c.composition_mode, + ); + + // If the destination is the displayed frame then the on-screen + // content changed. + const current: u32 = if (img.animation) |anim| anim.current_index else 0; + if (c.dest_frame - 1 == current) { + storage.markImageContentChanged(io, img); + } else { + storage.markMutated(io); + } + + return result; +} + +/// Get or lazily create the animation state for an image. +fn ensureAnimation( + alloc: Allocator, + img: *Image, +) Allocator.Error!*animation.Animation { + if (img.animation) |anim| return anim; + const anim = try alloc.create(animation.Animation); + anim.* = .{}; + img.animation = anim; + return anim; +} + /// Display a previously transmitted image. fn delete( + io: std.Io, alloc: Allocator, terminal: *Terminal, cmd: *const Command, ) Response { const storage = &terminal.screens.active.kitty_images; - storage.delete(alloc, terminal, cmd.control.delete); + + // Every delete command aborts an incomplete chunked upload. + if (storage.loading) |loading| { + loading.destroy(alloc); + storage.loading = null; + } + + // Then perform the actual deletion request, too. + storage.delete( + io, + alloc, + terminal, + cmd.control.delete.action, + ); // Delete never responds on success return .{}; } fn loadAndAddImage( + io: std.Io, alloc: Allocator, terminal: *Terminal, cmd: *const Command, @@ -327,7 +1014,18 @@ fn loadAndAddImage( } break :loading loading.*; - } else try .init(alloc, cmd, storage.image_limits); + } else loading: { + // Reusing a specific image ID deletes the old image and all of its + // placements when the new transmission begins, not when it completes. + if (t.image_id > 0) { + storage.delete(io, alloc, terminal, .{ .id = .{ + .image_id = t.image_id, + .delete = true, + } }); + } + + break :loading try .init(io, alloc, cmd, storage.image_limits); + }; // We only want to deinit on error. If we're chunking, then we don't // want to deinit at all. If we're not chunking, then we'll deinit @@ -336,12 +1034,12 @@ fn loadAndAddImage( // If the image has no ID, we assign one if (loading.image.id == 0) { - loading.image.id = storage.next_image_id; - storage.next_image_id +%= 1; - - // If the image also has no number then its auto-ID is "implicit". - // See the doc comment on the Image.implicit_id field for more detail. - if (loading.image.number == 0) loading.image.implicit_id = true; + if (loading.image.number > 0) { + loading.image.id = storage.nextImageId(.explicit); + } else { + loading.image.id = storage.nextImageId(.implicit); + loading.image.metadata.implicit_id = true; + } } // If this is chunked, this is the beginning of a new chunked transmission. @@ -362,7 +1060,7 @@ fn loadAndAddImage( // Validate and store our image var img = try loading.complete(alloc); errdefer img.deinit(alloc); - try storage.addImage(alloc, img); + try storage.addImage(io, alloc, terminal.screens.active, img); // Get our display settings const display_ = loading.display; @@ -380,6 +1078,7 @@ const EncodeableError = Image.Error || Allocator.Error; fn encodeError(r: *Response, err: EncodeableError) void { switch (err) { error.OutOfMemory => r.message = "ENOMEM: out of memory", + error.InsufficientData => r.message = "ENODATA: insufficient data", error.InvalidData => r.message = "EINVAL: invalid data", error.DecompressionFailed => r.message = "EINVAL: decompression failed", error.FilePathTooLong => r.message = "EINVAL: file path too long", @@ -393,11 +1092,262 @@ fn encodeError(r: *Response, err: EncodeableError) void { } } +test "kittygfx query validates image data" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var terminal = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer terminal.deinit(alloc); + + var cmd: Command = .{ + .control = .{ .query = .{ + .format = .rgb, + .width = 1, + .height = 1, + .image_id = 31, + } }, + // A 1x1 RGB image requires three bytes. + .data = try alloc.dupe(u8, &.{ 0, 0 }), + }; + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &terminal, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(u32, 31), resp.id); + try testing.expectEqualStrings("EINVAL: invalid data", resp.message); + try testing.expectEqual( + @as(usize, 0), + terminal.screens.active.kitty_images.images.count(), + ); +} + +test "kittygfx valid query does not replace or store image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var terminal = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer terminal.deinit(alloc); + const storage = &terminal.screens.active.kitty_images; + + // Store a red pixel under the same ID used by the query. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=31;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &terminal, &cmd).?.ok()); + } + + // Successfully validate a black pixel without replacing the red one. + var cmd: Command = .{ + .control = .{ .query = .{ + .format = .rgb, + .width = 1, + .height = 1, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, &.{ 0, 0, 0 }), + }; + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &terminal, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(usize, 1), storage.images.count()); + try testing.expectEqualSlices( + u8, + &.{ 255, 0, 0 }, + storage.imageById(31).?.data.bytes().?, + ); +} + +test "kittygfx image id and number are mutually exclusive for every action" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const inputs = [_][]const u8{ + "a=q,f=24,s=1,v=1,i=1,I=2,p=3;AAAA", + "a=t,f=24,s=1,v=1,i=1,I=2,p=3;AAAA", + "a=T,f=24,s=1,v=1,i=1,I=2,p=3;AAAA", + "a=p,i=1,I=2,p=3", + "a=d,d=a,i=1,I=2,p=3", + "a=f,i=1,I=2,p=3;AAAA", + "a=a,i=1,I=2,p=3", + "a=c,i=1,I=2,p=3", + }; + + for (inputs) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + try testing.expectEqual(@as(u32, 2), resp.image_number); + try testing.expectEqual(@as(u32, 3), resp.placement_id); + try testing.expectEqualStrings( + "EINVAL: image ID and number are mutually exclusive", + resp.message, + ); + + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try resp.encode(&writer); + try testing.expectEqualStrings( + "\x1b_Gi=1,I=2,p=3;EINVAL: image ID and number are mutually exclusive\x1b\\", + writer.buffered(), + ); + } + + try testing.expectEqual(@as(usize, 0), t.screens.active.kitty_images.images.count()); + try testing.expectEqual(@as(usize, 0), t.screens.active.kitty_images.placements.count()); +} + +test "kittygfx conflicting identifiers are rejected before mutation" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Store an image so a buggy put would succeed and mutate placement state. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Directly constructed commands must receive the same validation as + // commands produced by the parser. + { + const cmd: Command = .{ .control = .{ .display = .{ + .image_id = 1, + .image_number = 2, + .placement_id = 7, + .cursor_movement = .none, + } } }; + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + try testing.expectEqual(@as(u32, 2), resp.image_number); + try testing.expectEqual(@as(u32, 7), resp.placement_id); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + } + + // Add a real placement so a buggy delete would remove it. + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=7,C=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + } + + { + const cmd = try command.Parser.parseString( + alloc, + "a=d,d=i,i=1,I=2,p=7", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + } + + // q=2 suppresses the required error response but not the validation. + { + const cmd = try command.Parser.parseString( + alloc, + "a=d,d=i,i=1,I=2,p=7,q=2", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + } +} + +test "kittygfx chunked success response uses initial identifiers" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=2,I=93,p=7,m=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + + { + const cmd = try command.Parser.parseString(alloc, "m=0;AAAA"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + try testing.expectEqual(@as(u32, 93), resp.image_number); + try testing.expectEqual(@as(u32, 7), resp.placement_id); + + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try resp.encode(&writer); + try testing.expectEqualStrings( + "\x1b_Gi=1,I=93,p=7;OK\x1b\\", + writer.buffered(), + ); + } +} + +test "kittygfx chunked error response uses initial identifiers" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=41,p=7,m=1;AA==", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + + { + const cmd = try command.Parser.parseString(alloc, "m=0;AA=="); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(u32, 41), resp.id); + try testing.expectEqual(@as(u32, 7), resp.placement_id); + try testing.expectEqualStrings("EINVAL: invalid data", resp.message); + } +} + test "kittygfx more chunks with q=1" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); // Initial chunk has q=1 @@ -407,7 +1357,7 @@ test "kittygfx more chunks with q=1" { "a=T,f=24,t=d,i=1,s=1,v=2,c=10,r=1,m=1,q=1;////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } @@ -418,7 +1368,7 @@ test "kittygfx more chunks with q=1" { "m=0;////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } } @@ -426,8 +1376,9 @@ test "kittygfx more chunks with q=1" { test "kittygfx more chunks with q=0" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); // Initial chunk has q=0 @@ -437,7 +1388,7 @@ test "kittygfx more chunks with q=0" { "a=t,f=24,t=d,s=1,v=2,c=10,r=1,m=1,i=1,q=0;////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } @@ -448,7 +1399,7 @@ test "kittygfx more chunks with q=0" { "m=0;////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(resp.ok()); } } @@ -456,8 +1407,9 @@ test "kittygfx more chunks with q=0" { test "kittygfx more chunks with chunk increasing q" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); // Initial chunk has q=0 @@ -467,7 +1419,7 @@ test "kittygfx more chunks with chunk increasing q" { "a=t,f=24,t=d,s=1,v=2,c=10,r=1,m=1,i=1,q=0;////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } @@ -478,16 +1430,93 @@ test "kittygfx more chunks with chunk increasing q" { "m=0,q=1;////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } } +test "kittygfx delete aborts chunked image load" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Begin a two-chunk RGB image, then interrupt it with a delete. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=2,i=1,m=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expect(storage.loading != null); + + { + const cmd = try command.Parser.parseString(alloc, "a=d"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expect(storage.loading == null); + + // A fresh chunked upload must start from empty state after the delete. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=2,i=1,m=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + { + const cmd = try command.Parser.parseString(alloc, "m=0;AAAA"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 6), storage.imageById(1).?.data.len()); +} + +test "kittygfx uppercase id delete preserves image when placement does not match" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Store an unplaced 1x1 RGB image. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Uppercase deletion may free data only if the named placement matched. + { + const cmd = try command.Parser.parseString( + alloc, + "a=d,d=I,i=1,p=7", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + + try testing.expect(storage.imageById(1) != null); +} + test "kittygfx default format is rgba" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); const cmd = try command.Parser.parseString( @@ -495,7 +1524,7 @@ test "kittygfx default format is rgba" { "a=t,t=d,i=1,s=1,v=2,c=10,r=1;///////////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(resp.ok()); const storage = &t.screens.active.kitty_images; @@ -506,8 +1535,9 @@ test "kittygfx default format is rgba" { test "kittygfx test valid u32 (expect invalid image ID)" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); const cmd = try command.Parser.parseString( @@ -515,7 +1545,7 @@ test "kittygfx test valid u32 (expect invalid image ID)" { "a=p,i=4294967295", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(!resp.ok()); try testing.expectEqual(resp.message, "ENOENT: image not found"); } @@ -523,8 +1553,9 @@ test "kittygfx test valid u32 (expect invalid image ID)" { test "kittygfx test valid i32 (expect invalid image ID)" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); const cmd = try command.Parser.parseString( @@ -532,7 +1563,7 @@ test "kittygfx test valid i32 (expect invalid image ID)" { "a=p,i=1,z=-2147483648", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(!resp.ok()); try testing.expectEqual(resp.message, "ENOENT: image not found"); } @@ -540,8 +1571,9 @@ test "kittygfx test valid i32 (expect invalid image ID)" { test "kittygfx no response with no image ID or number" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); { @@ -550,7 +1582,7 @@ test "kittygfx no response with no image ID or number" { "a=t,f=24,t=d,s=1,v=2,c=10,r=1,i=0,I=0;////////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } } @@ -558,8 +1590,9 @@ test "kittygfx no response with no image ID or number" { test "kittygfx no response with no image ID or number load and display" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); { @@ -568,16 +1601,17 @@ test "kittygfx no response with no image ID or number load and display" { "a=T,f=24,t=d,s=1,v=2,c=10,r=1,i=0,I=0;////////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } } test "kittygfx retransmit same id gets fresh image generation" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); const storage = &t.screens.active.kitty_images; @@ -588,7 +1622,7 @@ test "kittygfx retransmit same id gets fresh image generation" { "a=t,t=d,f=24,i=1,s=1,v=2;////////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(resp.ok()); } const gen1 = storage.imageById(1).?.generation; @@ -604,7 +1638,7 @@ test "kittygfx retransmit same id gets fresh image generation" { "a=t,t=d,f=24,i=1,s=1,v=2;AAAAAAAA", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(resp.ok()); } const gen2 = storage.imageById(1).?.generation; @@ -612,11 +1646,134 @@ test "kittygfx retransmit same id gets fresh image generation" { try testing.expectEqual(gen2, storage.generation); } +test "kittygfx retransmit same id removes existing placements" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + const tracked = t.screens.active.pages.countTrackedPins(); + + // Transmit and display an image, then add anonymous and named placements. + // Multiple anonymous a=p placements for one image are explicitly valid. + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,t=d,f=24,i=1,s=1,v=2,C=1;////////", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,C=1"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=7,C=1"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + try testing.expectEqual(@as(usize, 3), storage.placements.count()); + try testing.expectEqual( + tracked + 3, + t.screens.active.pages.countTrackedPins(), + ); + + // Retransmitting replaces the image and must delete every old placement. + // Plain a=t creates no replacement placement of its own. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,t=d,f=24,i=1,s=1,v=2;AAAAAAAA", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); + + // a=T creates one new placement after deleting the previous image and + // placements, so repeated redraws remain bounded at one placement. + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,t=d,f=24,i=1,s=1,v=2,C=1;////////", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,t=d,f=24,i=1,s=1,v=2,C=1;AAAAAAAA", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + try testing.expectEqual( + tracked + 1, + t.screens.active.pages.countTrackedPins(), + ); +} + +test "kittygfx retransmit same id removes image on first chunk" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + const tracked = t.screens.active.pages.countTrackedPins(); + + // Store and display the old image. + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,t=d,f=24,i=1,s=1,v=2,C=1;////////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expect(storage.imageById(1) != null); + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + try testing.expectEqual( + tracked + 1, + t.screens.active.pages.countTrackedPins(), + ); + + // Starting a replacement for the same explicit ID removes the old image + // and placements before the replacement's final chunk arrives. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,t=d,f=24,i=1,s=1,v=2,m=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expect(storage.loading != null); + try testing.expect(storage.imageById(1) == null); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + test "kittygfx delete then retransmit same id gets fresh generation" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); const storage = &t.screens.active.kitty_images; @@ -628,7 +1785,7 @@ test "kittygfx delete then retransmit same id gets fresh generation" { "a=T,t=d,f=24,i=1,s=1,v=2,c=1,r=1;////////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(resp.ok()); } const gen1 = storage.imageById(1).?.generation; @@ -636,7 +1793,7 @@ test "kittygfx delete then retransmit same id gets fresh generation" { { const cmd = try command.Parser.parseString(alloc, "a=d,d=A"); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd); + const resp = execute(io, alloc, &t, &cmd); try testing.expect(resp == null); } try testing.expect(storage.imageById(1) == null); @@ -649,10 +1806,1798 @@ test "kittygfx delete then retransmit same id gets fresh generation" { "a=t,t=d,f=24,i=1,s=1,v=2;////////", ); defer cmd.deinit(alloc); - const resp = execute(alloc, &t, &cmd).?; + const resp = execute(io, alloc, &t, &cmd).?; try testing.expect(resp.ok()); } const gen2 = storage.imageById(1).?.generation; try testing.expect(gen2 > gen1); try testing.expect(gen2 > gen_delete); } + +test "kittygfx display clamps cell offsets" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.width_px = 50; // 10 px per col + t.height_px = 100; // 20 px per row + + const cmd = try command.Parser.parseString( + alloc, + "a=T,t=d,f=24,i=1,s=1,v=1,c=2,r=1,X=99,Y=99,C=1;AAAA", + ); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + + const storage = &t.screens.active.kitty_images; + var it = storage.placements.iterator(); + const placement = it.next().?.value_ptr; + try testing.expectEqual(@as(u32, 9), placement.x_offset); + try testing.expectEqual(@as(u32, 19), placement.y_offset); + + const actual = placement.pixelSize(storage.imageById(1).?, &t); + try testing.expectEqual(@as(u32, 11), actual.width); + try testing.expectEqual(@as(u32, 1), actual.height); +} + +test "kittygfx placement bounds cursor movement for untrusted dimensions" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString( + alloc, + "a=T,t=d,f=24,i=1,s=1,v=1,c=4294967295,r=4294967295;////", + ); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(usize, 1), t.screens.active.kitty_images.placements.count()); + // Reaching the bottom takes four rows, then scrolling is capped to one + // screen (five rows), matching Kitty's bounded screen-scroll behavior. + try testing.expectEqual(@as(usize, 10), t.screens.active.pages.scrollbar().total); +} + +test "kittygfx placement moves cursor past a tall image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Load a one-pixel RGB image, then place it over the full width and eight + // rows. Eight rows are taller than the screen but still within Kitty's + // scroll budget. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,t=d,f=24,i=1,s=1,v=1;////", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=p,i=1,p=1,c=5,r=8", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + + // A subsequent placement begins immediately after the first one instead + // of overlapping it at the old one-screen movement cap. + { + const cmd = try command.Parser.parseString( + alloc, + "a=p,i=1,p=2,C=1", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + + const storage = &t.screens.active.kitty_images; + const first = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const second = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }).?; + const first_pin = switch (first.location) { + .pin => |pin| pin, + .virtual, .relative => unreachable, + }; + const second_pin = switch (second.location) { + .pin => |pin| pin, + .virtual, .relative => unreachable, + }; + const first_y = t.screens.active.pages.pointFromPin( + .screen, + first_pin.*, + ).?.screen.y; + const second_y = t.screens.active.pages.pointFromPin( + .screen, + second_pin.*, + ).?.screen.y; + try testing.expectEqual(first_y + 8, second_y); +} + +test "kittygfx unknown format responds with EINVAL" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=42,t=d,i=31,s=1,v=1;AAAA", + ); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(u32, 31), resp.id); + try testing.expectEqualStrings("EINVAL: unsupported format", resp.message); + try testing.expectEqual( + @as(usize, 0), + t.screens.active.kitty_images.images.count(), + ); +} + +test "kittygfx unknown format on query responds with EINVAL" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString( + alloc, + "a=q,f=42,t=d,i=31,s=1,v=1;AAAA", + ); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(@as(u32, 31), resp.id); + try testing.expectEqualStrings("EINVAL: unsupported format", resp.message); +} + +test "kittygfx zero format is rgba" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Kitty treats f=0 as an absent f, i.e. RGBA. + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=0,t=d,i=1,s=1,v=2,c=10,r=1;///////////", + ); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + + const img = t.screens.active.kitty_images.imageById(1).?; + try testing.expectEqual(command.Transmission.Format.rgba, img.format); +} + +test "kittygfx unknown format with q=3 has no response" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // q above 2 is out of range in the spec but Kitty suppresses + // everything for anything above 1, so we must still parse it. + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=42,t=d,i=31,q=3,s=1,v=1;AAAA", + ); + defer cmd.deinit(alloc); + + try testing.expect(execute(io, alloc, &t, &cmd) == null); +} + +test "kittygfx out of range display keys are tolerated" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,f=24,t=d,i=31,s=1,v=1,C=2,U=2;AAAA", + ); + defer cmd.deinit(alloc); + + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 31), resp.id); + } + + // U=2 must behave like U=1, so the placement is virtual. + const storage = &t.screens.active.kitty_images; + var it = storage.placements.iterator(); + const entry = it.next().?; + try testing.expect(entry.value_ptr.location == .virtual); +} + +test "kittygfx number-based transmission assigns smallest free id" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Empty storage: the first free ID is 1, as in Kitty. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,I=42;/wAA", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + try testing.expectEqual(@as(u32, 42), resp.image_number); + } + + // Occupy ID 2 explicitly; the next number gets 3. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=2;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,I=43;/wAA", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 3), resp.id); + } + + // Deleting ID 1 opens a gap that the next number fills. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=I,i=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,I=44;/wAA", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + } + + try testing.expectEqual(@as(usize, 3), storage.images.count()); + try testing.expectEqual(@as(u32, 44), storage.imageById(1).?.number); + try testing.expectEqual(@as(u32, 0), storage.imageById(2).?.number); + try testing.expectEqual(@as(u32, 43), storage.imageById(3).?.number); +} + +test "kittygfx number-based id assignment does not replace client image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // A client stores and places a red pixel on the ID the old wrapping + // counter would assign first. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=2147483647;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=2147483647,C=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // A number-based transmission must not collide with it. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,I=42;AAD/", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + } + + // The client's image and placement are untouched. + try testing.expectEqual(@as(usize, 2), storage.images.count()); + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + try testing.expectEqualSlices( + u8, + &.{ 255, 0, 0 }, + storage.imageById(2147483647).?.data.bytes().?, + ); +} + +test "kittygfx implicit id assignment does not replace client image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // A client stores and places a red pixel on the ID the implicit + // counter assigns first. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=2147483647;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=2147483647,C=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Transmit without an ID or number: no response, and the counter + // skips over the in-use ID instead of replacing that image. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1;AAD/", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + + try testing.expectEqual(@as(usize, 2), storage.images.count()); + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + try testing.expectEqualSlices( + u8, + &.{ 255, 0, 0 }, + storage.imageById(2147483647).?.data.bytes().?, + ); + const implicit = storage.imageById(2147483648).?; + try testing.expect(implicit.metadata.implicit_id); + try testing.expectEqualSlices(u8, &.{ 0, 0, 255 }, implicit.data.bytes().?); +} + +test "kittygfx relative placement with missing parent image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // The parent image does not exist: the placement must be rejected + // with ENOPARENT, nothing may be created, and the cursor must not + // move (a relative placement never moves the cursor, and a failed + // one certainly must not). + { + const cmd = try command.Parser.parseString( + alloc, + "a=p,i=1,p=1,P=42,Q=1,H=2,V=2", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "ENOPARENT: parent image not found", + resp.message, + ); + } + + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expectEqual(0, t.screens.active.cursor.x); + try testing.expectEqual(0, t.screens.active.cursor.y); +} + +test "kittygfx relative placement with missing parent placement" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=t,f=24,s=1,v=1,i=2;AAAA", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // The parent image exists but has no placements at all. + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,P=2"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "ENOPARENT: parent placement not found", + resp.message, + ); + } + + // The parent image has a placement, but not the requested one. + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=2,p=1,C=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,P=2,Q=9"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "ENOPARENT: parent placement not found", + resp.message, + ); + } + + try testing.expectEqual(@as(usize, 1), storage.placements.count()); +} + +test "kittygfx relative placement cannot parent itself" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Explicitly via Q, and implicitly when the Q=0 fallback selects + // the placement being replaced. + for ([_][]const u8{ + "a=p,i=1,p=1,P=1,Q=1", + "a=p,i=1,p=1,P=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "EINVAL: placement cannot be its own parent", + resp.message, + ); + } + + // The original placement must be untouched. + const storage = &t.screens.active.kitty_images; + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + try testing.expect(p.location == .pin); +} + +test "kittygfx relative placement cycle" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + "a=p,i=1,p=2,P=1,Q=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Replacing placement 1 with a parent of placement 2 would create + // the cycle 1 -> 2 -> 1. + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=1,P=1,Q=2"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "ECYCLE: parent chain creates a cycle", + resp.message, + ); + } + + // The original placement must be untouched, keeping the stored + // chains acyclic. + const storage = &t.screens.active.kitty_images; + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + try testing.expect(p.location == .pin); +} + +test "kittygfx relative placement chain depth limit" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Chains of up to parent_chain_limit (8) links must work: these + // placements form the chain 9 -> 8 -> ... -> 2 -> 1. + for (2..10) |id| { + var buf: [64]u8 = undefined; + const cmd = try command.Parser.parseString( + alloc, + try std.fmt.bufPrint(&buf, "a=p,i=1,p={},P=1,Q={}", .{ id, id - 1 }), + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // One more link exceeds the limit. + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=10,P=1,Q=9"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "ETOODEEP: parent chain too deep", + resp.message, + ); + } + + const storage = &t.screens.active.kitty_images; + try testing.expectEqual(@as(usize, 9), storage.placements.count()); +} + +test "kittygfx relative placement does not move cursor" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // C is left at its default (move after) on the relative placement + // but it must never move the cursor. + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + "a=p,i=1,p=2,P=1,Q=1,H=3,V=2,c=2,r=2", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(0, t.screens.active.cursor.x); + try testing.expectEqual(0, t.screens.active.cursor.y); + + // The stored placement carries the parent link and offsets. + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }).?; + const rel = p.location.relative; + try testing.expect(rel.parent.eql(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + })); + try testing.expectEqual(@as(i32, 3), rel.horizontal_offset); + try testing.expectEqual(@as(i32, 2), rel.vertical_offset); +} + +test "kittygfx virtual placement with parent rejected before image lookup" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Kitty rejects U=1 + P= before checking that the image exists, + // so this must not be ENOENT. + const cmd = try command.Parser.parseString(alloc, "a=p,i=42,U=1,P=1"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "EINVAL: virtual placement cannot refer to a parent", + resp.message, + ); +} + +test "kittygfx deleting a parent deletes relative placements transitively" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Root (pin) <- child <- grandchild + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + "a=p,i=1,p=2,P=1,Q=1", + "a=p,i=1,p=3,P=1,Q=2", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 3), storage.placements.count()); + + // Deleting the middle placement takes the grandchild with it but + // leaves the root. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=i,i=1,p=2"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + try testing.expect(storage.placements.contains(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + })); + + // Deleting the root removes the remaining placement, and the + // image itself is retained (lowercase delete). + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=i,i=1,p=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expect(storage.imageById(1) != null); +} + +test "kittygfx retransmitting parent image deletes relative placements" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Image 2's placement is relative to image 1's placement. + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=t,f=24,s=1,v=1,i=2;AAAA", + "a=p,i=1,p=1,C=1", + "a=p,i=2,p=1,P=1,Q=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 2), storage.placements.count()); + + // Retransmitting image 1 removes its placements, which orphans + // and removes image 2's placement too. Image 2 is left without + // any placement so it is freed as well: retransmission deletes + // with uppercase semantics, and kitty also removes an image whose + // last placement died from a broken parent chain. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;AAAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expect(storage.imageById(2) == null); +} + +test "kittygfx relative placement parent fallback picks lowest external id" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=t,f=24,s=1,v=1,i=2;AAAA", + "a=p,i=1,p=7,C=1", + "a=p,i=1,p=3,C=1", + "a=p,i=2,P=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + var it = storage.placements.iterator(); + const rel = while (it.next()) |entry| { + if (entry.key_ptr.image_id == 2) break entry.value_ptr.location.relative; + } else return error.PlacementNotFound; + try testing.expect(rel.parent.eql(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 3 }, + })); +} + +test "kittygfx placements created after a full reset are retained" { + // Regression test: Screen.reset reuses the cursor's tracked pin + // but PageList.reset marked it garbage. Placements copy the cursor + // pin, so every placement created after a reset was born garbage + // and silently swept by the next placement command. + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 24, .cols = 80 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + t.fullReset(); + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + "a=p,i=1,p=2,C=1", + "a=p,i=1,p=3,P=1,Q=2", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 3), storage.placements.count()); +} + +test "kittygfx relative placement with pruned parent is ENOPARENT" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // The parent's tracked content is pruned from history but the + // placement hasn't been swept yet. The put must reap it and answer + // ENOPARENT rather than storing an orphan against it. + const parent = storage.placements.getPtr(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + parent.location.pin.garbage = true; + + { + const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=2,P=1,Q=1"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings( + "ENOPARENT: parent placement not found", + resp.message, + ); + } + try testing.expectEqual(@as(usize, 0), storage.placements.count()); +} + +test "kittygfx uppercase delete frees image of cascaded placements" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + for ([_][]const u8{ + "a=t,f=24,s=1,v=1,i=1;AAAA", + "a=p,i=1,p=1,C=1", + "a=p,i=1,p=2,P=1,Q=1", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // The uppercase delete only matches placement 1. The cascade + // removes placement 2, leaving the image without placements, so + // the image must be freed too. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=I,i=1,p=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expect(storage.imageById(1) == null); +} + +// Animation tests frequently start from a 1x1 RGB red image with +// id=1 ("/wAA" is FF0000). Composition converts images to RGBA, so +// after the first frame command the base data is FF0000FF. + +test "kittygfx animation: new frame with default gap responds with frame number" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Transmit a 1x1 RGB blue frame ("AAD/" is 0000FF). + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1;AAD/", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + try testing.expectEqual(@as(u32, 2), resp.frame); + + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try resp.encode(&writer); + try testing.expectEqualStrings("\x1b_Gi=1,r=2;OK\x1b\\", writer.buffered()); + + const img = storage.imagePtrByIdOrNumber(1, 0).?; + try testing.expectEqual(command.Transmission.Format.rgba, img.format); + try testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, img.data.bytes().?); + + const anim = img.animation.?; + try testing.expectEqual(@as(u32, 2), anim.frameCount()); + try testing.expectEqual(@as(u32, 0), anim.root_gap_ms); + try testing.expectEqual(@as(u32, 40), anim.frames.items[0].gap_ms); + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, anim.frames.items[0].data); + + // The displayed frame is still the root: renderData is the base. + try testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, img.renderData().bytes().?); + + // Frame bytes count against the storage total. + try testing.expectEqual(@as(usize, 8), storage.total_bytes); +} + +test "kittygfx animation: frame gap normalization on create" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + for ([_][]const u8{ + "a=f,i=1,f=24,s=1,v=1,z=100;AAD/", + "a=f,i=1,f=24,s=1,v=1,z=-5;AAD/", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqual(@as(u32, 100), anim.frames.items[0].gap_ms); + try testing.expectEqual(@as(u32, 0), anim.frames.items[1].gap_ms); +} + +test "kittygfx animation: background fill and offset composition" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // 2x1 RGB white image ("////////" is FFFFFF FFFFFF). + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=2,v=1,i=1;////////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // New frame: 1x1 RGB white transmitted at x=1 over an opaque red + // background (Y=4278190335 is 0xff0000ff, R in the MSB). + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1,x=1,Y=4278190335;////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqualSlices( + u8, + &.{ 255, 0, 0, 255, 255, 255, 255, 255 }, + anim.frames.items[0].data, + ); +} + +test "kittygfx animation: create from base frame with overwrite" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Frame 2 based on the root (c=1) with a semi-transparent blue + // pixel ("AAD/gA==" is 0000FF80) in overwrite mode: the source + // replaces the canvas including alpha. + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=32,s=1,v=1,c=1,X=1;AAD/gA==", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 128 }, anim.frames.items[0].data); +} + +test "kittygfx animation: alpha blend composes over base frame" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Blend a fully opaque blue pixel over the root: alpha blending + // an opaque source is equivalent to a copy. + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=32,s=1,v=1,c=1;AAD//w==", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Blend a fully transparent pixel over the root: the canvas is + // unchanged (still the red base). + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=32,s=1,v=1,c=1;AAD/AA==", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, anim.frames.items[0].data); + try testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, anim.frames.items[1].data); +} + +test "kittygfx animation: edit root frame bumps generation" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + const gen1 = storage.imagePtrByIdOrNumber(1, 0).?.generation; + + // r=1 edits the root frame in place. The root is the displayed + // frame so the image generation must change. + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1,r=1;AAD/", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.frame); + + const img = storage.imagePtrByIdOrNumber(1, 0).?; + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.data.bytes().?); + try testing.expect(img.generation > gen1); +} + +test "kittygfx animation: edit frame gap without data change" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Create frame 2, then edit it with z=-1: gap becomes gapless. + // Editing with z=0 leaves the gap unchanged (no 40ms default). + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1,z=77;AAD/", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1,r=2;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqual(@as(u32, 77), anim.frames.items[0].gap_ms); + + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1,r=2,z=-1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(u32, 0), anim.frames.items[0].gap_ms); +} + +test "kittygfx animation: frame errors" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + const cases = [_]struct { + input: []const u8, + message: []const u8, + }{ + // Unknown image. + .{ + .input = "a=f,i=9,f=24,s=1,v=1;AAD/", + .message = "ENOENT: image not found", + }, + // Frame bigger than the image. + .{ + .input = "a=f,i=1,f=24,s=2,v=1;////////", + .message = "EINVAL: frame dimensions exceed image", + }, + // Nonexistent base frame. + .{ + .input = "a=f,i=1,f=24,s=1,v=1,c=5;AAD/", + .message = "EINVAL: base frame not found", + }, + // Insufficient data for the declared rectangle. + .{ + .input = "a=f,i=1,f=24,s=1,v=1;AA==", + .message = "ENODATA: insufficient data", + }, + }; + for (cases) |case| { + const cmd = try command.Parser.parseString(alloc, case.input); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings(case.message, resp.message); + } + + // None of the failures may have created a frame. + const storage = &t.screens.active.kitty_images; + const img = storage.imagePtrByIdOrNumber(1, 0).?; + if (img.animation) |anim| { + try testing.expectEqual(@as(usize, 0), anim.frames.items.len); + } +} + +test "kittygfx animation: excess frame data is truncated" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Six bytes for a 1x1 RGB frame: Kitty tolerates the excess. + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1;AAD/////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, anim.frames.items[0].data); +} + +test "kittygfx animation: chunked frame transmission" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // 2x1 RGB white image. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=2,v=1,i=1;////////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Transmit a 2x1 frame in two chunks of one pixel each. The + // chunks repeat a=f per the protocol. No response until the + // final chunk. + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=2,v=1,z=60,m=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expect(storage.loading != null); + { + const cmd = try command.Parser.parseString(alloc, "a=f,m=0;AAD/"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 1), resp.id); + try testing.expectEqual(@as(u32, 2), resp.frame); + } + try testing.expect(storage.loading == null); + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqual(@as(u32, 60), anim.frames.items[0].gap_ms); + try testing.expectEqualSlices( + u8, + &.{ 255, 0, 0, 255, 0, 0, 255, 255 }, + anim.frames.items[0].data, + ); +} + +test "kittygfx animation: chunked frame continuation without a=f" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=2,v=1,i=1;////////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // The spec requires chunks to repeat a=f, but a bare continuation + // (which parses as a transmit action) must still continue the + // frame load rather than turn into an image transmission. + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=2,v=1,m=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + { + const cmd = try command.Parser.parseString(alloc, "m=0;AAD/"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 2), resp.frame); + } + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqual(@as(usize, 1), anim.frames.items.len); +} + +test "kittygfx animation: control command sets gap current state and loops" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1;AAD/", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + const img = storage.imagePtrByIdOrNumber(1, 0).?; + const gen1 = img.generation; + + // One command can set several things: the root frame's gap + // (r=1,z=50), the current frame (c=2), the state (s=3, running), + // and the loop count (v=3, meaning two loops). Successful a=a + // commands never respond. + const cmd = try command.Parser.parseString( + alloc, + "a=a,i=1,r=1,z=50,c=2,s=3,v=3", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + + const anim = img.animation.?; + try testing.expectEqual(@as(u32, 50), anim.root_gap_ms); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expectEqual(animation.Animation.State.running, anim.state); + try testing.expectEqual(@as(u32, 2), anim.max_loops); + + // Changing the current frame changes the displayed content. + try testing.expect(img.generation > gen1); + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.renderData().bytes().?); +} + +test "kittygfx animation: control command ignores invalid values" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Out-of-range frame numbers and s values are silently ignored. + const cmd = try command.Parser.parseString( + alloc, + "a=a,i=1,r=9,z=50,c=9,s=7", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqual(@as(u32, 0), anim.root_gap_ms); + try testing.expectEqual(@as(u32, 0), anim.current_index); + try testing.expectEqual(animation.Animation.State.stopped, anim.state); +} + +test "kittygfx animation: control command missing image responds ENOENT" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString(alloc, "a=a,i=9,s=3"); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings("ENOENT: image not found", resp.message); +} + +test "kittygfx animation: compose frames" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // 2x1 RGB image: red then blue ("/wAAAAD/" is FF0000 0000FF). + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=2,v=1,i=1;/wAAAAD/", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + // Frame 2 starts as a transparent canvas with a white pixel at + // x=0 ("////" is FFFFFF). + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1;////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Compose the root's pixel at (1,0) onto frame 2 at (0,0): + // r=1 is the source frame, c=2 the destination, X/Y the source + // offsets, x/y the destination offsets. + { + const cmd = try command.Parser.parseString( + alloc, + "a=c,i=1,r=1,c=2,w=1,h=1,X=1,x=0", + ); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + try testing.expectEqual(@as(u32, 0), resp.frame); + } + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqualSlices( + u8, + &.{ 0, 0, 255, 255, 0, 0, 0, 0 }, + anim.frames.items[0].data, + ); +} + +test "kittygfx animation: compose current frame bumps generation" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // 2x1 RGB white image; the root frame is the displayed frame. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=2,v=1,i=1;////////", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + const img = storage.imagePtrByIdOrNumber(1, 0).?; + const gen1 = img.generation; + + // a=c works on images without animation state: both frames are + // the root. Copy pixel 0 onto pixel 1. + const cmd = try command.Parser.parseString( + alloc, + "a=c,i=1,r=1,c=1,w=1,h=1,x=1", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + try testing.expect(img.generation > gen1); +} + +test "kittygfx animation: compose errors" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + const cases = [_]struct { + input: []const u8, + message: []const u8, + }{ + .{ + .input = "a=c,i=9,r=1,c=1", + .message = "ENOENT: image not found", + }, + .{ + .input = "a=c,i=1,r=2,c=1", + .message = "ENOENT: source frame not found", + }, + .{ + .input = "a=c,i=1,r=1,c=2", + .message = "ENOENT: destination frame not found", + }, + // 1x1 image: any offset pushes the rect out of bounds. + .{ + .input = "a=c,i=1,r=1,c=1,x=1", + .message = "EINVAL: destination rectangle out of bounds", + }, + .{ + .input = "a=c,i=1,r=1,c=1,X=1", + .message = "EINVAL: source rectangle out of bounds", + }, + // Same frame, same (whole-image) rect: overlap. + .{ + .input = "a=c,i=1,r=1,c=1", + .message = "EINVAL: source and destination rectangles overlap", + }, + }; + for (cases) |case| { + const cmd = try command.Parser.parseString(alloc, case.input); + defer cmd.deinit(alloc); + const resp = execute(io, alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqualStrings(case.message, resp.message); + } +} + +test "kittygfx animation: delete frame promotes root and fixes current" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + // Frames 2 and 3: blue and white. + for ([_][]const u8{ + "a=f,i=1,f=24,s=1,v=1,z=10;AAD/", + "a=f,i=1,f=24,s=1,v=1,z=20;////", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + const total_before = storage.total_bytes; + + // Delete the root frame (r omitted selects it): frame 2 becomes + // the new root, including its gap. Deletes never respond. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + const img = storage.imagePtrByIdOrNumber(1, 0).?; + const anim = img.animation.?; + try testing.expectEqual(@as(u32, 2), anim.frameCount()); + try testing.expectEqual(@as(u32, 10), anim.root_gap_ms); + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.data.bytes().?); + try testing.expectEqual(total_before - 4, storage.total_bytes); + + // Delete a frame number past the end: clamps to the last frame. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1,r=9"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expectEqual(@as(u32, 1), anim.frameCount()); + try testing.expectEqual(total_before - 8, storage.total_bytes); + + // Down to one frame: d=f is now a no-op and the image survives. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expect(storage.imageById(1) != null); +} + +test "kittygfx animation: uppercase frame delete removes non-animated image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + + // Transmit and place: unlike d=I, an uppercase frame delete on a + // non-animated image removes it even though it is placed. + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,f=24,s=1,v=1,i=1,C=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 1), storage.placements.count()); + + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=F,i=1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expect(storage.imageById(1) == null); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + try testing.expectEqual(@as(usize, 0), storage.total_bytes); +} + +test "kittygfx animation: deleting current frame refreshes display" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + for ([_][]const u8{ + "a=f,i=1,f=24,s=1,v=1;AAD/", + "a=f,i=1,f=24,s=1,v=1;////", + "a=a,i=1,c=3", + }) |input| { + const cmd = try command.Parser.parseString(alloc, input); + defer cmd.deinit(alloc); + _ = execute(io, alloc, &t, &cmd); + } + + const img = storage.imagePtrByIdOrNumber(1, 0).?; + const anim = img.animation.?; + try testing.expectEqual(@as(u32, 2), anim.current_index); + const gen1 = img.generation; + + // Deleting the last frame (the current one) clamps the index and + // refreshes the display. + { + const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1,r=3"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + } + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expect(img.generation > gen1); + try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.renderData().bytes().?); +} + +test "kittygfx animation: retransmitting base image resets animation" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1;AAD/", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + try testing.expectEqual(@as(usize, 8), storage.total_bytes); + + // Retransmit the base image: the animation is dropped and the + // frame bytes are credited back. + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + const img = storage.imagePtrByIdOrNumber(1, 0).?; + try testing.expect(img.animation == null); + try testing.expectEqual(@as(usize, 3), storage.total_bytes); +} + +test "kittygfx animation: control negative gap makes frame gapless" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + const storage = &t.screens.active.kitty_images; + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,s=1,v=1,i=1;/wAA", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + { + const cmd = try command.Parser.parseString( + alloc, + "a=f,i=1,f=24,s=1,v=1;AAD/", + ); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd).?.ok()); + } + + const cmd = try command.Parser.parseString(alloc, "a=a,i=1,r=2,z=-1"); + defer cmd.deinit(alloc); + try testing.expect(execute(io, alloc, &t, &cmd) == null); + + const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?; + try testing.expectEqual(@as(u32, 0), anim.frames.items[0].gap_ms); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig index b6f44fac..e411bafe 100644 --- a/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig @@ -6,15 +6,12 @@ const ArenaAllocator = std.heap.ArenaAllocator; const posix = std.posix; const fastmem = @import("../../fastmem.zig"); +const animation = @import("graphics_animation.zig"); const command = @import("graphics_command.zig"); +const kitty_windows = @import("windows.zig"); const PageList = @import("../PageList.zig"); const sys = @import("../sys.zig"); - -const temp_dir = struct { - const TempDir = @import("../../os/TempDir.zig"); - const allocTmpDir = @import("../../os/file.zig").allocTmpDir; - const freeTmpDir = @import("../../os/file.zig").freeTmpDir; -}; +const LimitedAllocator = @import("../../datastruct/main.zig").LimitedAllocator; const log = std.log.scoped(.kitty_gfx); @@ -34,36 +31,75 @@ pub const LoadingImage = struct { image: Image, /// The data that is being built up. - data: std.ArrayListUnmanaged(u8) = .{}, + data: std.ArrayListUnmanaged(u8) = .empty, /// This is non-null when a transmit and display command is given /// so that we display the image after it is fully loaded. display: ?command.Display = null, + /// This is non-null when this load is an animation frame + /// transmission (a=f) rather than a new image. On completion the + /// data is composed into the target image's animation instead of + /// being stored as an image. + frame: ?FrameContext = null, + /// Quiet is the quiet settings for the initial load command. This is /// used if q isn't set on subsequent chunks. quiet: command.Command.Quiet, + /// Response identifiers from the initial load command. Subsequent chunks + /// omit these, so completion responses must use the saved values. + response: command.Response = .{}, + + /// The temporary directory for file transmission (null means that + /// temporary directory transmission is disabled). + temporary_directory: ?[]const u8, + + pub const FrameContext = struct { + /// The frame parameters from the initial a=f command. Chunked + /// continuations only contribute payload bytes; all parameters + /// come from the command that started the load, matching the + /// protocol's requirement that chunks repeat a=f. + cmd: command.AnimationFrameLoading, + + /// The generation of the target image when the load began. + /// A different generation at completion means the image was + /// replaced or evicted mid-transmission and the frame must be + /// discarded rather than composed onto the wrong image. + image_generation: u64, + }; + /// The limits of the Kitty Graphics protocol we should allow. /// /// This can be used to restrict the type of images and other /// parameters for resource or security reasons. Note that depending /// on how libghostty is compiled, some of these may be fully unsupported /// and ignored (e.g. "file" on wasm32-freestanding). - pub const Limits = packed struct { + pub const Limits = struct { file: bool, - temporary_file: bool, + temporary_file: union(enum) { + enabled: struct { + /// The directory to expect temporary files in. + directory: []const u8, + }, + disabled: void, + }, shared_memory: bool, - pub const all: Limits = .{ - .file = true, - .temporary_file = true, - .shared_memory = true, - }; + /// Enables all filesystem-related image transmission mediums. `path` + /// is the temporary directory to expect files in when files are + /// transmitted using said medium. + pub fn allWithTempDir(path: []const u8) Limits { + return .{ + .file = true, + .temporary_file = .{ .enabled = .{ .directory = path } }, + .shared_memory = true, + }; + } pub const direct: Limits = .{ .file = false, - .temporary_file = false, + .temporary_file = .disabled, .shared_memory = false, }; }; @@ -72,6 +108,7 @@ pub const LoadingImage = struct { /// If this is a multi-chunk image, this should only be the FIRST /// chunk. pub fn init( + io: std.Io, alloc: Allocator, cmd: *const command.Command, limits: Limits, @@ -80,6 +117,10 @@ pub const LoadingImage = struct { // These can be overwritten by the data loading process. For example, // PNG loading sets the width/height from the data. const t = cmd.transmission().?; + + // Validated here rather than while parsing so the response can + // carry the image id, matching Kitty's initialize_load_data. + if (t.format_unknown) return error.UnsupportedFormat; var result: LoadingImage = .{ .image = .{ .id = t.image_id, @@ -88,10 +129,20 @@ pub const LoadingImage = struct { .height = t.height, .compression = t.compression, .format = t.format, + .metadata = .{ .transient = t.usage.transient }, }, .display = cmd.display(), .quiet = cmd.quiet, + .response = .{ + .id = t.image_id, + .image_number = t.image_number, + .placement_id = t.placement_id, + }, + .temporary_directory = switch (limits.temporary_file) { + .enabled => |d| d.directory, + .disabled => null, + }, }; // Special case for the direct medium, we just add the chunk directly. @@ -115,7 +166,7 @@ pub const LoadingImage = struct { switch (t.medium) { .direct => unreachable, .file => if (!limits.file) return error.UnsupportedMedium, - .temporary_file => if (!limits.temporary_file) return error.UnsupportedMedium, + .temporary_file => if (limits.temporary_file == .disabled) return error.UnsupportedMedium, .shared_memory => if (!limits.shared_memory) return error.UnsupportedMedium, } } @@ -124,29 +175,18 @@ pub const LoadingImage = struct { if (comptime builtin.os.tag != .windows) { if (std.mem.indexOfScalar(u8, cmd.data, 0) != null) { - // posix.realpath *asserts* that the path does not have - // internal nulls instead of erroring. - log.warn("failed to get absolute path: BadPathName", .{}); + // POSIX paths cannot contain internal nulls. + log.warn("invalid image path: BadPathName", .{}); return error.InvalidData; } } - var abs_buf: [std.fs.max_path_bytes]u8 = undefined; - const path = switch (t.medium) { - .direct => unreachable, // handled above - .file, .temporary_file => posix.realpath(cmd.data, &abs_buf) catch |err| { - log.warn("failed to get absolute path: {}", .{err}); - return error.InvalidData; - }, - .shared_memory => cmd.data, - }; - // Depending on the medium, load the data from the path. switch (t.medium) { .direct => unreachable, // handled above - .file => try result.readFile(.file, alloc, t, path), - .temporary_file => try result.readFile(.temporary_file, alloc, t, path), - .shared_memory => try result.readSharedMemory(alloc, t, path), + .file => try result.readFile(.file, io, alloc, t, cmd.data), + .temporary_file => try result.readFile(.temporary_file, io, alloc, t, cmd.data), + .shared_memory => try result.readSharedMemory(io, alloc, t, cmd.data), } return result; @@ -155,6 +195,7 @@ pub const LoadingImage = struct { /// Reads the data from a shared memory segment. fn readSharedMemory( self: *LoadingImage, + io: std.Io, alloc: Allocator, t: command.Transmission, path: []const u8, @@ -170,12 +211,21 @@ pub const LoadingImage = struct { return error.UnsupportedMedium; } + // POSIX shared memory names must begin with a slash, contain at + // least one character after it, contain no other slashes, and fit + // within NAME_MAX. Some shm_open implementations accept names + // without the leading slash, but the Kitty protocol does not. + if (!validSharedMemoryName(path, posix.NAME_MAX)) { + log.warn("invalid shared memory name", .{}); + return error.InvalidData; + } + // Since we're only supporting posix then max_path_bytes should // be enough to stack allocate the path. var buf: [std.fs.max_path_bytes]u8 = undefined; const pathz = std.fmt.bufPrintZ(&buf, "{s}", .{path}) catch return error.InvalidData; - const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), 0); + const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), @as(u16, 0)); switch (std.posix.errno(fd)) { .SUCCESS => {}, else => |err| { @@ -183,46 +233,34 @@ pub const LoadingImage = struct { return error.InvalidData; }, } - defer _ = std.c.close(fd); + const file: std.Io.File = .{ + .handle = fd, + .flags = .{ .nonblocking = false }, + }; + + defer file.close(io); defer _ = std.c.shm_unlink(pathz); // The size from stat on may be larger than our expected size because // shared memory has to be a multiple of the page size. const stat_size: usize = stat: { - const stat = std.posix.fstat(fd) catch |err| { + const stat = file.stat(io) catch |err| { log.warn("unable to fstat shared memory {s}: {}", .{ path, err }); return error.InvalidData; }; if (stat.size <= 0) return error.InvalidData; - break :stat @intCast(stat.size); - }; - - const expected_size: usize = switch (self.image.format) { - // Png we decode the full data size because later decoding will - // get the proper dimensions and assert validity. - .png => stat_size, - - // For these formats we have a size we must have. - .gray, .gray_alpha, .rgb, .rgba => size: { - const bpp = command.Transmission.formatBpp(self.image.format); - break :size self.image.width * self.image.height * bpp; - }, + break :stat std.math.cast(usize, stat.size) orelse + return error.InvalidData; }; - // Our stat size must be at least the expected size otherwise - // the shared memory data is invalid. - if (stat_size < expected_size) { - log.warn( - "shared memory size too small expected={} actual={}", - .{ expected_size, stat_size }, - ); - return error.InvalidData; - } + // Get the memory range we'll read. Validate it to make sure + // it doesn't overflow. + const range = try self.sharedMemoryRange(t, stat_size); const map = std.posix.mmap( null, stat_size, // mmap always uses the stat size - std.c.PROT.READ, + .{ .READ = true }, std.c.MAP{ .TYPE = .SHARED }, fd, 0, @@ -232,16 +270,63 @@ pub const LoadingImage = struct { }; defer std.posix.munmap(map); - // Our end size always uses the expected size so we cut off the - // padding for mmap alignment. - const start: usize = @intCast(t.offset); - const end: usize = if (t.size > 0) @min( - @as(usize, @intCast(t.offset)) + @as(usize, @intCast(t.size)), - expected_size, - ) else expected_size; - assert(self.data.items.len == 0); - try self.data.appendSlice(alloc, map[start..end]); + try self.data.appendSlice(alloc, map[range.start..range.end]); + } + + const SharedMemoryRange = struct { + start: usize, + end: usize, + }; + + /// Returns the byte range to copy from a shared memory object. + fn sharedMemoryRange( + self: *const LoadingImage, + t: command.Transmission, + stat_size: usize, + ) error{ + InvalidData, + DimensionsTooLarge, + }!SharedMemoryRange { + const expected_size: ?usize = switch (self.image.format) { + // PNG dimensions come from the decoded data. + .png => null, + + // Validate before multiplying because protocol dimensions are + // u32 values and may otherwise overflow in safe builds. + .gray, .gray_alpha, .rgb, .rgba => size: { + if (self.image.width > max_dimension or + self.image.height > max_dimension) + { + return error.DimensionsTooLarge; + } + + const bpp: usize = command.Transmission.formatBpp(self.image.format); + break :size @as(usize, self.image.width) * + @as(usize, self.image.height) * bpp; + }, + }; + + // Get our start offset and validate its within the range of + // the statted data. + const start = std.math.cast(usize, t.offset) orelse + return error.InvalidData; + if (start > stat_size) return error.InvalidData; + + // Validate that our length is within the stat range too. + const available = stat_size - start; + const data_size: usize = if (t.size > 0) + std.math.cast(usize, t.size) orelse return error.InvalidData + else if (self.image.compression == .none and expected_size != null) + expected_size.? + else + available; + if (data_size > max_size or data_size > available) { + return error.InvalidData; + } + + // data_size <= available guarantees this addition cannot overflow. + return .{ .start = start, .end = start + data_size }; } /// Reads the data from a temporary file and returns it. This allocates @@ -251,6 +336,7 @@ pub const LoadingImage = struct { fn readFile( self: *LoadingImage, comptime medium: command.Transmission.Medium, + io: std.Io, alloc: Allocator, t: command.Transmission, path: []const u8, @@ -260,37 +346,78 @@ pub const LoadingImage = struct { else => @compileError("readFile only supports file and temporary_file"), } - // Verify file seems "safe". This is logic copied directly from Kitty, - // mostly. This is really rough but it will catch obvious bad actors. - if (std.mem.startsWith(u8, path, "/proc/") or - std.mem.startsWith(u8, path, "/sys/") or - (std.mem.startsWith(u8, path, "/dev/") and - !std.mem.startsWith(u8, path, "/dev/shm/"))) - { - return error.InvalidData; + // Some Windows paths are dangerous to even open, so the raw path + // is checked before the open. The canonical path of the opened + // file is checked again in validatedFilePath. See kitty_windows + // for what is refused and why. + if (comptime builtin.os.tag == .windows) { + kitty_windows.checkPath(path) catch |err| { + log.warn("invalid image path: {}", .{err}); + return error.InvalidData; + }; } - // Temporary file logic - if (medium == .temporary_file) { - if (!isPathInTempDir(path)) return error.TemporaryFileNotInTempDir; - if (std.mem.indexOf(u8, path, "tty-graphics-protocol") == null) { - return error.TemporaryFileNotNamedCorrectly; + // The canonical path buffer is sized for the longest path the + // platform allows, which is about 96 KiB on Windows, so it is + // heap allocated rather than placed on the stack of whichever + // host thread feeds the stream. It is allocated before the open + // so the deferred temporary file deletion below can still use it. + const abs_buf = try alloc.alloc(u8, std.fs.max_path_bytes); + defer alloc.free(abs_buf); + + // Open our file right away before we do validation. This avoids + // TOCTOU issues. + var file = std.Io.Dir.cwd().openFile( + io, + path, + .{}, + ) catch |err| { + log.warn("failed to open image file: {}", .{err}); + return error.InvalidData; + }; + + // We'll populate a delete path if this is a temporary file. + var delete_path: ?[]const u8 = null; + defer { + file.close(io); + if (delete_path) |p| { + std.Io.Dir.cwd().deleteFile(io, p) catch |err| { + log.warn("failed to delete temporary file: {}", .{err}); + }; } } - defer if (medium == .temporary_file) { - posix.unlink(path) catch |err| { - log.warn("failed to delete temporary file: {}", .{err}); - }; - }; - var file = std.fs.cwd().openFile(path, .{}) catch |err| { - log.warn("failed to open temporary file: {}", .{err}); + // Derive the path from the open handle so the file we validate is the + // exact file we read. Resolving a path before opening it would allow a + // cooperating process to swap a symlink or directory entry in between. + const abs_path = validatedFilePath( + io, + file, + abs_buf, + ) catch |err| { + log.warn("failed to validate image file path: {}", .{err}); return error.InvalidData; }; - defer file.close(); + + // Temporary file logic + if (medium == .temporary_file) { + assert(self.temporary_directory != null); + if (!try isPathInTempDir( + io, + alloc, + self.temporary_directory.?, + abs_path, + )) return error.TemporaryFileNotInTempDir; + if (std.mem.indexOf( + u8, + abs_path, + "tty-graphics-protocol", + ) == null) return error.TemporaryFileNotNamedCorrectly; + delete_path = abs_path; + } // File must be a regular file - if (file.stat()) |stat| { + if (file.stat(io)) |stat| { if (stat.kind != .file) { log.warn("file is not a regular file kind={}", .{stat.kind}); return error.InvalidData; @@ -300,46 +427,96 @@ pub const LoadingImage = struct { return error.InvalidData; } + var buf: [4096]u8 = undefined; + var buf_reader = file.reader(io, &buf); if (t.offset > 0) { - file.seekTo(@intCast(t.offset)) catch |err| { + buf_reader.seekTo(@intCast(t.offset)) catch |err| { log.warn("failed to seek to offset {}: {}", .{ t.offset, err }); return error.InvalidData; }; } - - var buf: [4096]u8 = undefined; - var buf_reader = file.reader(&buf); const reader = &buf_reader.interface; // Read the file var managed: std.ArrayList(u8) = .empty; errdefer managed.deinit(alloc); - const size: usize = if (t.size > 0) @min(t.size, max_size) else max_size; - reader.appendRemaining(alloc, &managed, .limited(size)) catch { - log.warn("failed to read temporary file: {?}", .{buf_reader.err}); - return error.InvalidData; - }; + if (t.size > 0) { + // S is the exact number of bytes to read, not a maximum: + // https://sw.kovidgoyal.net/kitty/graphics-protocol/#local-client + const size = std.math.cast(usize, t.size) orelse + return error.InvalidData; + if (size > max_size) return error.InvalidData; + + // Read exact size + const data = reader.readAlloc(alloc, size) catch |err| { + log.warn("failed to read image file: {}", .{err}); + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + else => error.InvalidData, + }; + }; + managed = .{ .items = data, .capacity = data.len }; + } else { + reader.appendRemaining(alloc, &managed, .limited(max_size)) catch { + log.warn("failed to read image file: {?}", .{buf_reader.err}); + return error.InvalidData; + }; + } // Set our data assert(self.data.items.len == 0); self.data = .{ .items = managed.items, .capacity = managed.capacity }; } + /// Returns the canonical path of an open file after applying the file + /// transmission blocklist. + fn validatedFilePath(io: std.Io, file: std.Io.File, buf: []u8) ![]const u8 { + const path = buf[0..try file.realPath(io, buf)]; + + if (comptime builtin.os.tag == .windows) { + try kitty_windows.checkCanonicalPath(path); + return path; + } + + // This is logic copied directly from Kitty, mostly. This is really + // rough but it will catch obvious bad actors. + if (std.mem.startsWith(u8, path, "/proc/") or + std.mem.startsWith(u8, path, "/sys/") or + (std.mem.startsWith(u8, path, "/dev/") and + !std.mem.startsWith(u8, path, "/dev/shm/"))) + { + return error.InvalidData; + } + + return path; + } + /// Returns true if path appears to be in a temporary directory. /// Copies logic from Kitty. - fn isPathInTempDir(path: []const u8) bool { - if (std.mem.startsWith(u8, path, "/tmp")) return true; - if (std.mem.startsWith(u8, path, "/dev/shm")) return true; - const dir = temp_dir.allocTmpDir(std.heap.page_allocator) catch return false; - defer temp_dir.freeTmpDir(std.heap.page_allocator, dir); - if (std.mem.startsWith(u8, path, dir)) return true; + fn isPathInTempDir( + io: std.Io, + alloc: Allocator, + dir: []const u8, + path: []const u8, + ) Allocator.Error!bool { + if (isPathInDir("/tmp", path)) return true; + if (isPathInDir("/dev/shm", path)) return true; + if (isPathInDir(dir, path)) return true; // The temporary dir is sometimes a symlink. On macOS for - // example /tmp is /private/var/... - var buf: [std.fs.max_path_bytes]u8 = undefined; - if (posix.realpath(dir, &buf)) |real_dir| { - if (std.mem.startsWith(u8, path, real_dir)) return true; - } else |_| {} + // example /tmp is /private/var/... On Windows the directory a + // host passes (typically GetTempPath output) regularly differs + // from the canonical path in case or uses 8.3 short names, and + // resolving it covers both. The buffer is heap allocated for + // the reason given in readFile. + const buf = try alloc.alloc(u8, std.fs.max_path_bytes); + defer alloc.free(buf); + const real_dir = buf[0 .. std.Io.Dir.cwd().realPathFile( + io, + dir, + buf, + ) catch return false]; + if (isPathInDir(real_dir, path)) return true; return false; } @@ -389,11 +566,23 @@ pub const LoadingImage = struct { if (img.width == 0 or img.height == 0) return error.DimensionsRequired; if (img.width > max_dimension or img.height > max_dimension) return error.DimensionsTooLarge; - // Data length must be what we expect + // Data length must be what we expect. const bpp = command.Transmission.formatBpp(img.format); const expected_len = img.width * img.height * bpp; const actual_len = self.data.items.len; - if (actual_len != expected_len) { + if (self.frame != null) { + // Kitty allows animation frames to exceed their expected length + // and just truncates it. Not sure if thats expected but lets + // allow it too. + if (actual_len < expected_len) { + std.log.warn( + "insufficient frame data image id={} expected_len={} actual_len={}", + .{ img.id, expected_len, actual_len }, + ); + return error.InsufficientData; + } + self.data.items.len = expected_len; + } else if (actual_len != expected_len) { std.log.warn( "unexpected length image id={} width={} height={} bpp={} expected_len={} actual_len={}", .{ img.id, img.width, img.height, bpp, expected_len, actual_len }, @@ -403,7 +592,7 @@ pub const LoadingImage = struct { // Everything looks good, copy the image data over. var result = self.image; - result.data = try self.data.toOwnedSlice(alloc); + result.data = .{ .complete = try self.data.toOwnedSlice(alloc) }; errdefer result.deinit(alloc); self.image = .{}; return result; @@ -411,7 +600,7 @@ pub const LoadingImage = struct { /// Debug function to write the data to a file. This is useful for /// capturing some test data for unit tests. - pub fn debugDump(self: LoadingImage) !void { + pub fn debugDump(io: std.Io, self: LoadingImage) !void { if (comptime builtin.mode != .Debug) @compileError("debugDump in non-debug"); var buf: [1024]u8 = undefined; @@ -426,9 +615,9 @@ pub const LoadingImage = struct { self.image.id, }, ); - const cwd = std.fs.cwd(); - const f = try cwd.createFile(filename, .{}); - defer f.close(); + const cwd = std.Io.Dir.cwd(); + const f = try cwd.createFile(io, filename, .{}); + defer f.close(io); const writer = f.writer(); try writer.writeAll(self.data.items); @@ -470,14 +659,20 @@ pub const LoadingImage = struct { const decode_png_fn = sys.decode_png orelse return error.UnsupportedFormat; + + var limited: LimitedAllocator = .init(alloc, max_size); + const decode_alloc = limited.allocator(); const result = decode_png_fn( - alloc, + decode_alloc, self.data.items, ) catch |err| switch (err) { error.InvalidData => return error.InvalidData, - error.OutOfMemory => return error.OutOfMemory, + error.OutOfMemory => if (limited.limit_exceeded) + return error.InvalidData + else + return error.OutOfMemory, }; - defer alloc.free(result.data); + defer decode_alloc.free(result.data); if (result.data.len > max_size) { log.warn("png image too large size={} max_size={}", .{ result.data.len, max_size }); @@ -486,7 +681,7 @@ pub const LoadingImage = struct { // Replace our data self.data.deinit(alloc); - self.data = .{}; + self.data = .empty; try self.data.ensureUnusedCapacity(alloc, result.data.len); try self.data.appendSlice(alloc, result.data[0..result.data.len]); @@ -497,13 +692,13 @@ pub const LoadingImage = struct { } }; -/// Image represents a single fully loaded image. +/// Image represents a single image whose metadata is fully known. /// -/// The image data is always fully decoded raw pixels: loading inflates -/// any zlib-compressed payload and decodes PNG into RGBA before an image -/// is completed, so `compression` is always `.none` and `format` is -/// never `.png` for a stored image, and `data.len` always equals -/// `width * height * bytes-per-pixel`. +/// Complete image data is always fully decoded raw pixels: loading inflates +/// any zlib-compressed payload and decodes PNG into RGBA before an image is +/// completed, so `compression` is always `.none` and `format` is never `.png` +/// for a stored image. Pending image data reserves the exact decoded byte +/// length that will be attached later. pub const Image = struct { id: u32 = 0, number: u32 = 0, @@ -511,7 +706,23 @@ pub const Image = struct { height: u32 = 0, format: command.Transmission.Format = .rgb, compression: command.Transmission.Compression = .none, - data: []const u8 = "", + data: Data = .{ .complete = "" }, + metadata: packed struct(u32) { + /// The image's transient usage hint, used to prioritize eviction. + transient: bool = false, + + /// Set this if the image was loaded without an ID or number. Such + /// images must not receive responses. Kitty gives these client ID + /// 0 (unaddressable); our storage keys everything by one public + /// u32 ID, so they get an ID from the upper half of the range + /// that is guaranteed unused at assignment time, but a client + /// that explicitly transmits that ID later can still replace + /// them. + implicit_id: bool = false, + + /// Number of placements referencing this image. + placement_count: u30 = 0, + } = .{}, /// Unique, monotonically increasing stamp assigned each time an /// image is added to (or replaced in) an ImageStorage. A changed @@ -519,15 +730,25 @@ pub const Image = struct { /// have changed, even if the dimensions and byte length are the /// same (e.g. a retransmission of the same ID). Stamps order by /// transmission time. Zero means "never stored". + /// + /// For animated images this also changes whenever the frame that + /// should be displayed changes (advance, edit, or delete of the + /// current frame), since consumers key texture caches off it. generation: u64 = 0, - /// Set this to true if this image was loaded by a command that - /// doesn't specify an ID or number, since such commands should - /// not be responded to, even though we do currently give them - /// IDs in the public range (which is bad!). - implicit_id: bool = false, + /// Animation state, non-null once any animation command (a=f, + /// a=a) has attached animation state to this image. Owned by the + /// image; replaced/retransmitted images drop it, which implements + /// the protocol's "retransmission resets the animation" rule. + /// + /// This is only ever attached to images stored in an ImageStorage + /// and must only be mutated through the storage's own pointer + /// (Image values are copied around freely; copies share this + /// pointer and never own it). + animation: ?*animation.Animation = null, pub const Error = error{ + InsufficientData, InvalidData, DecompressionFailed, DimensionsRequired, @@ -540,14 +761,97 @@ pub const Image = struct { UnsupportedDepth, }; + pub const Data = union(enum) { + /// Owned, decoded image bytes. The empty default is not allocated. + complete: []const u8, + + /// Expected decoded byte length for a payload that has not arrived. + pending: usize, + + /// Bytes reserved against the storage limit. + pub fn len(self: Data) usize { + return switch (self) { + .complete => |data| data.len, + .pending => |expected_len| expected_len, + }; + } + + /// Returns decoded bytes when the payload is complete. + pub fn bytes(self: Data) ?[]const u8 { + return switch (self) { + .complete => |data| data, + .pending => null, + }; + } + + pub fn isPending(self: Data) bool { + return self == .pending; + } + + pub fn deinit(self: *Data, alloc: Allocator) void { + switch (self.*) { + .complete => |data| if (data.len > 0) alloc.free(data), + .pending => {}, + } + } + }; + pub fn deinit(self: *Image, alloc: Allocator) void { - if (self.data.len > 0) alloc.free(self.data); + self.data.deinit(alloc); + if (self.animation) |anim| { + anim.deinit(alloc); + alloc.destroy(anim); + self.animation = null; + } + } + + /// The pixel data that should be displayed for this image. For an + /// animated image this is the current animation frame; otherwise + /// (and for the root frame) it is the image's own data. + pub fn renderData(self: *const Image) Data { + if (self.animation) |anim| { + if (anim.current_index > 0) { + return .{ .complete = anim.frames.items[anim.current_index - 1].data }; + } + } + + return self.data; + } + + /// The pixel data of the given 1-based animation frame number, or + /// null if the frame doesn't exist. Frame 1 (the root frame) + /// always exists as long as the image data is complete, even for + /// images without animation state. + /// + /// The returned slice is owned by the image (or its animation) + /// and remains valid until the image or frame is mutated. + pub fn frameData(self: *const Image, number: u32) ?[]const u8 { + switch (number) { + 0 => return null, + 1 => return self.data.bytes(), + else => { + const anim = self.animation orelse return null; + // Minus 2 because frame is 1-based and frame 1 is the + // image base data, so the animation frames start at frame 2. + const idx = number - 2; + if (idx >= anim.frames.items.len) return null; + return anim.frames.items[idx].data; + }, + } + } + + /// Total bytes of pixel data reserved against the storage limit + /// for this image: the base data plus any animation frames. + pub fn storageSize(self: *const Image) usize { + var total: usize = self.data.len(); + if (self.animation) |anim| total += anim.frameBytes(); + return total; } /// Mostly for logging pub fn withoutData(self: *const Image) Image { var copy = self.*; - copy.data = ""; + if (copy.data == .complete) copy.data = .{ .complete = "" }; return copy; } }; @@ -558,13 +862,168 @@ pub const Image = struct { pub const Rect = struct { top_left: PageList.Pin, bottom_right: PageList.Pin, + + /// Returns true if the grid cell is inside this rectangle. Pin.isBetween + /// compares page order, so its interior rows intentionally do not constrain + /// x. Check the column independently and use isBetween only for the row. + pub fn contains(self: Rect, cell: PageList.Pin) bool { + if (cell.x < self.top_left.x or cell.x > self.bottom_right.x) return false; + + var row = cell; + row.x = self.top_left.x; + return row.isBetween(self.top_left, self.bottom_right); + } }; +/// Returns whether a name follows the POSIX shared memory name format. +fn validSharedMemoryName(name: []const u8, name_max: usize) bool { + if (name.len < 2 or name.len > name_max or name[0] != '/') return false; + for (name[1..]) |c| { + if (c == '/' or c == 0) return false; + } + + return true; +} + +/// Returns true if `path` is `dir` or is contained within it, requiring a +/// path-separator boundary so similarly prefixed directories do not match. +fn isPathInDir(dir: []const u8, path: []const u8) bool { + if (dir.len == 0 or !std.mem.startsWith(u8, path, dir)) return false; + if (path.len == dir.len or std.fs.path.isSep(dir[dir.len - 1])) return true; + return std.fs.path.isSep(path[dir.len]); +} + +test { + _ = kitty_windows; +} + +test "temporary file path must be inside directory" { + const testing = std.testing; + + try testing.expect(isPathInDir("/tmp", "/tmp/tty-graphics-protocol-image.data")); + try testing.expect(isPathInDir("/tmp/", "/tmp/tty-graphics-protocol-image.data")); + try testing.expect(isPathInDir("/tmp", "/tmp")); + + try testing.expect(!isPathInDir("", "/tmp/tty-graphics-protocol-image.data")); + try testing.expect(!isPathInDir("/tmp", "/tmpX/tty-graphics-protocol-image.data")); + try testing.expect(!isPathInDir("/dev/shm", "/dev/shm-evil/tty-graphics-protocol-image.data")); + try testing.expect(!isPathInDir("/custom/tmp", "/custom/tmp-suffix/tty-graphics-protocol-image.data")); +} + +test "shared memory names follow POSIX rules" { + const testing = std.testing; + + try testing.expect(validSharedMemoryName("/kitty", 8)); + try testing.expect(validSharedMemoryName("/1234567", 8)); + + try testing.expect(!validSharedMemoryName("", 8)); + try testing.expect(!validSharedMemoryName("/", 8)); + try testing.expect(!validSharedMemoryName("kitty", 8)); + try testing.expect(!validSharedMemoryName("/kitty/image", 16)); + try testing.expect(!validSharedMemoryName("/kitty\x00image", 16)); + try testing.expect(!validSharedMemoryName("/12345678", 8)); +} + +test "image load rejects invalid POSIX shared memory names" { + if (comptime builtin.abi.isAndroid() or + builtin.target.os.tag == .windows or + !builtin.link_libc) + { + return error.SkipZigTest; + } + + const testing = std.testing; + const alloc = testing.allocator; + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .shared_memory, + .width = 1, + .height = 1, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, "kitty-without-leading-slash"), + }; + defer cmd.deinit(alloc); + + try testing.expectError( + error.InvalidData, + LoadingImage.init(testing.io, alloc, &cmd, .{ + .file = false, + .temporary_file = .disabled, + .shared_memory = true, + }), + ); +} + +test "shared memory range with offset and size" { + const testing = std.testing; + + const loading: LoadingImage = .{ + .image = .{ + .width = 1, + .height = 1, + .format = .rgb, + }, + .quiet = .no, + .temporary_directory = null, + }; + + const explicit = try loading.sharedMemoryRange(.{ + .offset = 2, + .size = 3, + }, 5); + try testing.expectEqual(@as(usize, 2), explicit.start); + try testing.expectEqual(@as(usize, 5), explicit.end); + + const implicit = try loading.sharedMemoryRange(.{ + .offset = 2, + }, 5); + try testing.expectEqual(@as(usize, 2), implicit.start); + try testing.expectEqual(@as(usize, 5), implicit.end); +} + +test "shared memory range rejects out of bounds offset" { + const loading: LoadingImage = .{ + .image = .{ + .width = 1, + .height = 1, + .format = .rgb, + }, + .quiet = .no, + .temporary_directory = null, + }; + + try std.testing.expectError( + error.InvalidData, + loading.sharedMemoryRange(.{ .offset = 4 }, 3), + ); +} + +test "shared memory range validates dimensions before multiplication" { + const loading: LoadingImage = .{ + .image = .{ + .width = std.math.maxInt(u32), + .height = std.math.maxInt(u32), + .format = .rgba, + }, + .quiet = .no, + .temporary_directory = null, + }; + + try std.testing.expectError( + error.DimensionsTooLarge, + loading.sharedMemoryRange(.{}, 1), + ); +} + // This specifically tests we ALLOW invalid RGB data because Kitty // documents that this should work. test "image load with invalid RGB data" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; // <ESC>_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA<ESC>\ var cmd: command.Command = .{ @@ -577,13 +1036,14 @@ test "image load with invalid RGB data" { .data = try alloc.dupe(u8, "AAAA"), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); } test "image load with image too wide" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -595,7 +1055,7 @@ test "image load with image too wide" { .data = try alloc.dupe(u8, "AAAA"), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); try testing.expectError(error.DimensionsTooLarge, loading.complete(alloc)); } @@ -603,6 +1063,7 @@ test "image load with image too wide" { test "image load with image too tall" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -614,7 +1075,7 @@ test "image load with image too tall" { .data = try alloc.dupe(u8, "AAAA"), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); try testing.expectError(error.DimensionsTooLarge, loading.complete(alloc)); } @@ -622,6 +1083,7 @@ test "image load with image too tall" { test "image load: rgb, zlib compressed, direct" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -638,7 +1100,7 @@ test "image load: rgb, zlib compressed, direct" { ), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); var img = try loading.complete(alloc); defer img.deinit(alloc); @@ -650,6 +1112,7 @@ test "image load: rgb, zlib compressed, direct" { test "image load: rgb, not compressed, direct" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -666,7 +1129,7 @@ test "image load: rgb, not compressed, direct" { ), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); var img = try loading.complete(alloc); defer img.deinit(alloc); @@ -678,6 +1141,7 @@ test "image load: rgb, not compressed, direct" { test "image load: rgb, zlib compressed, direct, chunked" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; const data = @embedFile("testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data"); @@ -695,13 +1159,13 @@ test "image load: rgb, zlib compressed, direct, chunked" { .data = try alloc.dupe(u8, data[0..1024]), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); // Read our remaining chunks - var fbs = std.io.fixedBufferStream(data[1024..]); + var fbs: std.Io.Reader = .fixed(data[1024..]); var buf: [1024]u8 = undefined; - while (fbs.reader().readAll(&buf)) |size| { + while (fbs.readSliceShort(&buf)) |size| { try loading.addData(alloc, buf[0..size]); if (size < buf.len) break; } else |err| return err; @@ -715,6 +1179,7 @@ test "image load: rgb, zlib compressed, direct, chunked" { test "image load: rgb, zlib compressed, direct, chunked with zero initial chunk" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; const data = @embedFile("testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data"); @@ -731,13 +1196,13 @@ test "image load: rgb, zlib compressed, direct, chunked with zero initial chunk" } }, }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); // Read our remaining chunks - var fbs = std.io.fixedBufferStream(data); + var fbs: std.Io.Reader = .fixed(data); var buf: [1024]u8 = undefined; - while (fbs.reader().readAll(&buf)) |size| { + while (fbs.readSliceShort(&buf)) |size| { try loading.addData(alloc, buf[0..size]); if (size < buf.len) break; } else |err| return err; @@ -751,17 +1216,18 @@ test "image load: rgb, zlib compressed, direct, chunked with zero initial chunk" test "image load: temporary file without correct path" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -775,26 +1241,81 @@ test "image load: temporary file without correct path" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - try testing.expectError(error.TemporaryFileNotNamedCorrectly, LoadingImage.init(alloc, &cmd, .all)); + var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined; + try testing.expectError(error.TemporaryFileNotNamedCorrectly, LoadingImage.init( + io, + alloc, + &cmd, + .allWithTempDir(dir_path_buf[0..try tmp_dir.dir.realPath(testing.io, &dir_path_buf)]), + )); // Temporary file should still be there - try tmp_dir.dir.access(path, .{}); + try tmp_dir.dir.access(testing.io, path, .{}); +} + +test "image load: temporary file outside directory prefix is rejected" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + try tmp_dir.dir.createDir(io, "temp", .default_dir); + try tmp_dir.dir.createDir(io, "temp-suffix", .default_dir); + + var trusted_dir = try tmp_dir.dir.openDir(io, "temp", .{}); + defer trusted_dir.close(io); + var outside_dir = try tmp_dir.dir.openDir(io, "temp-suffix", .{}); + defer outside_dir.close(io); + + const filename = "tty-graphics-protocol-image.data"; + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try outside_dir.writeFile(io, .{ + .sub_path = filename, + .data = data, + }); + + var trusted_path_buf: [std.fs.max_path_bytes]u8 = undefined; + const trusted_path = trusted_path_buf[0..try trusted_dir.realPath(io, &trusted_path_buf)]; + var outside_path_buf: [std.fs.max_path_bytes]u8 = undefined; + const outside_path = outside_path_buf[0..try outside_dir.realPathFile(io, filename, &outside_path_buf)]; + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .temporary_file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, outside_path), + }; + defer cmd.deinit(alloc); + try testing.expectError( + error.TemporaryFileNotInTempDir, + LoadingImage.init(io, alloc, &cmd, .allWithTempDir(trusted_path)), + ); + + // Rejection must happen before temporary-file cleanup is armed. + try outside_dir.access(io, filename, .{}); } test "image load: rgb, not compressed, temporary file" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "tty-graphics-protocol-image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("tty-graphics-protocol-image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "tty-graphics-protocol-image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -808,30 +1329,37 @@ test "image load: rgb, not compressed, temporary file" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .all); + var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined; + var loading = try LoadingImage.init( + io, + alloc, + &cmd, + .allWithTempDir(dir_path_buf[0..try tmp_dir.dir.realPath(testing.io, &dir_path_buf)]), + ); defer loading.deinit(alloc); var img = try loading.complete(alloc); defer img.deinit(alloc); try testing.expect(img.compression == .none); // Temporary file should be gone - try testing.expectError(error.FileNotFound, tmp_dir.dir.access(path, .{})); + try testing.expectError(error.FileNotFound, tmp_dir.dir.access(testing.io, path, .{})); } test "image load: rgb, not compressed, regular file" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -845,12 +1373,508 @@ test "image load: rgb, not compressed, regular file" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .all); + var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined; + var loading = try LoadingImage.init( + io, + alloc, + &cmd, + .allWithTempDir(dir_path_buf[0..try tmp_dir.dir.realPath(testing.io, &dir_path_buf)]), + ); defer loading.deinit(alloc); var img = try loading.complete(alloc); defer img.deinit(alloc); try testing.expect(img.compression == .none); - try tmp_dir.dir.access(path, .{}); + try tmp_dir.dir.access(testing.io, path, .{}); +} + +test "image load: regular file size reads exactly requested bytes" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + try tmp_dir.dir.writeFile(io, .{ + .sub_path = "image.data", + .data = &.{ 1, 2, 3, 4, 5, 6 }, + }); + + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const path = path_buf[0..try tmp_dir.dir.realPathFile( + io, + "image.data", + &path_buf, + )]; + + const cases = [_]struct { + offset: u32, + expected: [3]u8, + }{ + .{ .offset = 0, .expected = .{ 1, 2, 3 } }, + .{ .offset = 3, .expected = .{ 4, 5, 6 } }, + }; + for (cases) |case| { + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .width = 1, + .height = 1, + .size = 3, + .offset = case.offset, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + + var loading = try LoadingImage.init(io, alloc, &cmd, .{ + .file = true, + .temporary_file = .disabled, + .shared_memory = false, + }); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + + try testing.expectEqualSlices(u8, &case.expected, img.data.complete); + } +} + +test "image load: regular file size rejects short data" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + try tmp_dir.dir.writeFile(io, .{ + .sub_path = "image.data", + .data = &.{ 1, 2 }, + }); + + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const path = path_buf[0..try tmp_dir.dir.realPathFile( + io, + "image.data", + &path_buf, + )]; + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .width = 1, + .height = 1, + .size = 3, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + + try testing.expectError( + error.InvalidData, + LoadingImage.init(io, alloc, &cmd, .{ + .file = true, + .temporary_file = .disabled, + .shared_memory = false, + }), + ); +} + +test "image load: rgb, not compressed, relative regular file" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(testing.io, .{ + .sub_path = "image.data", + .data = data, + }); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try std.fmt.allocPrint( + alloc, + ".zig-cache/tmp/{s}/image.data", + .{tmp_dir.sub_path}, + ), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(io, alloc, &cmd, .{ + .file = true, + .temporary_file = .disabled, + .shared_memory = false, + }); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); +} + +test "image load: blocklist applies to opened file after symlink swap" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + + const testing = std.testing; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + try tmp_dir.dir.writeFile(io, .{ + .sub_path = "safe.data", + .data = "safe", + }); + try tmp_dir.dir.symLink(io, "/dev/null", "image.data", .{}); + + // Pin the blocked file, then simulate the cooperating process replacing + // the path with a safe target before validation. + const blocked_file = try tmp_dir.dir.openFile(io, "image.data", .{}); + defer blocked_file.close(io); + try tmp_dir.dir.symLinkAtomic(io, "safe.data", "image.data", .{}); + + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + try testing.expectError( + error.InvalidData, + LoadingImage.validatedFilePath(io, blocked_file, &path_buf), + ); + + // The pathname now resolves to the safe replacement, demonstrating that + // the rejection above came from the already-open file handle. + const safe_file = try tmp_dir.dir.openFile(io, "image.data", .{}); + defer safe_file.close(io); + _ = try LoadingImage.validatedFilePath(io, safe_file, &path_buf); +} + +test "image load: windows UNC path is rejected before open" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + // Opening a UNC path would resolve the host name and authenticate to + // it over SMB, so the rejection has to happen on the raw path. The + // host name is in the reserved .invalid TLD so it can never resolve. + const paths = [_][]const u8{ + "\\\\nonexistent-host.invalid\\share\\tty-graphics-protocol-image.data", + "//nonexistent-host.invalid/share/tty-graphics-protocol-image.data", + "\\\\?\\UNC\\nonexistent-host.invalid\\share\\image.data", + }; + for (paths) |path| { + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + try testing.expectError( + error.InvalidData, + LoadingImage.init(io, alloc, &cmd, .{ + .file = true, + .temporary_file = .disabled, + .shared_memory = false, + }), + ); + } +} + +test "image load: windows device namespace paths are rejected before open" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + const filename = "tty-graphics-protocol-image.data"; + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(io, .{ .sub_path = filename, .data = data }); + + var dir_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir_path = dir_buf[0..try tmp_dir.dir.realPath(io, &dir_buf)]; + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const real_path = path_buf[0..try tmp_dir.dir.realPathFile(io, filename, &path_buf)]; + + // The verbatim, local device and NT namespace spellings all resolve + // to the same real file, so rejecting them proves the check runs on + // the raw path rather than on the canonical one. + const prefixes = [_][]const u8{ "\\\\?\\", "\\\\.\\", "\\??\\" }; + for (prefixes) |prefix| { + const path = try std.mem.concat(alloc, u8, &.{ prefix, real_path }); + defer alloc.free(path); + + const mediums = [_]command.Transmission.Medium{ .file, .temporary_file }; + for (mediums) |medium| { + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = medium, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + try testing.expectError( + error.InvalidData, + LoadingImage.init(io, alloc, &cmd, .allWithTempDir(dir_path)), + ); + } + } + + // A named pipe reached through the local device namespace. + { + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, "\\\\.\\pipe\\ghostty-kitty-graphics-test"), + }; + defer cmd.deinit(alloc); + try testing.expectError( + error.InvalidData, + LoadingImage.init(io, alloc, &cmd, .allWithTempDir(dir_path)), + ); + } + + // Nothing above reached the temporary file deletion. + try tmp_dir.dir.access(io, filename, .{}); +} + +test "image load: windows reserved device names are rejected before open" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + var dir_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir_path = dir_buf[0..try tmp_dir.dir.realPath(io, &dir_buf)]; + + const names = [_][]const u8{ "CON", "NUL.data", "com1", "LPT9.png", "AUX", "PRN." }; + for (names) |name| { + const path = try std.fs.path.join(alloc, &.{ dir_path, name }); + defer alloc.free(path); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + try testing.expectError( + error.InvalidData, + LoadingImage.init(io, alloc, &cmd, .{ + .file = true, + .temporary_file = .disabled, + .shared_memory = false, + }), + ); + } +} + +test "image load: windows local file accepted in forward slash and upper case spellings" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + const filename = "image.data"; + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(io, .{ .sub_path = filename, .data = data }); + + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const real_path = path_buf[0..try tmp_dir.dir.realPathFile(io, filename, &path_buf)]; + + // Both spellings open the same file; the canonical path the checks + // see is the backslash, on-disk case form either way. + const forward = try alloc.dupe(u8, real_path); + defer alloc.free(forward); + std.mem.replaceScalar(u8, forward, '\\', '/'); + const upper = try alloc.dupe(u8, real_path); + defer alloc.free(upper); + _ = std.ascii.upperString(upper, real_path); + + const spellings = [_][]const u8{ forward, upper }; + for (spellings) |path| { + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(io, alloc, &cmd, .{ + .file = true, + .temporary_file = .disabled, + .shared_memory = false, + }); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); + } + + try tmp_dir.dir.access(io, filename, .{}); +} + +test "image load: windows temporary file with differently spelled directory" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + const filename = "tty-graphics-protocol-image.data"; + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(io, .{ .sub_path = filename, .data = data }); + + var dir_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir_path = dir_buf[0..try tmp_dir.dir.realPath(io, &dir_buf)]; + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const real_path = path_buf[0..try tmp_dir.dir.realPathFile(io, filename, &path_buf)]; + + // Hosts hand over GetTempPath output, which regularly differs from + // the canonical path in case (`C:\WINDOWS\TEMP\`), so the directory + // prefix check only passes through the real-path fallback. + const dir_upper = try alloc.dupe(u8, dir_path); + defer alloc.free(dir_upper); + _ = std.ascii.upperString(dir_upper, dir_path); + const path_upper = try alloc.dupe(u8, real_path); + defer alloc.free(path_upper); + _ = std.ascii.upperString(path_upper, real_path); + try testing.expect(!isPathInDir(dir_upper, real_path) or + std.mem.eql(u8, dir_upper, dir_path)); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .temporary_file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path_upper), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(io, alloc, &cmd, .allWithTempDir(dir_upper)); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); + + // Temporary file should be gone + try testing.expectError(error.FileNotFound, tmp_dir.dir.access(io, filename, .{})); +} + +test "image load: windows canonical path check accepts a local file opened through a device spelling" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + const filename = "image.data"; + try tmp_dir.dir.writeFile(io, .{ .sub_path = filename, .data = "safe" }); + + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const real_path = path_buf[0..try tmp_dir.dir.realPathFile(io, filename, &path_buf)]; + + // readFile refuses this spelling before the open, but the post-open + // check works from the canonical path and so does not care how the + // file was reached: `\\.\C:\...` canonicalizes back to `C:\...`. + const device_path = try std.mem.concat(alloc, u8, &.{ "\\\\.\\", real_path }); + defer alloc.free(device_path); + const file = try std.Io.Dir.cwd().openFile(io, device_path, .{}); + defer file.close(io); + + const canon_buf = try alloc.alloc(u8, std.fs.max_path_bytes); + defer alloc.free(canon_buf); + const canon = try LoadingImage.validatedFilePath(io, file, canon_buf); + try testing.expectEqualStrings(real_path, canon); +} + +test "image load: windows canonical path check rejects a file reached through a UNC share" { + if (builtin.os.tag != .windows) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); + const filename = "image.data"; + try tmp_dir.dir.writeFile(io, .{ .sub_path = filename, .data = "safe" }); + + var path_buf: [std.fs.max_path_bytes]u8 = undefined; + const real_path = path_buf[0..try tmp_dir.dir.realPathFile(io, filename, &path_buf)]; + try testing.expect(kitty_windows.isDriveAbsolute(real_path)); + + // Reach the same local file through the loopback administrative + // share, which is how a junction or symlink into a share would look + // to the post-open check. The share needs the server service and an + // administrative token, so the test is skipped when the open fails. + const unc_path = try std.fmt.allocPrint( + alloc, + "\\\\localhost\\{c}$\\{s}", + .{ real_path[0], real_path[3..] }, + ); + defer alloc.free(unc_path); + const file = std.Io.Dir.cwd().openFile(io, unc_path, .{}) catch + return error.SkipZigTest; + defer file.close(io); + + const canon_buf = try alloc.alloc(u8, std.fs.max_path_bytes); + defer alloc.free(canon_buf); + try testing.expectError( + error.NotDriveAbsolute, + LoadingImage.validatedFilePath(io, file, canon_buf), + ); } test "image load: png, not compressed, regular file" { @@ -858,17 +1882,18 @@ test "image load: png, not compressed, regular file" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-png-none-50x76-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "tty-graphics-protocol-image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("tty-graphics-protocol-image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "tty-graphics-protocol-image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -882,18 +1907,91 @@ test "image load: png, not compressed, regular file" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .all); + var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined; + var loading = try LoadingImage.init( + io, + alloc, + &cmd, + .allWithTempDir(dir_path_buf[0..try tmp_dir.dir.realPath(testing.io, &dir_path_buf)]), + ); defer loading.deinit(alloc); var img = try loading.complete(alloc); defer img.deinit(alloc); try testing.expect(img.compression == .none); try testing.expect(img.format == .rgba); - try tmp_dir.dir.access(path, .{}); + try tmp_dir.dir.access(testing.io, path, .{}); +} + +test "image load: png rejects oversized decoder allocation" { + const testing = std.testing; + + const oversized_decoder = struct { + fn decode( + alloc: Allocator, + _: []const u8, + ) sys.DecodeError!sys.Image { + const data = try alloc.alloc(u8, max_size + 1); + return .{ + .width = 1, + .height = 1, + .data = data, + }; + } + }.decode; + + const original_decode_png = sys.decode_png; + defer sys.decode_png = original_decode_png; + sys.decode_png = &oversized_decoder; + + // Fail any allocation which reaches the underlying allocator. The size + // limiter should reject the decoder's request before it gets that far. + var failing = testing.FailingAllocator.init(testing.allocator, .{ + .fail_index = 0, + }); + const alloc = failing.allocator(); + + var loading: LoadingImage = .{ + .image = .{ .format = .png }, + .quiet = .no, + .temporary_directory = null, + }; + defer loading.deinit(alloc); + + try testing.expectError(error.InvalidData, loading.complete(alloc)); + try testing.expect(!failing.has_induced_failure); +} + +test "image load: png rejects oversized Wuffs image before allocation" { + if (sys.decode_png == null) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + // Turn the small test PNG into a 32768x32767 image. Its decoded RGBA + // size is just under Wuffs' 4 GiB package limit but over Kitty's 400 MiB + // limit, which previously allowed the large allocation to happen first. + var data = @embedFile("testdata/image-png-none-50x76-2147483647-raw.data").*; + std.mem.writeInt(u32, data[16..20], 32768, .big); + std.mem.writeInt(u32, data[20..24], 32767, .big); + std.mem.writeInt(u32, data[29..33], std.hash.Crc32.hash(data[12..29]), .big); + + const cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .png, + .medium = .direct, + } }, + .data = &data, + }; + var loading = try LoadingImage.init(testing.io, alloc, &cmd, .direct); + defer loading.deinit(alloc); + + try testing.expectError(error.InvalidData, loading.complete(alloc)); } test "limits: direct medium always allowed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -908,24 +2006,25 @@ test "limits: direct medium always allowed" { defer cmd.deinit(alloc); // Direct medium should work even with the most restrictive limits - var loading = try LoadingImage.init(alloc, &cmd, .direct); + var loading = try LoadingImage.init(io, alloc, &cmd, .direct); defer loading.deinit(alloc); } test "limits: file medium blocked by limits" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -939,23 +2038,24 @@ test "limits: file medium blocked by limits" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - try testing.expectError(error.UnsupportedMedium, LoadingImage.init(alloc, &cmd, .direct)); + try testing.expectError(error.UnsupportedMedium, LoadingImage.init(io, alloc, &cmd, .direct)); } test "limits: file medium allowed by limits" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -969,9 +2069,9 @@ test "limits: file medium allowed by limits" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .{ + var loading = try LoadingImage.init(io, alloc, &cmd, .{ .file = true, - .temporary_file = false, + .temporary_file = .disabled, .shared_memory = false, }); defer loading.deinit(alloc); @@ -980,17 +2080,18 @@ test "limits: file medium allowed by limits" { test "limits: temporary file medium blocked by limits" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "tty-graphics-protocol-image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("tty-graphics-protocol-image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "tty-graphics-protocol-image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -1004,30 +2105,31 @@ test "limits: temporary file medium blocked by limits" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - try testing.expectError(error.UnsupportedMedium, LoadingImage.init(alloc, &cmd, .{ + try testing.expectError(error.UnsupportedMedium, LoadingImage.init(io, alloc, &cmd, .{ .file = true, - .temporary_file = false, + .temporary_file = .disabled, .shared_memory = true, })); // File should still exist since we blocked before reading - try tmp_dir.dir.access("tty-graphics-protocol-image.data", .{}); + try tmp_dir.dir.access(testing.io, "tty-graphics-protocol-image.data", .{}); } test "limits: temporary file medium allowed by limits" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var tmp_dir = try temp_dir.TempDir.init(); - defer tmp_dir.deinit(); + var tmp_dir = testing.tmpDir(.{}); + defer tmp_dir.cleanup(); const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); - try tmp_dir.dir.writeFile(.{ + try tmp_dir.dir.writeFile(testing.io, .{ .sub_path = "tty-graphics-protocol-image.data", .data = data, }); var buf: [std.fs.max_path_bytes]u8 = undefined; - const path = try tmp_dir.dir.realpath("tty-graphics-protocol-image.data", &buf); + const path = buf[0..try tmp_dir.dir.realPathFile(testing.io, "tty-graphics-protocol-image.data", &buf)]; var cmd: command.Command = .{ .control = .{ .transmit = .{ @@ -1041,10 +2143,19 @@ test "limits: temporary file medium allowed by limits" { .data = try alloc.dupe(u8, path), }; defer cmd.deinit(alloc); - var loading = try LoadingImage.init(alloc, &cmd, .{ - .file = false, - .temporary_file = true, - .shared_memory = false, - }); + var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined; + var loading = try LoadingImage.init( + io, + alloc, + &cmd, + + .{ + .file = false, + .temporary_file = .{ + .enabled = .{ .directory = dir_path_buf[0..try tmp_dir.dir.realPath(testing.io, &dir_path_buf)] }, + }, + .shared_memory = false, + }, + ); defer loading.deinit(alloc); } diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_pixel.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_pixel.zig new file mode 100644 index 00000000..1f446873 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_pixel.zig @@ -0,0 +1,235 @@ +//! Pixel-buffer operations for the Kitty graphics protocol: format +//! conversion to RGBA, background fill, and rectangle composition. +//! These are the primitives behind animation frame loading (a=f) and +//! frame composition (a=c). See graphics_animation.zig for the +//! animation model built on top of them. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const wuffs = @import("wuffs"); +const command = @import("graphics_command.zig"); + +/// Convert pixel data in the given format to a freshly allocated RGBA +/// buffer. The caller owns the result; the input is not freed. +/// +/// The input length must be a multiple of the format's bytes per +/// pixel; image loading validates data length against the image +/// dimensions before storing it. +pub fn rgbaFromFormat( + alloc: Allocator, + format: command.Transmission.Format, + data: []const u8, +) Allocator.Error![]u8 { + const result = switch (format) { + .rgba => return try alloc.dupe(u8, data), + .rgb => wuffs.swizzle.rgbToRgba(alloc, data), + .gray => wuffs.swizzle.gToRgba(alloc, data), + .gray_alpha => wuffs.swizzle.gaToRgba(alloc, data), + + // PNG is decoded to RGBA during image loading. + .png => unreachable, + }; + + return result catch |err| switch (err) { + error.OutOfMemory => error.OutOfMemory, + // These are fixed, supported swizzles; wuffs cannot fail to + // prepare them and nothing else in the conversion errors. + error.WuffsError, error.Overflow => unreachable, + }; +} + +/// Fill an RGBA buffer with the given background color. +pub fn fillBackground( + data: []u8, + bg: command.AnimationFrameLoading.Background, +) void { + const raw: u32 = @bitCast(bg); + if (raw == 0) { + @memset(data, 0); + return; + } + var i: usize = 0; + while (i + 4 <= data.len) : (i += 4) { + data[i + 0] = bg.r; + data[i + 1] = bg.g; + data[i + 2] = bg.b; + data[i + 3] = bg.a; + } +} + +/// Compose the `src` rectangle (src_width x src_height RGBA pixels) +/// onto the `dst` canvas (dst_width x dst_height RGBA pixels) with +/// its top-left corner at (x, y). Portions of the rectangle outside +/// the canvas are silently clipped, matching Kitty's a=f behavior. +pub fn composeRect( + dst: []u8, + dst_width: u32, + dst_height: u32, + src: []const u8, + src_width: u32, + src_height: u32, + x: u32, + y: u32, + mode: command.CompositionMode, +) void { + if (x >= dst_width or y >= dst_height) return; + const width: usize = @min(src_width, dst_width - x); + const height: usize = @min(src_height, dst_height - y); + for (0..height) |row| { + const dst_off = ((y + row) * dst_width + x) * 4; + const src_off = row * @as(usize, src_width) * 4; + composeRow( + dst[dst_off..][0 .. width * 4], + src[src_off..][0 .. width * 4], + mode, + ); + } +} + +/// Compose a width x height rectangle between two full-size RGBA +/// canvases sharing the same `canvas_width` stride, reading from +/// (src_x, src_y) in `src` and writing at (dst_x, dst_y) in `dst`. +/// The caller must have validated that both rectangles are within +/// bounds; a=c reports out-of-bounds rectangles as errors rather +/// than clipping. +pub fn composeCanvasRect( + dst: []u8, + src: []const u8, + canvas_width: u32, + width: u32, + height: u32, + src_x: u32, + src_y: u32, + dst_x: u32, + dst_y: u32, + mode: command.CompositionMode, +) void { + for (0..height) |row| { + const dst_off = ((dst_y + row) * @as(usize, canvas_width) + dst_x) * 4; + const src_off = ((src_y + row) * @as(usize, canvas_width) + src_x) * 4; + composeRow( + dst[dst_off..][0 .. @as(usize, width) * 4], + src[src_off..][0 .. @as(usize, width) * 4], + mode, + ); + } +} + +fn composeRow(dst: []u8, src: []const u8, mode: command.CompositionMode) void { + switch (mode) { + .overwrite => @memcpy(dst, src), + .alpha_blend => wuffs.swizzle.rgbaSrcOver(dst, src), + } +} + +test "rgba conversion" { + const testing = std.testing; + const alloc = testing.allocator; + + { + const rgb = [_]u8{ 1, 2, 3, 4, 5, 6 }; + const result = try rgbaFromFormat(alloc, .rgb, &rgb); + defer alloc.free(result); + try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 255, 4, 5, 6, 255 }, result); + } + + { + const gray = [_]u8{ 7, 8 }; + const result = try rgbaFromFormat(alloc, .gray, &gray); + defer alloc.free(result); + try testing.expectEqualSlices(u8, &.{ 7, 7, 7, 255, 8, 8, 8, 255 }, result); + } + + { + const ga = [_]u8{ 7, 100, 8, 200 }; + const result = try rgbaFromFormat(alloc, .gray_alpha, &ga); + defer alloc.free(result); + try testing.expectEqualSlices(u8, &.{ 7, 7, 7, 100, 8, 8, 8, 200 }, result); + } + + { + const rgba = [_]u8{ 1, 2, 3, 4 }; + const result = try rgbaFromFormat(alloc, .rgba, &rgba); + defer alloc.free(result); + try testing.expectEqualSlices(u8, &rgba, result); + } +} + +test "fill background" { + var buf: [8]u8 = undefined; + fillBackground(&buf, .{ .r = 1, .g = 2, .b = 3, .a = 4 }); + try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 1, 2, 3, 4 }, &buf); + + fillBackground(&buf, .{}); + try std.testing.expectEqualSlices(u8, &(.{0} ** 8), &buf); +} + +test "compose rect overwrite with clipping" { + // 2x2 canvas, compose a 2x1 rect at (1, 1): only the first pixel + // of the rect fits, the rest clips off the right edge. + var dst = [_]u8{0} ** 16; + const src = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 }; + composeRect(&dst, 2, 2, &src, 2, 1, 1, 1, .overwrite); + + var expect = [_]u8{0} ** 16; + expect[12] = 1; + expect[13] = 2; + expect[14] = 3; + expect[15] = 4; + try std.testing.expectEqualSlices(u8, &expect, &dst); +} + +test "compose rect entirely out of bounds" { + var dst = [_]u8{9} ** 16; + const src = [_]u8{1} ** 4; + composeRect(&dst, 2, 2, &src, 1, 1, 2, 0, .overwrite); + composeRect(&dst, 2, 2, &src, 1, 1, 0, 2, .overwrite); + try std.testing.expectEqualSlices(u8, &(.{9} ** 16), &dst); +} + +test "alpha blend source-over semantics" { + const testing = std.testing; + + // Opaque source overwrites exactly. + { + var dst = [4]u8{ 10, 20, 30, 40 }; + composeRect(&dst, 1, 1, &.{ 100, 110, 120, 255 }, 1, 1, 0, 0, .alpha_blend); + try testing.expectEqualSlices(u8, &.{ 100, 110, 120, 255 }, &dst); + } + + // Fully transparent source leaves the destination untouched + // (like Kitty; see the module doc on rounding). + { + var dst = [4]u8{ 10, 20, 30, 40 }; + composeRect(&dst, 1, 1, &.{ 100, 110, 120, 0 }, 1, 1, 0, 0, .alpha_blend); + try testing.expectEqualSlices(u8, &.{ 10, 20, 30, 40 }, &dst); + } + + // 50% source over opaque destination. + { + var dst = [4]u8{ 0, 0, 0, 255 }; + composeRect(&dst, 1, 1, &.{ 255, 255, 255, 128 }, 1, 1, 0, 0, .alpha_blend); + try testing.expectEqual(@as(u8, 255), dst[3]); + try testing.expectEqual(@as(u8, 128), dst[0]); + } + + // Blending over a transparent destination yields the source + // exactly, matching Kitty: wuffs passes the source through + // untouched when the destination is transparent. + { + var dst = [4]u8{ 0, 0, 0, 0 }; + composeRect(&dst, 1, 1, &.{ 200, 100, 50, 128 }, 1, 1, 0, 0, .alpha_blend); + try testing.expectEqualSlices(u8, &.{ 200, 100, 50, 128 }, &dst); + } +} + +test "compose canvas rect" { + // 3x1 canvas: copy pixel at x=0 onto x=2. + var canvas = [_]u8{ 1, 2, 3, 4, 0, 0, 0, 0, 9, 9, 9, 9 }; + composeCanvasRect(&canvas, &canvas, 3, 1, 1, 0, 0, 2, 0, .overwrite); + try std.testing.expectEqualSlices( + u8, + &.{ 1, 2, 3, 4, 0, 0, 0, 0, 1, 2, 3, 4 }, + &canvas, + ); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig index ba82ea40..897c8944 100644 --- a/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig @@ -6,6 +6,8 @@ const ArenaAllocator = std.heap.ArenaAllocator; const terminal = @import("../main.zig"); const point = @import("../point.zig"); const size = @import("../size.zig"); +const animation = @import("graphics_animation.zig"); +const pixel = @import("graphics_pixel.zig"); const command = @import("graphics_command.zig"); const PageList = @import("../PageList.zig"); const Screen = @import("../Screen.zig"); @@ -32,8 +34,8 @@ var generation_counter: GenerationCounter = .{}; /// Returns the next generation stamp. Stamps are unique and strictly /// monotonically increasing process-wide, starting at 1 (0 is reserved /// to mean "never stamped"). -pub fn nextGeneration() u64 { - return generation_counter.next(); +pub fn nextGeneration(io: std.Io) u64 { + return generation_counter.next(io); } /// Backing implementation for the generation counter. We use a @@ -48,16 +50,17 @@ pub fn nextGeneration() u64 { const GenerationCounter = if (@bitSizeOf(usize) >= 64) struct { value: std.atomic.Value(u64) = .init(0), - fn next(self: *@This()) u64 { + fn next(self: *@This(), io: std.Io) u64 { + _ = io; return self.value.fetchAdd(1, .monotonic) + 1; } } else struct { - mutex: std.Thread.Mutex = .{}, + mutex: std.Io.Mutex = .init, value: u64 = 0, - fn next(self: *@This()) u64 { - self.mutex.lock(); - defer self.mutex.unlock(); + fn next(self: *@This(), io: std.Io) u64 { + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); self.value += 1; return self.value; } @@ -100,11 +103,10 @@ pub const ImageStorage = struct { /// This field must only be written via markMutated. generation: u64 = 0, - /// This is the next automatically assigned image ID. We start mid-way - /// through the u32 range to avoid collisions with buggy programs. - /// TODO: This isn't good enough, it's perfectly legal for programs - /// to use IDs in the latter half of the range and collisions - /// are not gracefully handled. + /// This is the next automatically assigned image ID for images + /// transmitted without an ID or number. We start mid-way through + /// the u32 range to stay clear of the low IDs client programs + /// typically pick. See nextImageId. next_image_id: u32 = 2147483647, /// This is the next automatically assigned placement ID. This is never @@ -131,6 +133,38 @@ pub const ImageStorage = struct { total_bytes: usize = 0, total_limit: usize = 320 * 1000 * 1000, // 320MB + /// Identifies one exact pending image transmission. The generation is + /// assigned by this storage when the pending image is inserted, so a + /// later replacement of the same ID cannot consume stale payload bytes. + pub const PendingImage = struct { + id: u32, + generation: u64, + + /// Attach owned decoded bytes if this exact pending transmission is + /// still resident. On true, storage owns `data`; on false, the caller + /// retains ownership. Completion preserves the image generation (and + /// therefore eviction age) while marking storage content as mutated. + pub fn complete( + self: PendingImage, + storage: *ImageStorage, + io: std.Io, + data: []const u8, + ) bool { + const img = storage.images.getPtr(self.id) orelse return false; + if (img.generation != self.generation) return false; + + const expected_len = switch (img.data) { + .complete => return false, + .pending => |len| len, + }; + if (data.len != expected_len) return false; + + img.data = .{ .complete = data }; + storage.markMutated(io); + return true; + } + }; + pub fn deinit( self: *ImageStorage, alloc: Allocator, @@ -138,12 +172,12 @@ pub const ImageStorage = struct { ) void { if (self.loading) |loading| loading.destroy(alloc); + self.clearPlacements(s); + self.placements.deinit(alloc); + var it = self.images.iterator(); while (it.next()) |kv| kv.value_ptr.deinit(alloc); self.images.deinit(alloc); - - self.clearPlacements(s); - self.placements.deinit(alloc); } /// Kitty image protocol is enabled if we have a non-zero limit. @@ -153,15 +187,16 @@ pub const ImageStorage = struct { /// Record a content mutation: marks the storage dirty and assigns a /// fresh generation stamp. Must be called by anything that changes - /// the set of images or placements (or image contents). + /// the set of images or placements (or image contents), including + /// the animation command handlers in graphics_exec.zig. /// /// Do NOT call this for geometry-only events (scrolling, resizing, /// screen switches); those must set only the dirty flag directly. /// Bumping the generation for geometry changes would break the /// contract that an unchanged generation means unchanged contents. - fn markMutated(self: *ImageStorage) void { + pub fn markMutated(self: *ImageStorage, io: std.Io) void { self.dirty = true; - self.generation = nextGeneration(); + self.generation = nextGeneration(io); } /// Sets the limit in bytes for the total amount of image data that @@ -170,23 +205,24 @@ pub const ImageStorage = struct { /// be disabled. pub fn setLimit( self: *ImageStorage, + io: std.Io, alloc: Allocator, s: *terminal.Screen, limit: usize, - ) !void { + ) void { // Special case disabling by quickly deleting all if (limit == 0) { const image_limits = self.image_limits; self.deinit(alloc, s); self.* = .{ .image_limits = image_limits }; - self.markMutated(); + self.markMutated(io); } // If we re lowering our limit, check if we need to evict. if (limit < self.total_bytes) { const req_bytes = self.total_bytes - limit; log.info("evicting images to lower limit, evicting={}", .{req_bytes}); - if (!try self.evictImage(alloc, req_bytes)) { + if (!self.evictImage(io, alloc, s, req_bytes)) { log.warn("failed to evict enough images for required bytes", .{}); } } @@ -194,54 +230,137 @@ pub const ImageStorage = struct { self.total_limit = limit; } - /// Add an already-loaded image to the storage. This will automatically - /// free any existing image with the same ID. - pub fn addImage(self: *ImageStorage, alloc: Allocator, img: Image) Allocator.Error!void { + /// Returns the next ID to automatically assign to an image that + /// was transmitted without an explicit ID (i=). The result is + /// never zero (zero means "no ID") and never an ID currently in + /// use, so an automatic ID never replaces an existing image. + pub fn nextImageId( + self: *ImageStorage, + mode: enum { explicit, implicit }, + ) u32 { + // Starting ID depends on mode. + var id: u32 = switch (mode) { + // Yeah, starting from 1 is wasteful. This matches what Kitty + // does. In the future we can probably cache a low-water-mark + // based on delete behavior. + .explicit => 1, + .implicit => self.next_image_id, + }; + + // Go through all possible images. We have +2 because we can + // exceed the total by 1 (new ID). + const count: usize = self.images.count(); + for (0..count + 2) |_| { + if (id != 0 and !self.images.contains(id)) break; + id +%= 1; + } + + // Zero is never allowed. + if (id == 0) id = 1; + + // Keep track of our next image id for implicit to speed that up. + if (mode == .implicit) self.next_image_id = id +% 1; + + return id; + } + + /// Add an image to the storage. This will automatically free any existing + /// image with the same ID. Prefer addPendingImage for pending data so the + /// caller receives a completion token. + pub fn addImage( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + s: *terminal.Screen, + img: Image, + ) Allocator.Error!void { + const new_len = img.data.len(); + // If the image itself is over the limit, then error immediately - if (img.data.len > self.total_limit) return error.OutOfMemory; + if (new_len > self.total_limit) return error.OutOfMemory; + + // Credit an existing image's reservation before calculating the + // replacement size. In particular, a completed live transmission + // replacing pending snapshot metadata must be able to reuse the + // reservation without evicting its own ID. + const old_len = if (self.images.get(img.id)) |old| + old.storageSize() + else + 0; + assert(old_len <= self.total_bytes); + + // Reserve map capacity before evicting anything so allocation failure + // cannot leave storage partially evicted. Existing keys need no room. + if (!self.images.contains(img.id)) { + try self.images.ensureUnusedCapacity(alloc, 1); + } // If this would put us over the limit, then evict. - const total_bytes = self.total_bytes + img.data.len; + const total_bytes = self.total_bytes - old_len + new_len; if (total_bytes > self.total_limit) { const req_bytes = total_bytes - self.total_limit; log.info("evicting images to make space for {} bytes", .{req_bytes}); - if (!try self.evictImage(alloc, req_bytes)) { + if (!self.evictImageExcept(io, alloc, s, req_bytes, img.id)) { log.warn("failed to evict enough images for required bytes", .{}); return error.OutOfMemory; } } - // Do the gop op first so if it fails we don't get a partial state - const gop = try self.images.getOrPut(alloc, img.id); + const gop = self.images.getOrPutAssumeCapacity(img.id); - log.debug("addImage image={}", .{img: { - var copy = img; - copy.data = ""; - break :img copy; - }}); + log.debug("addImage image={}", .{img.withoutData()}); - // Write our new image if (gop.found_existing) { - self.total_bytes -= gop.value_ptr.data.len; + // Retransmitting a specific image ID replaces the old image and all + // of its placements, as required by the Kitty graphics protocol. + self.removePlacementsByImageId(s, img.id); + + // Relative placements parented to the removed placements go too. + _ = self.removeOrphans(s, null); + + // Replacing an image drops its animation frames with it, + // implementing the protocol rule that retransmitting the + // base image resets the animation. + self.total_bytes -= gop.value_ptr.storageSize(); gop.value_ptr.deinit(alloc); } gop.value_ptr.* = img; - self.total_bytes += img.data.len; + gop.value_ptr.metadata.placement_count = 0; + self.total_bytes += new_len; // Stamp the stored image with a fresh generation. This gives // every add/replace a unique stamp even when the same image ID // is retransmitted with identical dimensions, so consumers // (e.g. renderer texture caches) can detect content changes. - self.markMutated(); + self.markMutated(io); gop.value_ptr.generation = self.generation; } + /// Add an image whose decoded payload bytes have not arrived yet. + /// Returns the token required to complete this exact transmission. + pub fn addPendingImage( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + s: *terminal.Screen, + img: Image, + ) Allocator.Error!PendingImage { + assert(img.data == .pending); + try self.addImage(io, alloc, s, img); + const stored = self.images.get(img.id).?; + return .{ .id = stored.id, .generation = stored.generation }; + } + /// Add a placement for a given image. The caller must verify in advance - /// the image exists to prevent memory corruption. + /// the image exists to prevent memory corruption. On success, storage + /// owns `p`; on error, the caller retains ownership. The screen must own + /// any tracked pin in `p` and in the placement it replaces. pub fn addPlacement( self: *ImageStorage, + io: std.Io, alloc: Allocator, + s: *terminal.Screen, image_id: u32, placement_id: u32, p: Placement, @@ -253,6 +372,12 @@ pub const ImageStorage = struct { p, }); + // When we add a placement, take this opportunity to reap garbage. + // Garbage are placements that disappeared off scrollback (were + // pruned). We don't clear Kitty state in the hot path so we do + // this opportunistically here. + self.reapGarbagePlacements(io, s); + // The important piece here is that the placement ID needs to // be marked internal if it is zero. This allows multiple placements // to be added for the same image. If it is non-zero, then it is @@ -273,9 +398,227 @@ pub const ImageStorage = struct { }; const gop = try self.placements.getOrPut(alloc, key); + if (gop.found_existing) { + gop.value_ptr.deinit(s); + } else { + const img = self.images.getPtr(image_id).?; + img.metadata.placement_count = std.math.add( + @TypeOf(img.metadata.placement_count), + img.metadata.placement_count, + 1, + ) catch { + self.placements.removeByPtr(gop.key_ptr); + return error.OutOfMemory; + }; + } gop.value_ptr.* = p; - self.markMutated(); + // This always mutates + self.markMutated(io); + } + + /// How the row operation behind a scrollMarginsBegin/end pair moves + /// tracked pins, which determines how much repositioning work the + /// placements need. + pub const ScrollOp = enum { + /// The operation shifts the entire active window down (it + /// creates scrollback), so every placement anchored in the + /// active area changes active position and must be restored. + window_shift, + + /// The operation moves rows in place within the scrolling + /// region: pins anchored outside the region rows keep their + /// active position without help, so only placements anchored + /// inside the region rows need handling. This is the common + /// case (e.g. a status bar image beside a scrolling pane + /// costs almost nothing per scroll). + in_place, + }; + + /// Adjust placements for a scroll of the terminal's scrolling region + /// by `delta` rows (negative moves content up). This implements the + /// Kitty graphics protocol behavior for scrolls bounded by margins: + /// placements entirely inside the scrolling region move with the content + /// and are clipped when the move would extend them past a margin (deleted + /// when fully clipped), while every other placement (straddling a margin, + /// outside the region, or in the scrollback) must not move at all. + /// + /// This is split into two phases around the row operation because + /// the various scroll implementations move tracked pins in + /// inconsistent ways (some shift the active area so every pin moves, + /// some rotate rows in place and adjust only pins inside the + /// region). We record the desired final position of every placement + /// up front in the returned state, whose end() repositions the pins + /// once the rows have settled, making the result independent of the + /// path taken. Every call must be paired with exactly one end(). + /// + /// Callers must skip this entirely when the scrolling region is the + /// full screen: a full-screen scroll moves placements with their + /// anchored rows (possibly into the scrollback) via pin tracking, + /// which already matches kitty's marginless scroll behavior. + pub fn scrollMarginsBegin( + self: *ImageStorage, + io: std.Io, + t: *terminal.Terminal, + delta: isize, + op: ScrollOp, + ) ScrollMargins { + const s: *terminal.Screen = t.screens.active; + assert(self == &s.kitty_images); + var result: ScrollMargins = .{ .screen = s }; + + const top: i64 = t.scrolling_region.top; + const bottom: i64 = t.scrolling_region.bottom; + + var mutated = false; + var it = self.placements.iterator(); + while (it.next()) |entry| { + const p: *Placement = entry.value_ptr; + + // Virtual placements follow their placeholder cells and + // relative placements follow their parents, so neither is + // ever adjusted by scrolls, matching kitty. + const pin: *PageList.Pin = switch (p.location) { + .pin => |pin| pin, + .virtual, .relative => continue, + }; + + // Pruned placements are reaped by reapGarbagePlacements. + if (pin.garbage) continue; + + // Placements anchored outside the active area (scrollback) + // are never touched by a scroll within the margins. + const coord = (s.pages.pointFromPin( + .active, + pin.*, + ) orelse continue).coord(); + const y: i64 = coord.y; + + // An in-place operation doesn't touch pins anchored outside + // the region rows, and a placement anchored there can never + // be entirely inside the region, so it needs no work at all. + if (op == .in_place and (y < top or y > bottom)) continue; + + // The final position defaults to unmoved; restoring the pin + // to this exact spot afterwards is what stops the row + // operations from dragging the placement around. + var final_y: i64 = y; + + inside: { + const image = self.images.get(entry.key_ptr.image_id) orelse break :inside; + const grid = p.gridSize(image, t); + + // Unknown geometry (e.g. pixel sizes not yet reported) + // means we can't know the extent, so we can't consider + // the placement contained. + if (grid.rows == 0 or grid.cols == 0) break :inside; + + // Only placements entirely within the scrolling region + // move. Kitty only has top/bottom margins so it only + // checks rows; the column check is our generalization + // for left/right margins and is trivially true for + // full-width regions. + if (y < top or y + grid.rows - 1 > bottom) break :inside; + const x: i64 = coord.x; + if (x < t.scrolling_region.left or + @min(x + grid.cols - 1, @as(i64, t.cols) - 1) > t.scrolling_region.right) break :inside; + + const new_y: i64 = y + delta; + const rows: i64 = grid.rows; + const top_clip: i64 = @max(0, top - new_y); + const bottom_clip: i64 = @max(0, new_y + rows - 1 - bottom); + const visible: bool = clip: { + if (top_clip >= rows or bottom_clip >= rows) break :clip false; + + if (top_clip > 0) { + if (!p.clipTop( + image, + t, + @intCast(top_clip), + grid.rows, + )) break :clip false; + mutated = true; + final_y = top; + break :clip true; + } + + if (bottom_clip > 0) { + if (!p.clipBottom( + image, + t, + @intCast(bottom_clip), + grid.rows, + )) break :clip false; + mutated = true; + } + + final_y = new_y; + break :clip true; + }; + + // Scrolled or clipped entirely out of the region: the + // placement is deleted, like kitty. The image itself is + // retained for future placements. + if (!visible) { + self.removePlacement(s, entry); + mutated = true; + continue; + } + } + + result.restores.append(s.alloc, .{ + .pin = pin, + .x = pin.x, + .y = @intCast(final_y), + }) catch { + // OOM: this placement is left to the whims of the + // generic pin tracking. Degraded, but safe. + log.warn("OOM adjusting image placement for scroll", .{}); + continue; + }; + } + + if (mutated) { + // Placements deleted by clipping may orphan relative placements. + // Orphans have no pins so this never touches the restores. + _ = self.removeOrphans(s, null); + self.markMutated(io); + } + + return result; + } + + /// Reap pin-backed placements whose tracked content has been pruned + /// from history, along with any relative placements orphaned by + /// that, marking the content mutation. + /// + /// Virtual and relative placements have no tracked screen location and + /// are never pruned themselves. Kitty removes placements once they + /// scroll out of retained history. + fn reapGarbagePlacements( + self: *ImageStorage, + io: std.Io, + s: *terminal.Screen, + ) void { + var removed = false; + var it = self.placements.iterator(); + while (it.next()) |entry| { + const pin = switch (entry.value_ptr.location) { + .pin => |pin| pin, + .virtual, .relative => continue, + }; + if (!pin.garbage) continue; + + self.removePlacement(s, entry); + removed = true; + } + if (!removed) return; + + // If we removed a placement, then also remove any orphan + // children if this was a parent. + _ = self.removeOrphans(s, null); + + self.markMutated(io); } fn clearPlacements(self: *ImageStorage, s: *terminal.Screen) void { @@ -284,6 +627,290 @@ pub const ImageStorage = struct { self.placements.clearRetainingCapacity(); } + fn removePlacementsByImageId( + self: *ImageStorage, + s: *terminal.Screen, + image_id: u32, + ) void { + var it = self.placements.iterator(); + while (it.next()) |entry| { + if (entry.key_ptr.image_id != image_id) continue; + self.removePlacement(s, entry); + } + } + + /// Remove a placement by its map entry, releasing any tracked pin + /// and keeping the image's placement count in sync. The entry must + /// point into the placements map (via iteration or getEntry). + fn removePlacement( + self: *ImageStorage, + s: *terminal.Screen, + entry: PlacementMap.Entry, + ) void { + entry.value_ptr.deinit(s); + const img = self.images.getPtr(entry.key_ptr.image_id).?; + assert(img.metadata.placement_count > 0); + img.metadata.placement_count -= 1; + self.placements.removeByPtr(entry.key_ptr); + } + + /// Remove relative placements whose parent placement no longer + /// exists, keeping a relative placement's lifetime tied to its + /// parent chain. Chains can be several links deep, so this loops + /// until a pass removes nothing to take out entire orphaned + /// subtrees. Returns true if anything was removed. + /// + /// If `delete_unused` is non-null, an image left without placements + /// by the reap is freed using it. This matches uppercase delete + /// semantics; every other removal path retains image data and + /// passes null. + /// + /// This must be called, outside of any placements iteration, after + /// every operation that removes placements. Kitty gets the same + /// effect lazily by dropping unresolvable placements while drawing; + /// we do it eagerly because our renderer never mutates terminal + /// state. + fn removeOrphans( + self: *ImageStorage, + s: *terminal.Screen, + delete_unused: ?Allocator, + ) bool { + var removed_any = false; + var removed = true; + while (removed) { + removed = false; + var it = self.placements.iterator(); + while (it.next()) |entry| { + const rel = switch (entry.value_ptr.location) { + .relative => |rel| rel, + .pin, .virtual => continue, + }; + if (self.placements.contains(rel.parent)) continue; + + // Parent is gone, remove this placement. + const image_id = entry.key_ptr.image_id; + self.removePlacement(s, entry); + removed = true; + removed_any = true; + + if (delete_unused) |alloc| self.deleteIfUnused( + alloc, + image_id, + ); + } + } + + return removed_any; + } + + /// Maximum number of parent links in a relative placement chain, + /// matching the minimum specified in the spec and the actual + /// limit defined by Kitty at the time of authoring. + pub const parent_chain_limit = 8; + + pub const ParentError = error{ + /// The parent image (P=) does not exist. + ParentImageNotFound, + /// The parent image exists but the requested placement (Q=, or + /// any placement when Q is omitted) does not. + ParentPlacementNotFound, + /// The placement refers to itself as its own parent. + SelfParent, + /// The parent chain loops back to the placement being created. + Cycle, + /// The parent chain exceeds parent_chain_limit links. + TooDeep, + /// An ancestor in the chain no longer exists. This should not + /// happen since removeOrphans keeps chains intact, but we + /// check anyway rather than trusting the invariant. + AncestorNotFound, + }; + + /// Resolve and validate the parent reference (P=/Q=) of a relative + /// placement, returning the concrete key of the parent placement. + /// `child` is the key of the placement being created when it is + /// addressable (an explicit placement ID); null for placements that + /// will receive a fresh internal ID, which nothing can refer to yet. + /// + /// Checks: the parent must exist, the placement must not + /// parent itself, and the resulting ancestor chain must be acyclic + /// and within parent_chain_limit. + pub fn resolveParent( + self: *ImageStorage, + io: std.Io, + s: *terminal.Screen, + child: ?PlacementKey, + parent_image_id: u32, + parent_placement_id: u32, + ) ParentError!PlacementKey { + // Reap placements whose content has been pruned from history + // before resolving: a pruned parent must be reported as missing, + // not accepted and then immediately reaped by addPlacement's own + // sweep, which would store an orphan. + self.reapGarbagePlacements(io, s); + + // If the parent doesn't exist we're already failed. + if (!self.images.contains(parent_image_id)) { + return error.ParentImageNotFound; + } + + // Find the parent + const parent: PlacementKey = parent: { + // An explicit parent placement ID (Q=) selects exactly that + // placement. + if (parent_placement_id > 0) { + const key: PlacementKey = .{ + .image_id = parent_image_id, + .placement_id = .{ + .tag = .external, + .id = parent_placement_id, + }, + }; + if (!self.placements.contains(key)) { + return error.ParentPlacementNotFound; + } + break :parent key; + } + + // No Q: pick a placement of the parent image. Kitty picks + // the oldest surviving placement; our placement map doesn't + // track creation order so we pick by PlacementId.preferredOver + // instead. This is unspecified so any behavior here is fine. + // In practice the parent image has a single placement, and + // clients use Q when it doesn't. + const best: PlacementId = best: { + var best: ?PlacementId = null; + var it = self.placements.keyIterator(); + while (it.next()) |key| { + if (key.image_id != parent_image_id) continue; + const id = key.placement_id; + const b = best orelse { + best = id; + continue; + }; + if (id.preferredOver(b)) best = id; + } + break :best best orelse return error.ParentPlacementNotFound; + }; + + break :parent .{ + .image_id = parent_image_id, + .placement_id = best, + }; + }; + + // A placement cannot be its own parent. This must be checked + // before the chain walk so it reports EINVAL, not ECYCLE. + if (child) |c| if (parent.eql(c)) return error.SelfParent; + + // Walk the would-be ancestor chain. `depth` counts parent links, + // starting at one for the link we are about to create. + var depth: usize = 1; + var key = parent; + while (true) { + if (child) |c| if (key.eql(c)) return error.Cycle; + const p = self.placements.get(key) orelse return error.AncestorNotFound; + const rel = switch (p.location) { + .relative => |rel| rel, + // A pin or virtual placement is the chain root. + .pin, .virtual => break, + }; + if (depth >= parent_chain_limit) return error.TooDeep; + depth += 1; + key = rel.parent; + } + + return parent; + } + + /// The result of resolving a relative placement's parent chain: + /// the chain's root placement (always pin or virtual, never + /// relative) and the total cell offset from the root's origin. + pub const ResolvedChain = struct { + root_key: PlacementKey, + root: Placement, + horizontal_offset: i32, + vertical_offset: i32, + }; + + /// Resolve a relative placement's parent chain to its root, + /// accumulating the cell offsets (H=/V=) of every link on the way. + /// The placement's position is the root's origin plus the accumulated + /// offsets. + /// + /// Returns null when the chain is broken or too deep. Neither can + /// normally happen for stored placements (resolveParent validates + /// chains and removeOrphans removes broken ones), with one kitty + /// quirk: replacing an ancestor placement can deepen the chains + /// below it beyond parent_chain_limit after the fact. + pub fn resolveChain( + self: *const ImageStorage, + rel: Placement.Relative, + ) ?ResolvedChain { + var horizontal = rel.horizontal_offset; + var vertical = rel.vertical_offset; + var key = rel.parent; + var depth: usize = 1; + while (true) { + const p = self.placements.get(key) orelse return null; + switch (p.location) { + .relative => |parent_rel| { + if (depth >= parent_chain_limit) return null; + depth += 1; + horizontal +|= parent_rel.horizontal_offset; + vertical +|= parent_rel.vertical_offset; + key = parent_rel.parent; + }, + + .pin, .virtual => return .{ + .root_key = key, + .root = p, + .horizontal_offset = horizontal, + .vertical_offset = vertical, + }, + } + } + } + + /// Returns the placement that a unicode placeholder cell referencing + /// this image/placement ID pair targets, or null if there is none. A + /// zero placement ID targets one of the image's virtual placements, + /// chosen by PlacementId.preferredOver so the choice is stable (an + /// image rarely has more than one). This is the shared lookup used + /// both for sizing placeholder runs and for positioning relative + /// placements whose chain roots at a virtual placement. + pub fn placeholderTarget( + self: *const ImageStorage, + image_id: u32, + placement_id: u32, + ) ?struct { key: PlacementKey, placement: Placement } { + if (placement_id > 0) { + const key: PlacementKey = .{ + .image_id = image_id, + .placement_id = .{ .tag = .external, .id = placement_id }, + }; + const p = self.placements.get(key) orelse return null; + return .{ .key = key, .placement = p }; + } + + var best: ?PlacementKey = null; + var it = self.placements.iterator(); + while (it.next()) |entry| { + if (entry.key_ptr.image_id != image_id) continue; + if (entry.value_ptr.location != .virtual) continue; + const b = best orelse { + best = entry.key_ptr.*; + continue; + }; + if (entry.key_ptr.placement_id.preferredOver(b.placement_id)) { + best = entry.key_ptr.*; + } + } + + const key = best orelse return null; + return .{ .key = key, .placement = self.placements.get(key).? }; + } + /// Get an image by its ID. If the image doesn't exist, null is returned. pub fn imageById(self: *const ImageStorage, image_id: u32) ?Image { return self.images.get(image_id); @@ -307,46 +934,285 @@ pub const ImageStorage = struct { return newest; } + /// Get a mutable pointer to a stored image, by ID or (newest by) + /// number, following the protocol's id/number addressing. Used by + /// the animation commands, which mutate images in place. The + /// pointer is invalidated by any operation that adds or removes + /// images. + pub fn imagePtrByIdOrNumber( + self: *const ImageStorage, + image_id: u32, + image_number: u32, + ) ?*Image { + if (image_id != 0) return self.images.getPtr(image_id); + + var newest: ?*Image = null; + var it = self.images.iterator(); + while (it.next()) |kv| { + if (kv.value_ptr.number != image_number) continue; + if (newest == null or + kv.value_ptr.generation > newest.?.generation) + { + newest = kv.value_ptr; + } + } + + return newest; + } + + /// Record that the displayed content of an image changed without + /// the image being re-added: marks the storage mutated and stamps + /// the image with the fresh generation so consumers (e.g. the + /// renderer's texture cache) replace what they hold. Used when an + /// animation changes which frame is current or edits the current + /// frame's pixels. + pub fn markImageContentChanged( + self: *ImageStorage, + io: std.Io, + img: *Image, + ) void { + self.markMutated(io); + img.generation = self.generation; + } + + /// Convert a stored image's base data to RGBA in place, adjusting + /// byte accounting. All animation composition happens in RGBA; + /// this is called before the first composition into an image. + /// + /// The pixels are unchanged visually but the stored representation + /// changed, so the image is stamped with a fresh generation. + pub fn convertImageToRgba( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + img: *Image, + ) Allocator.Error!void { + if (img.format == .rgba) return; + const old = img.data.bytes() orelse return; + + const rgba = try pixel.rgbaFromFormat(alloc, img.format, old); + self.total_bytes -= old.len; + self.total_bytes += rgba.len; + img.data.deinit(alloc); + img.data = .{ .complete = rgba }; + img.format = .rgba; + self.markImageContentChanged(io, img); + } + + /// Reserve `bytes` of storage for animation frame data belonging + /// to `image_id`, evicting other images if needed, mirroring how + /// image transmission reserves space. + /// + /// Errors if the space cannot be made available. On success the caller + /// owns the reservation and must either attach the frame data to the + /// image or call releaseAnimationBytes. + pub fn reserveAnimationBytes( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + s: *terminal.Screen, + image_id: u32, + bytes: usize, + ) Allocator.Error!void { + if (bytes > self.total_limit) return error.OutOfMemory; + + const total_bytes = self.total_bytes + bytes; + if (total_bytes > self.total_limit) { + const req_bytes = total_bytes - self.total_limit; + // Excess this large cannot be recovered by evicting other + // images (evictImageExcept also requires it). + if (req_bytes > self.total_limit) return error.OutOfMemory; + log.info("evicting images for animation frame, evicting={}", .{req_bytes}); + if (!self.evictImageExcept( + io, + alloc, + s, + req_bytes, + image_id, + )) { + log.warn("failed to evict enough images for animation frame", .{}); + return error.OutOfMemory; + } + } + + self.total_bytes += bytes; + } + + /// Release a reservation made by reserveAnimationBytes, or credit + /// bytes freed by deleting animation frame data. + pub fn releaseAnimationBytes(self: *ImageStorage, bytes: usize) void { + assert(bytes <= self.total_bytes); + self.total_bytes -= bytes; + } + + /// Advance every running animation to the frame that should be + /// displayed at `now_ms` and report when the next frame change is + /// due, as a delay in milliseconds relative to `now_ms`. Null + /// means no running animation needs a future tick. + /// + /// `now_ms` is a monotonic timestamp on a clock of the caller's + /// choosing. The same clock must be used for every call. The + /// caller is expected to be the renderer, ticking once per frame + /// build and scheduling a wakeup for the returned delay. + pub fn animationTick(self: *ImageStorage, io: std.Io, now_ms: u64) ?u64 { + var min_delay: ?u64 = null; + + var it = self.images.iterator(); + while (it.next()) |entry| { + const img: *Image = entry.value_ptr; + + // The gates below mirror Kitty's image_is_animatable. + + // No animation state was ever attached (plain image). + const anim = img.animation orelse continue; + + // Stopped is the initial state of every animation: frames + // then only change client-driven (a=a c=N), never by time. + if (anim.state == .stopped) continue; + + // Only the root frame exists; there is nothing to advance + // to yet even in the running state. + if (anim.frames.items.len == 0) continue; + + // Unplaced images don't animate. This is our simpler + // approximation of Kitty's "is actually drawn" visibility + // gate; it is what stops an image that was transmitted but + // never placed from waking the renderer forever. + if (img.metadata.placement_count == 0) continue; + + // The base pixel data hasn't arrived yet (e.g. an image + // restored from a snapshot); nothing can be displayed. + if (img.data.isPending()) continue; + + // A zero total duration means every frame is gapless and + // no frame can ever be displayed, so the animation can + // never advance. This also guards the gapless-skip loop + // below from never terminating. + if (anim.durationMs() == 0) continue; + + // A finite loop budget (a=a v=N) that ran out on an + // earlier tick froze playback on the last frame for good. + if (anim.max_loops > 0 and anim.current_loop >= anim.max_loops) continue; + + const shown_at: u64 = shown_at: { + // First tick since playback started (or since the + // current frame changed through another path, e.g. + // a=a c=N): the frame is considered shown as of now, + // and its gap starts counting from here. + const at = anim.frame_shown_at_ms orelse break :shown_at now_ms; + + // A timestamp from the future means the caller's clock + // restarted; re-anchor rather than stalling until the + // old timestamp comes around again. + if (at > now_ms) break :shown_at now_ms; + + break :shown_at at; + }; + anim.frame_shown_at_ms = shown_at; + + // The current frame is replaced once its gap has elapsed. + // We advance at most one displayed frame per tick with no + // catch-up, exactly like Kitty: if ticks lag behind the + // gaps, the animation slows down rather than skipping. + var next_at: u64 = shown_at +| anim.gapAt(anim.current_index); + if (now_ms >= next_at) advance: { + // Walk forward to the next displayable frame. This is + // a loop only because gapless (gap=0) frames are never + // displayed and are stepped over; the durationMs gate + // above guarantees a displayable frame exists. + const count: u32 = anim.frameCount(); + var idx = anim.current_index; + while (true) { + const next = (idx + 1) % count; + if (next == 0) { + // Wrapping past the last frame back to the + // root. A loading-state (a=a s=2) animation + // refuses the wrap: it parks on the last frame + // awaiting more frames from the client. + if (anim.state == .loading) break :advance; + + // Each wrap completes a loop; a finite budget + // that just ran out parks on the last frame. + anim.current_loop += 1; + if (anim.max_loops > 0 and + anim.current_loop >= anim.max_loops) break :advance; + } + idx = next; + if (anim.gapAt(idx) != 0) break; + } + + // Show the chosen frame: restart its gap timer and + // stamp a fresh generation so consumers (the renderer + // texture cache, the C API) pick up the new pixels. + anim.current_index = idx; + anim.frame_shown_at_ms = now_ms; + self.markImageContentChanged(io, img); + next_at = now_ms +| anim.gapAt(idx); + } + + // Schedule the next tick. A parked animation left next_at + // in the past and so never schedules one; it is woken by + // its trigger instead (a new frame arriving, or an a=a + // command changing the state). + if (next_at > now_ms) { + const delay = next_at - now_ms; + min_delay = if (min_delay) |m| @min(m, delay) else delay; + } + } + + return min_delay; + } + + /// Clear placements intersecting the active screen, then reclaim every + /// image with no remaining placement. Unlike protocol d=A, a terminal + /// clear also reclaims images that were already unplaced. + pub fn clearScreen( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + t: *terminal.Terminal, + ) void { + const placements_before = self.placements.count(); + const images_before = self.images.count(); + + // Delete unused placements and images. Orphaned relative + // placements must be reaped before the image sweep so that + // their images are reclaimable too. + self.deleteVisiblePlacements(alloc, t, true); + _ = self.removeOrphans(t.screens.active, null); + var image_it = self.images.iterator(); + while (image_it.next()) |entry| { + self.deleteIfUnused(alloc, entry.key_ptr.*); + } + + // Mark mutated only if things changed. + if (self.placements.count() != placements_before or + self.images.count() != images_before) self.markMutated(io); + } + /// Delete placements, images. pub fn delete( self: *ImageStorage, + io: std.Io, alloc: Allocator, t: *terminal.Terminal, - cmd: command.Delete, + cmd: command.Delete.Action, ) void { // Deletes only ever remove placements/images, so comparing counts // before and after tells us whether anything actually changed. - // Only then do we mark a mutation. This matters because a - // delete-all runs on every screen clear (e.g. `ESC [ 2 J`), and - // we don't want empty clears to dirty the image state or bump - // the generation. + // Only then do we mark a mutation, so a delete that matches nothing + // doesn't dirty the image state or bump the generation. const placements_before = self.placements.count(); const images_before = self.images.count(); defer if (self.placements.count() != placements_before or - self.images.count() != images_before) self.markMutated(); + self.images.count() != images_before) self.markMutated(io); switch (cmd) { - .all => |delete_images| { - var it = self.placements.iterator(); - while (it.next()) |entry| { - // Skip virtual placements - switch (entry.value_ptr.location) { - .pin => {}, - .virtual => continue, - } - - // Deinit the placement and remove it - const image_id = entry.key_ptr.image_id; - entry.value_ptr.deinit(t.screens.active); - self.placements.removeByPtr(entry.key_ptr); - if (delete_images) self.deleteIfUnused(alloc, image_id); - } - - if (delete_images) { - var image_it = self.images.iterator(); - while (image_it.next()) |kv| self.deleteIfUnused(alloc, kv.key_ptr.*); - } - }, + .all => |delete_images| self.deleteVisiblePlacements( + alloc, + t, + delete_images, + ), .id => |v| self.deleteById( alloc, @@ -435,8 +1301,7 @@ pub const ImageStorage = struct { const img = self.imageById(entry.key_ptr.image_id) orelse continue; const rect = entry.value_ptr.rect(img, t) orelse continue; if (rect.top_left.x <= x and rect.bottom_right.x >= x) { - entry.value_ptr.deinit(t.screens.active); - self.placements.removeByPtr(entry.key_ptr); + self.removePlacement(t.screens.active, entry); if (v.delete) self.deleteIfUnused(alloc, img.id); } } @@ -464,8 +1329,7 @@ pub const ImageStorage = struct { var target_pin_copy = target_pin; target_pin_copy.x = rect.top_left.x; if (target_pin_copy.isBetween(rect.top_left, rect.bottom_right)) { - entry.value_ptr.deinit(t.screens.active); - self.placements.removeByPtr(entry.key_ptr); + self.removePlacement(t.screens.active, entry); if (v.delete) self.deleteIfUnused(alloc, img.id); } } @@ -475,7 +1339,9 @@ pub const ImageStorage = struct { var it = self.placements.iterator(); while (it.next()) |entry| { switch (entry.value_ptr.location) { - .pin => {}, + // Relative placements carry their own z value and + // are matched by z deletes just like kitty does. + .pin, .relative => {}, // Virtual placeholders cannot delete by z according // to the spec. @@ -484,37 +1350,99 @@ pub const ImageStorage = struct { if (entry.value_ptr.z == v.z) { const image_id = entry.key_ptr.image_id; - entry.value_ptr.deinit(t.screens.active); - self.placements.removeByPtr(entry.key_ptr); + self.removePlacement(t.screens.active, entry); if (v.delete) self.deleteIfUnused(alloc, image_id); } } }, .range => |v| range: { - if (v.first <= 0 or v.last <= 0) { - log.warn("delete range values must be greater than zero", .{}); - break :range; - } - if (v.first > v.last) { - log.warn("delete range 'x' ({}) must be less than or equal to 'y' ({})", .{ v.first, v.last }); - break :range; + // Both bounds default to zero when omitted. An inverted range + // or a zero upper bound is not an error, it just selects + // nothing: image IDs are always non-zero. + if (v.last == 0 or v.first > v.last) break :range; + + // Remove matching placements in one pass. + var placement_it = self.placements.iterator(); + while (placement_it.next()) |entry| { + if (entry.key_ptr.image_id < v.first or + entry.key_ptr.image_id > v.last) continue; + + self.removePlacement(t.screens.active, entry); } - var it = self.placements.iterator(); - while (it.next()) |entry| { - if (entry.key_ptr.image_id >= v.first or entry.key_ptr.image_id <= v.last) { - const image_id = entry.key_ptr.image_id; - entry.value_ptr.deinit(t.screens.active); - self.placements.removeByPtr(entry.key_ptr); - if (v.delete) self.deleteIfUnused(alloc, image_id); + // Uppercase deletion also frees matching images that are now + // unused, including images that had no placements initially. + if (!v.delete) break :range; + var image_it = self.images.iterator(); + while (image_it.next()) |entry| { + const image_id = entry.key_ptr.*; + if (image_id >= v.first and image_id <= v.last) { + self.deleteIfUnused(alloc, image_id); } } }, - // We don't support animation frames yet so they are successfully - // deleted! - .animation_frames => {}, + .animation_frames => |v| self.deleteAnimationFrame( + io, + alloc, + t.screens.active, + v, + ), + } + + // Deleting placements orphans any relative placements parented + // to them (transitively). Their lifetime is tied to the parent + // so they are removed as well, and an uppercase delete also + // frees any image the cascade leaves without placements (the + // per-branch deleteIfUnused calls above ran while the orphans + // still counted as placements). + const delete_unused: bool = switch (cmd) { + .all, .intersect_cursor => |v| v, + inline else => |v| v.delete, + }; + _ = self.removeOrphans( + t.screens.active, + if (delete_unused) alloc else null, + ); + } + + /// Delete only non-virtual placements that intersect the active screen. + /// The protocol defines d=a/A in terms of visible placements, and an + /// uppercase delete only frees data for images selected by those + /// placements. + fn deleteVisiblePlacements( + self: *ImageStorage, + alloc: Allocator, + t: *terminal.Terminal, + delete_unused: bool, + ) void { + var it = self.placements.iterator(); + while (it.next()) |entry| { + const pin = switch (entry.value_ptr.location) { + .pin => |pin| pin, + // Virtual placements are never selected by visible + // deletes per the protocol. Relative placements are + // removed with their parents instead (removeOrphans). + .virtual, .relative => continue, + }; + if (pin.garbage) continue; + + // Placements anchored in the active area are necessarily visible. + // Only compute their extent when the anchor is already in history + // and the bottom edge may still intersect the active area. + if (t.screens.active.pages.pointFromPin( + .active, + pin.*, + ) == null) { + const image = self.imageById(entry.key_ptr.image_id) orelse continue; + const rect = entry.value_ptr.rect(image, t) orelse continue; + if (t.screens.active.pages.pointFromPin(.active, rect.bottom_right) == null) continue; + } + + const image_id = entry.key_ptr.image_id; + self.removePlacement(t.screens.active, entry); + if (delete_unused) self.deleteIfUnused(alloc, image_id); } } @@ -526,47 +1454,124 @@ pub const ImageStorage = struct { placement_id: u32, delete_unused: bool, ) void { + var matched = placement_id == 0; + // If no placement, we delete all placements with the ID - if (placement_id == 0) { - var it = self.placements.iterator(); - while (it.next()) |entry| { - if (entry.key_ptr.image_id == image_id) { - entry.value_ptr.deinit(s); - self.placements.removeByPtr(entry.key_ptr); - } - } - } else { - if (self.placements.getEntry(.{ - .image_id = image_id, - .placement_id = .{ .tag = .external, .id = placement_id }, - })) |entry| { - entry.value_ptr.deinit(s); - self.placements.removeByPtr(entry.key_ptr); - } + if (placement_id == 0) self.removePlacementsByImageId( + s, + image_id, + ) else if (self.placements.getEntry(.{ + .image_id = image_id, + .placement_id = .{ + .tag = .external, + .id = placement_id, + }, + })) |entry| { + self.removePlacement(s, entry); + matched = true; } - // If this is specified, then we also delete the image - // if it is no longer in use. - if (delete_unused) self.deleteIfUnused(alloc, image_id); + // A placement ID narrows the selection to that exact placement, so an + // unmatched selector must not free otherwise-unreferenced image data. + // https://sw.kovidgoyal.net/kitty/graphics-protocol/#deleting-images + if (delete_unused and matched) self.deleteIfUnused(alloc, image_id); } - /// Delete an image if it is unused. - fn deleteIfUnused(self: *ImageStorage, alloc: Allocator, image_id: u32) void { - var it = self.placements.iterator(); - while (it.next()) |kv| { - if (kv.key_ptr.image_id == image_id) { - return; - } + /// Delete an animation frame (d=f/F). Deletes never produce + /// responses, so all failures are only logged. Kitty behaviors + /// implemented here: on an image without extra frames a lowercase + /// delete is a no-op while an uppercase delete removes the entire + /// image, placements included; the frame number is clamped to the + /// last frame and zero selects the root frame; deleting the root + /// frame promotes frame 2 to be the new root. + fn deleteAnimationFrame( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + s: *terminal.Screen, + v: command.Delete.Action.AnimationFrames, + ) void { + if (v.image_id == 0 and v.image_number == 0) { + log.warn("delete animation frames requires image id or number", .{}); + return; } + const img = self.imagePtrByIdOrNumber( + v.image_id, + v.image_number, + ) orelse { + log.warn( + "delete animation frames for unknown image id={} number={}", + .{ v.image_id, v.image_number }, + ); + return; + }; + + const anim: *animation.Animation = anim: { + if (img.animation) |anim| { + if (anim.frames.items.len > 0) break :anim anim; + } - // If we get here, we can delete the image. - if (self.images.getEntry(image_id)) |entry| { - self.total_bytes -= entry.value_ptr.data.len; + // The image is not (or no longer) an animation. The + // uppercase delete removes the entire image, even when it + // still has placements. + if (!v.delete) return; + self.removePlacementsByImageId(s, img.id); + const entry = self.images.getEntry(img.id).?; + self.total_bytes -= entry.value_ptr.storageSize(); entry.value_ptr.deinit(alloc); self.images.removeByPtr(entry.key_ptr); + return; + }; + + // Clamp the frame number: zero selects the root frame and + // values past the end select the last frame. + const count: u32 = anim.frameCount(); + var number: u32 = @min(v.frame, count); + if (number == 0) number = 1; + + if (number == 1) { + // Deleting the root frame promotes frame 2 to root. The + // promoted frame's bytes stay reserved; only the old root + // data is freed. + self.releaseAnimationBytes(img.data.len()); + img.data.deinit(alloc); + const promoted = anim.frames.orderedRemove(0); + img.data = .{ .complete = promoted.data }; + anim.root_gap_ms = promoted.gap_ms; + } else { + const removed = anim.frames.orderedRemove(number - 2); + self.releaseAnimationBytes(removed.data.len); + alloc.free(removed.data); + } + + // Fix up the current frame. + const removed_idx: u32 = if (number == 1) 0 else number - 2; + const remaining: u32 = @intCast(anim.frames.items.len); + if (anim.current_index > remaining) { + anim.current_index = remaining; + anim.frame_shown_at_ms = null; + self.markImageContentChanged(io, img); + return; + } + if (removed_idx == anim.current_index) { + anim.frame_shown_at_ms = null; + self.markImageContentChanged(io, img); + } else { + if (removed_idx < anim.current_index) anim.current_index -= 1; + self.markMutated(io); } } + /// Delete an image if it is unused. + fn deleteIfUnused(self: *ImageStorage, alloc: Allocator, image_id: u32) void { + const entry = self.images.getEntry(image_id) orelse return; + if (entry.value_ptr.metadata.placement_count > 0) return; + + self.total_bytes -= entry.value_ptr.storageSize(); + entry.value_ptr.deinit(alloc); + self.images.removeByPtr(entry.key_ptr); + } + /// Deletes all placements intersecting a screen point. fn deleteIntersecting( self: *ImageStorage, @@ -584,133 +1589,173 @@ pub const ImageStorage = struct { while (it.next()) |entry| { const img = self.imageById(entry.key_ptr.image_id) orelse continue; const rect = entry.value_ptr.rect(img, t) orelse continue; - if (target_pin.isBetween(rect.top_left, rect.bottom_right)) { + if (rect.contains(target_pin)) { if (filter) |f| if (!f(filter_ctx, entry.value_ptr.*)) continue; - entry.value_ptr.deinit(t.screens.active); - self.placements.removeByPtr(entry.key_ptr); + self.removePlacement(t.screens.active, entry); if (delete_unused) self.deleteIfUnused(alloc, img.id); } } } /// Evict image to make space. This will evict the oldest image, - /// prioritizing unused images first, as recommended by the published - /// Kitty spec. + /// prioritizing transient images and unused images as recommended by the + /// published Kitty spec. /// /// This will evict as many images as necessary to make space for /// req bytes. - fn evictImage(self: *ImageStorage, alloc: Allocator, req: usize) !bool { + fn evictImage( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + s: *terminal.Screen, + req: usize, + ) bool { + return self.evictImageExcept(io, alloc, s, req, null); + } + + /// Evict images while preserving `exclude_id`, used when replacing an + /// existing image whose old reservation has already been credited. + fn evictImageExcept( + self: *ImageStorage, + io: std.Io, + alloc: Allocator, + s: *terminal.Screen, + req: usize, + exclude_id: ?u32, + ) bool { assert(req <= self.total_limit); - // Ironically we allocate to evict. We should probably redesign the - // data structures to avoid this but for now allocating a little - // bit is fine compared to the megabytes we're looking to save. const Candidate = struct { id: u32, generation: u64, - used: bool, - }; - var candidates: std.ArrayList(Candidate) = .empty; - defer candidates.deinit(alloc); + // Lower values are evicted first: + // 0: transient, unused + // 1: not transient, unused + // 2: transient, used + // 3: not transient, used + priority: u2, - var it = self.images.iterator(); - while (it.next()) |kv| { - const img = kv.value_ptr; - - // This is a huge waste. See comment above about redesigning - // our data structures to avoid this. Eviction should be very - // rare though and we never have that many images/placements - // so hopefully this will last a long time. - const used = used: { - var p_it = self.placements.iterator(); - while (p_it.next()) |p_kv| { - if (p_kv.key_ptr.image_id == img.id) { - break :used true; - } - } - - break :used false; - }; - - try candidates.append(alloc, .{ - .id = img.id, - .generation = img.generation, - .used = used, - }); - } + fn init(img: *const Image) @This() { + return .{ + .id = img.id, + .generation = img.generation, + .priority = (if (img.metadata.transient) @as(u2, 0) else @as(u2, 1)) + + (if (img.metadata.placement_count > 0) @as(u2, 2) else @as(u2, 0)), + }; + } - // Sort - std.mem.sortUnstable( - Candidate, - candidates.items, - {}, - struct { - fn lessThan( - ctx: void, - lhs: Candidate, - rhs: Candidate, - ) bool { - _ = ctx; - - // If their usage matches, then it's based on the - // generation stamp, which orders by transmit time. - // (Stamps are unique but tie-break by ID anyway to - // stay deterministic for hand-built test images.) - if (lhs.used == rhs.used) return if (lhs.generation == rhs.generation) - lhs.id < rhs.id - else - lhs.generation < rhs.generation; - - // If not used, then its a better candidate - return !lhs.used; - } - }.lessThan, - ); + fn lessThan(lhs: @This(), rhs: @This()) bool { + if (lhs.priority != rhs.priority) + return lhs.priority < rhs.priority; + if (lhs.generation != rhs.generation) + return lhs.generation < rhs.generation; + return lhs.id < rhs.id; + } + }; // Evicting anything is a content mutation. This matters for the // setLimit path in particular, which doesn't otherwise mark it. - var any_evicted = false; - defer if (any_evicted) self.markMutated(); + // Evicted placements can also orphan relative placements of + // other images, which must be reaped along with them. + const images_before = self.images.count(); + defer if (self.images.count() != images_before) { + _ = self.removeOrphans(s, null); + self.markMutated(io); + }; - // They're in order of best to evict. var evicted: usize = 0; - for (candidates.items) |c| { - // Delete all the placements for this image and the image. + while (evicted < req) { + const c = candidate: { + var best: ?Candidate = null; + var it = self.images.iterator(); + while (it.next()) |kv| { + const img = kv.value_ptr; + if (exclude_id != null and img.id == exclude_id.?) continue; + + const current = Candidate.init(img); + if (best == null or current.lessThan(best.?)) best = current; + } + break :candidate best orelse return false; + }; + var p_it = self.placements.iterator(); while (p_it.next()) |entry| { if (entry.key_ptr.image_id == c.id) { - self.placements.removeByPtr(entry.key_ptr); - any_evicted = true; + self.removePlacement(s, entry); } } - if (self.images.getEntry(c.id)) |entry| { - log.info("evicting image id={} bytes={}", .{ c.id, entry.value_ptr.data.len }); + const entry = self.images.getEntry(c.id).?; + const image_len = entry.value_ptr.storageSize(); + log.info("evicting image id={} bytes={}", .{ c.id, image_len }); - evicted += entry.value_ptr.data.len; - self.total_bytes -= entry.value_ptr.data.len; + evicted += image_len; + self.total_bytes -= image_len; - entry.value_ptr.deinit(alloc); - self.images.removeByPtr(entry.key_ptr); - any_evicted = true; - - if (evicted > req) return true; - } + entry.value_ptr.deinit(alloc); + self.images.removeByPtr(entry.key_ptr); } - return false; + return true; } + /// State returned by scrollMarginsBegin: the final active-area + /// position every surviving placement pin must be restored to once + /// the scrolled rows have settled. Every begin must be paired with + /// exactly one end() call after the scroll's row operations + /// complete. + pub const ScrollMargins = struct { + screen: *terminal.Screen, + restores: std.ArrayListUnmanaged(Restore) = .empty, + + const Restore = struct { + pin: *PageList.Pin, + x: size.CellCountInt, + y: u32, + }; + + /// Reposition every recorded placement pin to its post-scroll + /// position and release the state. Must be called exactly + /// once, after the scroll's row operations complete. + pub fn end(self: *ScrollMargins) void { + for (self.restores.items) |restore| { + restore.pin.* = self.screen.pages.pin(.{ .active = .{ + .x = restore.x, + .y = restore.y, + } }) orelse continue; + } + self.restores.deinit(self.screen.alloc); + } + }; + /// Every placement is uniquely identified by the image ID and the /// placement ID. If an image ID isn't specified it is assumed to be 0. /// Likewise, if a placement ID isn't specified it is assumed to be 0. pub const PlacementKey = struct { image_id: u32, - placement_id: packed struct { - tag: enum(u1) { internal, external }, - id: u32, - }, + placement_id: PlacementId, + + pub fn eql(self: PlacementKey, other: PlacementKey) bool { + return std.meta.eql(self, other); + } + }; + + /// Internal placement IDs are assigned by us for placements created + /// without an explicit ID (p=0); external IDs are client-specified. + /// The two are separate namespaces, hence the tag. + pub const PlacementId = packed struct { + tag: enum(u1) { internal, external }, + id: u32, + + /// Deterministic preference order used when an operation must + /// pick a single placement out of several (kitty uses creation + /// order, which our map doesn't track): external IDs win over + /// internal ones, and lower IDs win within a tag. + pub fn preferredOver(self: PlacementId, other: PlacementId) bool { + if (self.tag != other.tag) return self.tag == .external; + return self.id < other.id; + } }; pub const Placement = struct { @@ -739,7 +1784,27 @@ pub const ImageStorage = struct { pin: *PageList.Pin, /// Virtual placement (U=1) for unicode placeholders. - virtual: void, + virtual, + + /// Placed relative to a parent placement (P=/Q=). The + /// placement has no screen position of its own; it is + /// positioned at render time by resolving the parent chain + /// to its root (see resolveChain) and therefore follows the + /// parent through scrolls automatically. Its lifetime is + /// tied to the parent: removing any ancestor removes it + /// too (see removeOrphans). + relative: Relative, + }; + + pub const Relative = struct { + /// The parent placement. Resolved to a concrete key when + /// the placement is created, so the parent is guaranteed + /// to exist at that point. + parent: PlacementKey, + + /// Cell offsets from the parent's origin (H=/V=). + horizontal_offset: i32 = 0, + vertical_offset: i32 = 0, }; pub fn deinit( @@ -748,10 +1813,80 @@ pub const ImageStorage = struct { ) void { switch (self.location) { .pin => |p| s.pages.untrackPin(p), - .virtual => {}, + .virtual, .relative => {}, } } + /// Multiply two protocol-controlled values without allowing them to + /// wrap. Placement geometry is exposed as u32, so values larger than + /// that are represented by the largest possible value. + fn saturatingMul(lhs: u32, rhs: u32) u32 { + return std.math.mul(u32, lhs, rhs) catch std.math.maxInt(u32); + } + + /// Scale a dimension by an aspect ratio and round to the nearest + /// integer. The u64 intermediate can hold the product of two u32s as + /// well as the rounding adjustment. + fn scaleDimension(value: u32, numerator: u32, denominator: u32) u32 { + if (denominator == 0) return 0; + + const rounded = (@as(u64, value) * @as(u64, numerator) + + @as(u64, denominator) / 2) / @as(u64, denominator); + return std.math.cast(u32, rounded) orelse std.math.maxInt(u32); + } + + pub const SourceRect = struct { + x: u32, + y: u32, + width: u32, + height: u32, + }; + + /// Returns the requested source rectangle intersected with the image. + /// A zero width or height requests the full corresponding image + /// dimension before intersection, as defined by the Kitty protocol. + pub fn sourceRect(self: Placement, image: Image) SourceRect { + const x = @min(self.source_x, image.width); + const y = @min(self.source_y, image.height); + return .{ + .x = x, + .y = y, + .width = @min( + if (self.source_width > 0) self.source_width else image.width, + image.width - x, + ), + .height = @min( + if (self.source_height > 0) self.source_height else image.height, + image.height - y, + ), + }; + } + + /// Returns the placement offset clamped within the first cell. Pixel + /// geometry may temporarily be unavailable, in which case there is no + /// valid offset within the cell. + pub fn cellOffset( + self: Placement, + t: *const terminal.Terminal, + ) struct { + x: u32, + y: u32, + } { + const cell_width: u32 = t.width_px / t.cols; + const cell_height: u32 = t.height_px / t.rows; + + return .{ + .x = if (cell_width > 0) + @min(self.x_offset, cell_width - 1) + else + 0, + .y = if (cell_height > 0) + @min(self.y_offset, cell_height - 1) + else + 0, + }; + } + /// Returns the size of this placement's image in pixels, /// taking into account the source rectangle, specified /// rows/columns, and aspect ratio. @@ -763,9 +1898,9 @@ pub const ImageStorage = struct { width: u32, height: u32, } { - // Height / width of the image in px. - const width = if (self.source_width > 0) self.source_width else image.width; - const height = if (self.source_height > 0) self.source_height else image.height; + const source = self.sourceRect(image); + const width = source.width; + const height = source.height; // If we don't have any specified cols or rows then the placement // should be the native size of the image, and doesn't need to be @@ -782,20 +1917,18 @@ pub const ImageStorage = struct { // count and the height by the row count, because it should be. const cell_width: u32 = t.width_px / t.cols; const cell_height: u32 = t.height_px / t.rows; - - const width_f64: f64 = @floatFromInt(width); - const height_f64: f64 = @floatFromInt(height); + const cell_offset = self.cellOffset(t); // If we have a specified cols AND rows then we calculate // the width and height from them directly, we don't need // to adjust for aspect ratio. if (self.columns > 0 and self.rows > 0) { - const calc_width = cell_width * self.columns; - const calc_height = cell_height * self.rows; + const calc_width = saturatingMul(cell_width, self.columns); + const calc_height = saturatingMul(cell_height, self.rows); return .{ - .width = calc_width, - .height = calc_height, + .width = calc_width -| cell_offset.x, + .height = calc_height -| cell_offset.y, }; } @@ -805,11 +1938,11 @@ pub const ImageStorage = struct { // If only the columns were specified, we determine // the height of the image based on the aspect ratio. if (self.columns > 0) { - const aspect = height_f64 / width_f64; - const calc_width: u32 = cell_width * self.columns; - const calc_height: u32 = @intFromFloat(@round( - @as(f64, @floatFromInt(calc_width)) * aspect, - )); + const calc_width = saturatingMul( + cell_width, + self.columns, + ) -| cell_offset.x; + const calc_height = scaleDimension(calc_width, height, width); return .{ .width = calc_width, @@ -820,11 +1953,11 @@ pub const ImageStorage = struct { // Otherwise, only the rows were specified, so we // determine the width based on the aspect ratio. { - const aspect = width_f64 / height_f64; - const calc_height: u32 = cell_height * self.rows; - const calc_width: u32 = @intFromFloat(@round( - @as(f64, @floatFromInt(calc_height)) * aspect, - )); + const calc_height = saturatingMul( + cell_height, + self.rows, + ) -| cell_offset.y; + const calc_width = scaleDimension(calc_height, width, height); return .{ .width = calc_width, @@ -851,15 +1984,16 @@ pub const ImageStorage = struct { // Otherwise we calculate the pixel size, divide by // cell size, and round up to the nearest integer. const calc_size = self.pixelSize(image, t); + const cell_offset = self.cellOffset(t); return .{ .cols = std.math.divCeil( u32, - calc_size.width + self.x_offset, + calc_size.width +| cell_offset.x, t.width_px / t.cols, ) catch 0, .rows = std.math.divCeil( u32, - calc_size.height + self.y_offset, + calc_size.height +| cell_offset.y, t.height_px / t.rows, ) catch 0, }; @@ -867,9 +2001,82 @@ pub const ImageStorage = struct { // in such a case it seems safe to return 0 for this. } + /// Permanently clip `count` rows off the top of this placement, + /// which currently spans `span` grid rows, by shrinking the + /// source rectangle (the requested source rect is materialized + /// into explicit values in the process). Used when a scroll + /// within margins pushes the placement past the top margin. + /// Requires 0 < count < span. Returns false if no visible + /// source pixels would remain, in which case the placement is + /// unmodified and should be deleted. + fn clipTop( + self: *Placement, + image: Image, + t: *const terminal.Terminal, + count: u32, + span: u32, + ) bool { + assert(count > 0 and count < span); + const src = self.sourceRect(image); + const crop: u32 = if (self.rows > 0) + // Scaled placement: each grid row shows an equal + // fraction of the source. + @intCast(@as(u64, src.height) * count / span) + else + // Native size: each grid row shows one cell height of + // source pixels (kitty does the same). + saturatingMul(t.height_px / t.rows, count); + if (crop >= src.height) return false; + self.source_x = src.x; + self.source_y = src.y + crop; + self.source_width = src.width; + self.source_height = src.height - crop; + if (self.rows > 0) self.rows -= count; + return true; + } + + /// clipTop, but clipping `count` rows off the bottom. + fn clipBottom( + self: *Placement, + image: Image, + t: *const terminal.Terminal, + count: u32, + span: u32, + ) bool { + assert(count > 0 and count < span); + const src = self.sourceRect(image); + // An empty source can never be clipped smaller. This also + // guarantees we never store an explicit zero source height, + // which would be reinterpreted as "full image". + if (src.height == 0) return false; + if (self.rows > 0) { + const crop: u32 = @intCast(@as(u64, src.height) * count / span); + if (crop >= src.height) return false; + self.source_height = src.height - crop; + self.rows -= count; + } else { + // The remaining rows can show this many source pixels, + // with the first cell losing cellOffset pixels to the + // placement's y offset. + const visible = saturatingMul(t.height_px / t.rows, span - count); + const offset = self.cellOffset(t).y; + if (visible <= offset) return false; + self.source_height = @min(src.height, visible - offset); + } + self.source_x = src.x; + self.source_y = src.y; + self.source_width = src.width; + return true; + } + /// Returns a selection of the entire rectangle this placement - /// occupies within the screen. This can return null if the placement - /// doesn't have an associated rect (i.e. a virtual placement). + /// occupies within the screen. This can return null for a virtual + /// placement or when unavailable pixel geometry makes it empty. + /// + /// Relative placements also return null: they have no screen + /// position of their own, so geometric queries (delete by + /// intersection, row, column, etc.) never match them directly. + /// They are instead removed when their parent chain is removed. pub fn rect( self: Placement, image: Image, @@ -878,20 +2085,25 @@ pub const ImageStorage = struct { const grid_size = self.gridSize(image, t); const pin = switch (self.location) { .pin => |p| p, - .virtual => return null, + .virtual, .relative => return null, }; + if (pin.garbage) return null; + + // A zero pixel-sized placement can produce a zero grid size when + // pixel geometry is unavailable. It occupies no rectangle. + if (grid_size.cols == 0 or grid_size.rows == 0) return null; var br = switch (pin.downOverflow(grid_size.rows - 1)) { .offset => |v| v, .overflow => |v| v.end, }; - br.x = @min( + br.x = @intCast(@min( // We need to sub one here because the x value is // one width already. So if the image is width "1" // then we add zero to X because X itself is width 1. - pin.x + (grid_size.cols - 1), - t.cols - 1, - ); + @as(u32, pin.x) +| (grid_size.cols - 1), + @as(u32, t.cols) - 1, + )); return .{ .top_left = pin.*, @@ -914,17 +2126,18 @@ fn trackPin( test "storage: add placement with zero placement id" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 100, .rows = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); - try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); - try s.addPlacement(alloc, 1, 0, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); - try s.addPlacement(alloc, 1, 0, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); try testing.expectEqual(@as(usize, 2), s.placements.count()); try testing.expectEqual(@as(usize, 2), s.images.count()); @@ -940,25 +2153,124 @@ test "storage: add placement with zero placement id" { }) != null); } -test "storage: delete all placements and images" { +test "storage: replacing placement releases tracked pin" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + + const tracked = t.screens.active.pages.countTrackedPins(); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + try testing.expectEqual( + tracked + 1, + t.screens.active.pages.countTrackedPins(), + ); + + const replacement_pin = try trackPin(&t, .{ .x = 2, .y = 2 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = replacement_pin }, + }); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual( + tracked + 1, + t.screens.active.pages.countTrackedPins(), + ); + try testing.expectEqual( + replacement_pin, + s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?.location.pin, + ); +} + +test "storage: adding placement reclaims garbage placements" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + + const tracked = t.screens.active.pages.countTrackedPins(); + const old_pin = try trackPin(&t, .{ .x = 0, .y = 0 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = old_pin }, + }); + old_pin.garbage = true; + + const new_pin = try trackPin(&t, .{ .x = 1, .y = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = new_pin }, + }); + + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual( + tracked + 1, + t.screens.active.pages.countTrackedPins(), + ); + try testing.expectEqual( + new_pin, + s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .internal, .id = 1 }, + }).?.location.pin, + ); +} + +test "storage: placement count limit permits replacement" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .virtual = {} } }); + + const img = s.images.getPtr(1).?; + img.metadata.placement_count = std.math.maxInt(@TypeOf(img.metadata.placement_count)); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .virtual = {} } }); + try testing.expectError( + error.OutOfMemory, + s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .virtual = {} } }), + ); + try testing.expectEqual(@as(usize, 1), s.placements.count()); +} + +test "storage: delete all visible placements and matching images" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .all = true }); + s.delete(io, alloc, &t, .{ .all = true }); try testing.expect(s.dirty); - try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expect(s.images.contains(3)); try testing.expectEqual(@as(usize, 0), s.placements.count()); try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); } @@ -966,45 +2278,133 @@ test "storage: delete all placements and images" { test "storage: delete all placements and images preserves limit" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); s.total_limit = 5000; - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .all = true }); + s.delete(io, alloc, &t, .{ .all = true }); try testing.expect(s.dirty); - try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expect(s.images.contains(3)); try testing.expectEqual(@as(usize, 0), s.placements.count()); try testing.expectEqual(@as(usize, 5000), s.total_limit); try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); } +test "storage: delete all visible placements preserves scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ + .rows = 2, + .cols = 2, + .max_scrollback_bytes = 4096, + }); + defer t.deinit(alloc); + t.width_px = 2; + t.height_px = 2; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 1, .height = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) }, + }); + try t.scrollUp(1); + + const history_key: ImageStorage.PlacementKey = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }; + try testing.expect(t.screens.active.pages.pointFromPin( + .active, + s.placements.get(history_key).?.location.pin.*, + ) == null); + + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ + .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) }, + }); + + s.delete(io, alloc, &t, .{ .all = true }); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expect(s.placements.contains(history_key)); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expect(s.images.contains(1)); +} + +test "storage: delete all includes placements spanning into active area" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ + .rows = 2, + .cols = 2, + .max_scrollback_bytes = 4096, + }); + defer t.deinit(alloc); + t.width_px = 2; + t.height_px = 2; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 2, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) }, + }); + try t.scrollUp(1); + + const placement = s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + try testing.expect(t.screens.active.pages.pointFromPin( + .active, + placement.location.pin.*, + ) == null); + const rect = placement.rect(s.imageById(1).?, &t).?; + try testing.expect(t.screens.active.pages.pointFromPin( + .active, + rect.bottom_right, + ) != null); + + s.delete(io, alloc, &t, .{ .all = true }); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(@as(usize, 0), s.images.count()); +} + test "storage: delete all placements" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .all = false }); + s.delete(io, alloc, &t, .{ .all = false }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 0), s.placements.count()); try testing.expectEqual(@as(usize, 3), s.images.count()); @@ -1014,20 +2414,21 @@ test "storage: delete all placements" { test "storage: delete all placements by image id" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .id = .{ .image_id = 2 } }); + s.delete(io, alloc, &t, .{ .id = .{ .image_id = 2 } }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 1), s.placements.count()); try testing.expectEqual(@as(usize, 3), s.images.count()); @@ -1037,20 +2438,21 @@ test "storage: delete all placements by image id" { test "storage: delete all placements by image id and unused images" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .id = .{ .delete = true, .image_id = 2 } }); + s.delete(io, alloc, &t, .{ .id = .{ .delete = true, .image_id = 2 } }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 1), s.placements.count()); try testing.expectEqual(@as(usize, 2), s.images.count()); @@ -1060,21 +2462,22 @@ test "storage: delete all placements by image id and unused images" { test "storage: delete placement by specific id" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .id = .{ + s.delete(io, alloc, &t, .{ .id = .{ .delete = true, .image_id = 1, .placement_id = 2, @@ -1085,10 +2488,84 @@ test "storage: delete placement by specific id" { try testing.expectEqual(tracked + 2, t.screens.active.pages.countTrackedPins()); } +test "storage: uppercase id delete preserves image when placement does not match" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + + s.dirty = false; + const generation = s.generation; + s.delete(io, alloc, &t, .{ .id = .{ + .delete = true, + .image_id = 1, + .placement_id = 7, + } }); + + try testing.expect(s.imageById(1) != null); + try testing.expect(!s.dirty); + try testing.expectEqual(generation, s.generation); +} + +test "storage: uppercase id delete frees image after placement matches" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 9, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + + s.dirty = false; + s.delete(io, alloc, &t, .{ .id = .{ + .delete = true, + .image_id = 1, + .placement_id = 9, + } }); + + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expect(s.dirty); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: uppercase id delete without placement frees unplaced image" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + + s.dirty = false; + s.delete(io, alloc, &t, .{ .id = .{ + .delete = true, + .image_id = 1, + } }); + + try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expect(s.dirty); +} + test "storage: delete intersecting cursor" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; @@ -1096,15 +2573,15 @@ test "storage: delete intersecting cursor" { var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); - try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); t.screens.active.cursorAbsolute(12, 12); s.dirty = false; - s.delete(alloc, &t, .{ .intersect_cursor = false }); + s.delete(io, alloc, &t, .{ .intersect_cursor = false }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 1), s.placements.count()); try testing.expectEqual(@as(usize, 2), s.images.count()); @@ -1117,10 +2594,66 @@ test "storage: delete intersecting cursor" { }) != null); } +test "storage: delete intersecting cursor checks interior row column" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 10, .height = 10 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 20, .y = 0 }) } }); + + // This is inside the right placement and on an interior row shared by + // both placements, but it is outside the left placement's columns. + t.screens.active.cursorAbsolute(21, 5); + s.delete(io, alloc, &t, .{ .intersect_cursor = false }); + + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); +} + +test "storage: delete intersecting cell checks interior row column" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 10, .height = 10 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 20, .y = 0 }) } }); + + // Protocol coordinates are one-based, so this targets grid cell (21, 5). + s.delete(io, alloc, &t, .{ .intersect_cell = .{ + .x = 22, + .y = 6, + } }); + + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); +} + test "storage: delete intersecting cursor plus unused" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; @@ -1128,15 +2661,15 @@ test "storage: delete intersecting cursor plus unused" { var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); - try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); t.screens.active.cursorAbsolute(12, 12); s.dirty = false; - s.delete(alloc, &t, .{ .intersect_cursor = true }); + s.delete(io, alloc, &t, .{ .intersect_cursor = true }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 1), s.placements.count()); try testing.expectEqual(@as(usize, 2), s.images.count()); @@ -1152,7 +2685,8 @@ test "storage: delete intersecting cursor plus unused" { test "storage: delete intersecting cursor hits multiple" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; @@ -1160,15 +2694,15 @@ test "storage: delete intersecting cursor hits multiple" { var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); - try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); t.screens.active.cursorAbsolute(26, 26); s.dirty = false; - s.delete(alloc, &t, .{ .intersect_cursor = true }); + s.delete(io, alloc, &t, .{ .intersect_cursor = true }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 0), s.placements.count()); try testing.expectEqual(@as(usize, 1), s.images.count()); @@ -1178,7 +2712,8 @@ test "storage: delete intersecting cursor hits multiple" { test "storage: delete by column" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; @@ -1186,13 +2721,13 @@ test "storage: delete by column" { var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); - try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .column = .{ + s.delete(io, alloc, &t, .{ .column = .{ .delete = false, .x = 60, } }); @@ -1211,19 +2746,20 @@ test "storage: delete by column" { test "storage: delete by column 1x1" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 3, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 2, .y = 0 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 1, .height = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 3, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 2, .y = 0 }) } }); - s.delete(alloc, &t, .{ .column = .{ + s.delete(io, alloc, &t, .{ .column = .{ .delete = false, .x = 2, } }); @@ -1244,7 +2780,8 @@ test "storage: delete by column 1x1" { test "storage: delete by row" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; @@ -1252,13 +2789,13 @@ test "storage: delete by row" { var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); - try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); s.dirty = false; - s.delete(alloc, &t, .{ .row = .{ + s.delete(io, alloc, &t, .{ .row = .{ .delete = false, .y = 60, } }); @@ -1277,19 +2814,20 @@ test "storage: delete by row" { test "storage: delete by row 1x1" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 100, .cols = 100 }); defer t.deinit(alloc); t.width_px = 100; t.height_px = 100; var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) } }); - try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 1 }) } }); - try s.addPlacement(alloc, 1, 3, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 2 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 1, .height = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 3, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 2 }) } }); - s.delete(alloc, &t, .{ .row = .{ + s.delete(io, alloc, &t, .{ .row = .{ .delete = false, .y = 2, } }); @@ -1310,22 +2848,23 @@ test "storage: delete by row 1x1" { test "storage: delete images by range 1" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); try testing.expectEqual(@as(usize, 3), s.images.count()); try testing.expectEqual(@as(usize, 2), s.placements.count()); s.dirty = false; - s.delete(alloc, &t, .{ .range = .{ .delete = false, .first = 1, .last = 2 } }); + s.delete(io, alloc, &t, .{ .range = .{ .delete = false, .first = 1, .last = 2 } }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 3), s.images.count()); try testing.expectEqual(@as(usize, 0), s.placements.count()); @@ -1335,22 +2874,23 @@ test "storage: delete images by range 1" { test "storage: delete images by range 2" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); try testing.expectEqual(@as(usize, 3), s.images.count()); try testing.expectEqual(@as(usize, 2), s.placements.count()); s.dirty = false; - s.delete(alloc, &t, .{ .range = .{ .delete = true, .first = 1, .last = 2 } }); + s.delete(io, alloc, &t, .{ .range = .{ .delete = true, .first = 1, .last = 2 } }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 1), s.images.count()); try testing.expectEqual(@as(usize, 0), s.placements.count()); @@ -1360,58 +2900,237 @@ test "storage: delete images by range 2" { test "storage: delete images by range 3" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 3, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); try testing.expectEqual(@as(usize, 3), s.images.count()); - try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expectEqual(@as(usize, 3), s.placements.count()); s.dirty = false; - s.delete(alloc, &t, .{ .range = .{ .delete = false, .first = 1, .last = 1 } }); + s.delete(io, alloc, &t, .{ .range = .{ .delete = false, .first = 2, .last = 2 } }); try testing.expect(s.dirty); try testing.expectEqual(@as(usize, 3), s.images.count()); - try testing.expectEqual(@as(usize, 0), s.placements.count()); - try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); + try testing.expect(s.placements.get(.{ + .image_id = 3, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); + try testing.expectEqual(tracked + 2, t.screens.active.pages.countTrackedPins()); } test "storage: delete images by range 4" { const testing = std.testing; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); const tracked = t.screens.active.pages.countTrackedPins(); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); - try s.addImage(alloc, .{ .id = 2 }); - try s.addImage(alloc, .{ .id = 3 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); - try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 3, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); try testing.expectEqual(@as(usize, 3), s.images.count()); - try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expectEqual(@as(usize, 3), s.placements.count()); s.dirty = false; - s.delete(alloc, &t, .{ .range = .{ .delete = true, .first = 1, .last = 1 } }); + s.delete(io, alloc, &t, .{ .range = .{ .delete = true, .first = 2, .last = 2 } }); try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); + try testing.expect(s.placements.get(.{ + .image_id = 3, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); + try testing.expectEqual(tracked + 2, t.screens.active.pages.countTrackedPins()); +} + +test "storage: uppercase range deletes unplaced image data" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + + s.delete(io, alloc, &t, .{ + .range = .{ + .delete = true, + // Zero is the default lower bound when x is omitted. + .first = 0, + .last = 2, + }, + }); try testing.expectEqual(@as(usize, 1), s.images.count()); - try testing.expectEqual(@as(usize, 0), s.placements.count()); - try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); + try testing.expect(s.images.contains(3)); +} + +test "storage: delete images by empty range" { + // Ranges that select nothing are a silent no-op, matching kitty, which + // performs no validation and filters with `x <= image_id <= y`. + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + // Inverted range. + s.delete(io, alloc, &t, .{ .range = .{ .delete = true, .first = 5, .last = 4 } }); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + // Upper bound omitted, so it defaults to zero. + s.delete(io, alloc, &t, .{ .range = .{ .delete = true, .first = 5, .last = 0 } }); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + // Both bounds omitted. Image IDs are never zero so this matches nothing. + s.delete(io, alloc, &t, .{ .range = .{ .delete = true, .first = 0, .last = 0 } }); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + // Both placements survive, so both of their pins are still tracked. + try testing.expectEqual(tracked + 2, t.screens.active.pages.countTrackedPins()); +} + +test "storage: erase display preserves scrollback and reclaims unplaced images" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ + .rows = 2, + .cols = 2, + .max_scrollback_bytes = 4096, + }); + defer t.deinit(alloc); + t.width_px = 2; + t.height_px = 2; + + const s = &t.screens.active.kitty_images; + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 1, .height = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) }, + }); + try t.scrollUp(1); + + const history_key: ImageStorage.PlacementKey = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }; + try testing.expect(t.screens.active.pages.pointFromPin( + .active, + s.placements.get(history_key).?.location.pin.*, + ) == null); + + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 1, .height = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) }, + }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3, .width = 1, .height = 1 }); + + t.eraseDisplay(.complete, false); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expect(s.placements.contains(history_key)); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expect(s.images.contains(1)); + try testing.expect(!s.images.contains(2)); + try testing.expect(!s.images.contains(3)); +} + +test "storage: cell offsets stay within explicit destination rectangle" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 5, .rows = 5 }); + defer t.deinit(alloc); + t.width_px = 50; // 10 px per col + t.height_px = 100; // 20 px per row + + // Explicit columns and rows describe the far cell boundaries. Offsets + // move the near edge inward without moving those far edges. + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .x_offset = 3, + .y_offset = 4, + .columns = 2, + .rows = 1, + }; + const actual = placement.pixelSize(.{ .width = 4, .height = 3 }, &t); + try testing.expectEqual(@as(u32, 17), actual.width); + try testing.expectEqual(@as(u32, 16), actual.height); + try testing.expectEqual(@as(u32, 2), placement.gridSize(.{ .width = 4, .height = 3 }, &t).cols); + try testing.expectEqual(@as(u32, 1), placement.gridSize(.{ .width = 4, .height = 3 }, &t).rows); +} + +test "storage: cell offsets clamp to cell bounds" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 5, .rows = 5 }); + defer t.deinit(alloc); + t.width_px = 50; // 10 px per col + t.height_px = 100; // 20 px per row + + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .x_offset = std.math.maxInt(u32), + .y_offset = std.math.maxInt(u32), + .columns = 1, + .rows = 1, + }; + const offset = placement.cellOffset(&t); + try testing.expectEqual(@as(u32, 9), offset.x); + try testing.expectEqual(@as(u32, 19), offset.y); + + // Even hostile offsets leave one pixel inside the requested cell. + const actual = placement.pixelSize(.{ .width = 1, .height = 1 }, &t); + try testing.expectEqual(@as(u32, 1), actual.width); + try testing.expectEqual(@as(u32, 1), actual.height); } test "storage: aspect ratio calculation when only columns or rows specified" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 100, .rows = 100 }); defer t.deinit(alloc); t.width_px = 1000; // 10 px per col t.height_px = 2000; // 20 px per row @@ -1453,10 +3172,162 @@ test "storage: aspect ratio calculation when only columns or rows specified" { } } +test "storage: default source rectangle is intersected before sizing" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 5, .rows = 5 }); + defer t.deinit(alloc); + + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .source_x = 3, + .source_y = 1, + }; + const actual = placement.pixelSize(.{ .width = 4, .height = 3 }, &t); + try testing.expectEqual(@as(u32, 1), actual.width); + try testing.expectEqual(@as(u32, 2), actual.height); +} + +test "storage: explicit source rectangle is intersected before sizing" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + // The requested 8x8 rectangle intersects this 10x10 image as 2x3. + // With a two-column destination, the clipped 2:3 aspect ratio produces + // a 20x30 pixel destination. + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .source_x = 8, + .source_y = 7, + .source_width = 8, + .source_height = 8, + .columns = 2, + }; + const actual = placement.pixelSize(.{ .width = 10, .height = 10 }, &t); + try testing.expectEqual(@as(u32, 20), actual.width); + try testing.expectEqual(@as(u32, 30), actual.height); +} + +test "storage: placement geometry handles untrusted dimensions" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + const max = std.math.maxInt(u32); + + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 2, .rows = 2 }); + defer t.deinit(alloc); + t.width_px = max; + t.height_px = max; + + // Cell dimensions multiplied by protocol-controlled row and column + // counts saturate instead of panicking or wrapping. + { + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .columns = 3, + .rows = 3, + }; + const actual = placement.pixelSize(.{ .width = 1, .height = 1 }, &t); + try testing.expectEqual(max, actual.width); + try testing.expectEqual(max, actual.height); + } + + // Aspect-ratio scaling also saturates when the derived dimension does + // not fit in the public u32 geometry type. + { + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .columns = 3, + .source_height = max, + }; + const actual = placement.pixelSize(.{ .width = 1, .height = 1 }, &t); + try testing.expectEqual(max, actual.width); + try testing.expectEqual(max, actual.height); + } + { + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .rows = 3, + .source_width = max, + }; + const actual = placement.pixelSize(.{ .width = 1, .height = 1 }, &t); + try testing.expectEqual(max, actual.width); + try testing.expectEqual(max, actual.height); + } + + // Pixel offsets are protocol-controlled too. Clamp them to the cell + // before including them in grid geometry. + t.width_px = 2; + t.height_px = 2; + { + const placement: ImageStorage.Placement = .{ + .location = .{ .virtual = {} }, + .x_offset = max, + .y_offset = max, + }; + const actual = placement.gridSize(.{ .width = 1, .height = 1 }, &t); + try testing.expectEqual(@as(u32, 1), actual.cols); + try testing.expectEqual(@as(u32, 1), actual.rows); + } + + const pin = try trackPin(&t, .{ .x = 0, .y = 0 }); + defer t.screens.active.pages.untrackPin(pin); + + // Explicit maximum dimensions must clamp the rectangle to the terminal + // without overflowing its horizontal extent. + { + const placement: ImageStorage.Placement = .{ + .location = .{ .pin = pin }, + .columns = max, + .rows = 1, + }; + const rect = placement.rect(.{ .width = 1, .height = 1 }, &t).?; + try testing.expectEqual(@as(size.CellCountInt, 1), rect.bottom_right.x); + } + + // A garbage pin represents content that has been pruned from retained + // history. Its fallback location must not make the placement visible. + pin.garbage = true; + { + const placement: ImageStorage.Placement = .{ + .location = .{ .pin = pin }, + .columns = 1, + .rows = 1, + }; + try testing.expect(placement.rect(.{ .width = 1, .height = 1 }, &t) == null); + } + pin.garbage = false; + + // Terminals can temporarily have no pixel geometry. A placement whose + // computed grid is empty has no rectangle, so rect must not subtract one + // from a zero row count. + t.width_px = 0; + t.height_px = 0; + { + const placement: ImageStorage.Placement = .{ + .location = .{ .pin = pin }, + .columns = 1, + }; + const actual = placement.gridSize(.{ .width = 1, .height = 1 }, &t); + try testing.expectEqual(@as(u32, 0), actual.cols); + try testing.expectEqual(@as(u32, 0), actual.rows); + try testing.expect(placement.rect(.{ .width = 1, .height = 1 }, &t) == null); + } +} + test "storage: generation stamps on image add and replace" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); var s: ImageStorage = .{}; @@ -1465,7 +3336,7 @@ test "storage: generation stamps on image add and replace" { // Fresh storage has generation zero (never mutated). try testing.expectEqual(@as(u64, 0), s.generation); - try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 1, .height = 1 }); const gen1 = s.generation; try testing.expect(gen1 > 0); @@ -1473,7 +3344,7 @@ test "storage: generation stamps on image add and replace" { try testing.expectEqual(gen1, img1.generation); // A second image gets a strictly greater stamp. - try s.addImage(alloc, .{ .id = 2, .width = 1, .height = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .width = 1, .height = 1 }); const gen2 = s.generation; try testing.expect(gen2 > gen1); try testing.expectEqual(gen2, s.imageById(2).?.generation); @@ -1481,7 +3352,7 @@ test "storage: generation stamps on image add and replace" { // Retransmitting the same image ID (identical dimensions) gets a // fresh stamp: this is what makes same-sized retransmissions // detectable by renderers. - try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .width = 1, .height = 1 }); const gen3 = s.generation; try testing.expect(gen3 > gen2); try testing.expectEqual(gen3, s.imageById(1).?.generation); @@ -1492,16 +3363,17 @@ test "storage: generation stamps on image add and replace" { test "storage: generation bumps on placement and delete" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); - try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); const gen_add = s.generation; - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); const gen_place = s.generation; try testing.expect(gen_place > gen_add); @@ -1510,26 +3382,32 @@ test "storage: generation bumps on placement and delete" { _ = s.imageByNumber(1); try testing.expectEqual(gen_place, s.generation); - s.delete(alloc, &t, .{ .all = true }); + s.delete(io, alloc, &t, .{ .all = true }); try testing.expect(s.generation > gen_place); } test "storage: generation bumps when setLimit evicts or disables" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); const data = try alloc.dupe(u8, "1234"); - try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1, .data = data }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 1, + .data = .{ .complete = data }, + }); const gen_add = s.generation; // Lowering the limit evicts the image and must mark a mutation. s.dirty = false; - try s.setLimit(alloc, t.screens.active, 1); + s.setLimit(io, alloc, t.screens.active, 1); try testing.expect(s.dirty); try testing.expect(s.generation > gen_add); try testing.expectEqual(@as(usize, 0), s.images.count()); @@ -1537,15 +3415,16 @@ test "storage: generation bumps when setLimit evicts or disables" { // Disabling (limit=0) resets the storage and must mark a mutation. s.dirty = false; - try s.setLimit(alloc, t.screens.active, 0); + s.setLimit(io, alloc, t.screens.active, 0); try testing.expect(s.dirty); try testing.expect(s.generation > gen_evict); } test "storage: imageByNumber returns most recently transmitted" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); var s: ImageStorage = .{}; @@ -1553,27 +3432,28 @@ test "storage: imageByNumber returns most recently transmitted" { // Two images sharing a number: the newest transmission wins, // regardless of insertion order or clock resolution. - try s.addImage(alloc, .{ .id = 1, .number = 7 }); - try s.addImage(alloc, .{ .id = 2, .number = 7 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .number = 7 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2, .number = 7 }); try testing.expectEqual(@as(u32, 2), s.imageByNumber(7).?.id); // Retransmit the first: it becomes the newest. - try s.addImage(alloc, .{ .id = 1, .number = 7 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1, .number = 7 }); try testing.expectEqual(@as(u32, 1), s.imageByNumber(7).?.id); } test "storage: nextGeneration is unique and monotonic" { const testing = std.testing; - const a = nextGeneration(); - const b = nextGeneration(); + const a = nextGeneration(testing.io); + const b = nextGeneration(testing.io); try testing.expect(b > a); try testing.expect(a > 0); } test "storage: no-op delete does not mark a mutation" { const testing = std.testing; + const io = testing.io; const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); defer t.deinit(alloc); var s: ImageStorage = .{}; @@ -1581,21 +3461,1204 @@ test "storage: no-op delete does not mark a mutation" { // A delete-all on an empty storage (this runs on every screen // clear) must not dirty the state or bump the generation. - s.delete(alloc, &t, .{ .all = true }); + s.delete(io, alloc, &t, .{ .all = true }); try testing.expect(!s.dirty); try testing.expectEqual(@as(u64, 0), s.generation); // Same for a delete that matches nothing. - try s.addImage(alloc, .{ .id = 1 }); - try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); const gen = s.generation; s.dirty = false; - s.delete(alloc, &t, .{ .id = .{ .image_id = 42 } }); + s.delete(io, alloc, &t, .{ .id = .{ .image_id = 42 } }); try testing.expect(!s.dirty); try testing.expectEqual(gen, s.generation); // But a delete that removes something does mark a mutation. - s.delete(alloc, &t, .{ .id = .{ .image_id = 1 } }); + s.delete(io, alloc, &t, .{ .id = .{ .image_id = 1 } }); try testing.expect(s.dirty); try testing.expect(s.generation > gen); } + +test "storage: evicts images in priority order" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{ .total_limit = 192 }; + defer s.deinit(alloc, t.screens.active); + + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + .metadata = .{ .transient = false }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 2, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + .metadata = .{ .transient = true }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 3, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + .metadata = .{ .transient = true }, + }); + try s.addPlacement( + io, + alloc, + t.screens.active, + 2, + 1, + .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }, + ); + + const gen = s.generation; + const result = s.evictImage(io, alloc, t.screens.active, 96); + try testing.expect(s.dirty); + try testing.expect(s.generation > gen); + try testing.expectEqual(true, result); + try testing.expectEqual(1, s.images.count()); + try testing.expect(!s.images.contains(1)); + try testing.expect(s.images.contains(2)); + try testing.expect(!s.images.contains(3)); +} + +test "storage: eviction releases placement pins" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{ .total_limit = 128 }; + defer s.deinit(alloc, t.screens.active); + + const tracked = t.screens.active.pages.countTrackedPins(); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 2, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + try testing.expectEqual(tracked + 2, t.screens.active.pages.countTrackedPins()); + + // Adding a third image evicts the oldest equally-ranked image and its + // placement. The newer image's placement and tracked pin remain intact. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 3, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + }); + try testing.expect(!s.images.contains(1)); + try testing.expect(s.images.contains(2)); + try testing.expect(s.images.contains(3)); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expect(s.placements.contains(.{ + .image_id = 2, + .placement_id = .{ .tag = .external, .id = 1 }, + })); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); +} + +test "storage: pending image completes once and preserves age" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{ .total_limit = 16 }; + defer s.deinit(alloc, t.screens.active); + + const pending = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 1, + .number = 7, + .width = 2, + .height = 2, + .format = .rgba, + .data = .{ .pending = 16 }, + }); + try testing.expectEqual(@as(usize, 16), s.total_bytes); + try testing.expectEqual(@as(u32, 1), s.imageByNumber(7).?.id); + try testing.expect(s.imageById(1).?.data.isPending()); + + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + + const wrong = try alloc.dupe(u8, "short"); + const wrong_completed = pending.complete(&s, io, wrong); + try testing.expect(!wrong_completed); + defer alloc.free(wrong); + + const storage_generation = s.generation; + s.dirty = false; + const pixels = try alloc.dupe(u8, "*" ** 16); + try testing.expect(pending.complete(&s, io, pixels)); + try testing.expect(s.dirty); + try testing.expect(s.generation > storage_generation); + try testing.expectEqual(pending.generation, s.imageById(1).?.generation); + try testing.expectEqual(@as(usize, 16), s.total_bytes); + try testing.expectEqualSlices(u8, pixels, s.imageById(1).?.data.bytes().?); + + const duplicate = try alloc.dupe(u8, "!" ** 16); + const duplicate_completed = pending.complete(&s, io, duplicate); + try testing.expect(!duplicate_completed); + defer alloc.free(duplicate); +} + +test "storage: stale pending completion loses to delete replacement and eviction" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{ .total_limit = 8 }; + defer s.deinit(alloc, t.screens.active); + + const deleted = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 1, + .data = .{ .pending = 4 }, + }); + s.delete(io, alloc, &t, .{ .id = .{ .delete = true, .image_id = 1 } }); + const deleted_data = try alloc.dupe(u8, "gone"); + const deleted_completed = deleted.complete(&s, io, deleted_data); + try testing.expect(!deleted_completed); + defer alloc.free(deleted_data); + + const replaced = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 2, + .data = .{ .pending = 4 }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 2, + .data = .{ .complete = try alloc.dupe(u8, "live") }, + }); + const replaced_data = try alloc.dupe(u8, "late"); + const replaced_completed = replaced.complete(&s, io, replaced_data); + try testing.expect(!replaced_completed); + defer alloc.free(replaced_data); + try testing.expectEqualStrings("live", s.imageById(2).?.data.bytes().?); + + const evicted = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 3, + .data = .{ .pending = 4 }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 4, + .data = .{ .complete = try alloc.dupe(u8, "12345678") }, + }); + try testing.expect(s.imageById(3) == null); + const evicted_data = try alloc.dupe(u8, "late"); + const evicted_completed = evicted.complete(&s, io, evicted_data); + try testing.expect(!evicted_completed); + defer alloc.free(evicted_data); +} + +test "storage: replacement reuses pending reservation and removes placements" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{ .total_limit = 12 }; + defer s.deinit(alloc, t.screens.active); + const tracked = t.screens.active.pages.countTrackedPins(); + + const pending = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 2, + .height = 1, + .format = .rgba, + .data = .{ .pending = 8 }, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 2, + .data = .{ .complete = try alloc.dupe(u8, "keep") }, + }); + + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 2, + .height = 1, + .format = .rgba, + .data = .{ .complete = try alloc.dupe(u8, "12345678") }, + }); + try testing.expect(s.images.contains(1)); + try testing.expect(s.images.contains(2)); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); + try testing.expectEqual( + @as(u30, 0), + s.imageById(1).?.metadata.placement_count, + ); + try testing.expectEqual(@as(usize, 12), s.total_bytes); + + const stale = try alloc.dupe(u8, "snapshot"); + const stale_completed = pending.complete(&s, io, stale); + try testing.expect(!stale_completed); + defer alloc.free(stale); + + // Growing the replacement requires eviction, but the replacement ID is + // excluded. The other image supplies the needed bytes. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .data = .{ .complete = try alloc.dupe(u8, "1234567890") }, + }); + try testing.expect(s.images.contains(1)); + try testing.expect(!s.images.contains(2)); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(@as(usize, 10), s.total_bytes); + + s.delete(io, alloc, &t, .{ .id = .{ .delete = true, .image_id = 1 } }); + try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); +} + +test "storage: pending images share exact eviction ordering" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{ .total_limit = 192 }; + defer s.deinit(alloc, t.screens.active); + + _ = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 1, + .data = .{ .pending = 64 }, + .metadata = .{ .transient = false }, + }); + _ = try s.addPendingImage(io, alloc, t.screens.active, .{ + .id = 2, + .data = .{ .pending = 64 }, + .metadata = .{ .transient = true }, + }); + try s.addImage(io, alloc, t.screens.active, .{ + .id = 3, + .data = .{ .complete = try alloc.dupe(u8, "*" ** 64) }, + .metadata = .{ .transient = true }, + }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + + // ID 3 is transient and unused, so one exact-size eviction is enough. + try testing.expect(s.evictImage(io, alloc, t.screens.active, 64)); + try testing.expect(s.images.contains(1)); + try testing.expect(s.images.contains(2)); + try testing.expect(!s.images.contains(3)); + try testing.expectEqual(@as(usize, 128), s.total_bytes); +} + +test "storage: nextImageId number matches Kitty get_free_client_id" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // Empty storage returns 1, as does Kitty. + try testing.expectEqual(@as(u32, 1), s.nextImageId(.explicit)); + + // Contiguous IDs from 1: the next ID after them. + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 3 }); + try testing.expectEqual(@as(u32, 4), s.nextImageId(.explicit)); + + // The first gap is filled, even when higher IDs exist. + try s.addImage(io, alloc, t.screens.active, .{ .id = 100 }); + s.delete(io, alloc, &t, .{ .id = .{ .image_id = 2, .delete = true } }); + try testing.expectEqual(@as(u32, 2), s.nextImageId(.explicit)); + + // 1 is reused as soon as it is free. + s.delete(io, alloc, &t, .{ .id = .{ .image_id = 1, .delete = true } }); + try testing.expectEqual(@as(u32, 1), s.nextImageId(.explicit)); +} + +test "storage: nextImageId implicit skips in-use ids and zero" { + const testing = std.testing; + const io = testing.io; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // A client image already sits on the counter's first two values. + try s.addImage(io, alloc, t.screens.active, .{ .id = 2147483647 }); + try s.addImage(io, alloc, t.screens.active, .{ .id = 2147483648 }); + try testing.expectEqual(@as(u32, 2147483649), s.nextImageId(.implicit)); + try testing.expectEqual(@as(u32, 2147483650), s.nextImageId(.implicit)); + + // Wrapping skips zero, which means "no ID" protocol-wide. + s.next_image_id = std.math.maxInt(u32); + try testing.expectEqual(std.math.maxInt(u32), s.nextImageId(.implicit)); + try testing.expectEqual(@as(u32, 1), s.nextImageId(.implicit)); +} + +test "storage: scroll margins placement inside region scrolls and clips at top" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // 2-row image (10x10px cells) inside the region (rows 1-4). + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 20, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 2 }) }, + }); + t.setTopAndBottomMargin(2, 5); + t.setCursorPos(5, 1); + + // Entirely inside: moves up with the content. + try t.index(); + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 1 }, pt.coord()); + } + + // Would extend above the top margin: anchored at the top margin + // with the top cell row clipped off the source. + try t.index(); + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 1 }, pt.coord()); + try testing.expectEqual(@as(u32, 10), p.source_y); + try testing.expectEqual(@as(u32, 10), p.source_height); + } + + // Fully clipped: deleted. + try t.index(); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); + // The image itself is retained. + try testing.expectEqual(@as(usize, 1), storage.images.count()); +} + +test "storage: scroll margins placement straddling region does not move" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // 3-row image anchored at the top of a 2-row region: not entirely + // within the region, so region scrolls must not move it. This + // exercises the scrollback-creating path (region top at row 0). + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 30, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + t.setTopAndBottomMargin(1, 2); + t.setCursorPos(2, 1); + + try t.index(); + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 0 }, pt.coord()); + try testing.expectEqual(@as(u32, 0), p.source_y); + try testing.expectEqual(@as(u32, 0), p.source_height); +} + +test "storage: scroll margins placement below region does not move" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // A "status bar" image below the bottom margin must stay put while + // the region above it scrolls (scrollback-creating path). + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 10, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 5 }) }, + }); + t.setTopAndBottomMargin(1, 4); + t.setCursorPos(4, 1); + + try t.index(); + try t.index(); + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 5 }, pt.coord()); +} + +test "storage: scroll margins reverse index clips at bottom" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // 2-row image at the bottom of the region (rows 1-4). + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 20, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 3 }) }, + }); + t.setTopAndBottomMargin(2, 5); + t.setCursorPos(2, 1); + + // Moves down, with the bottom cell row clipped off the source. + t.reverseIndex(); + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 4 }, pt.coord()); + try testing.expectEqual(@as(u32, 0), p.source_y); + try testing.expectEqual(@as(u32, 10), p.source_height); + } + + // Fully clipped: deleted. + t.reverseIndex(); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); +} + +test "storage: scroll margins scaled placement clips proportionally" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // A 40px-tall image scaled into 2 rows, inside a 2-row region. + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 40, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 1 }) }, + .columns = 1, + .rows = 2, + }); + t.setTopAndBottomMargin(2, 3); + t.setCursorPos(3, 1); + + try t.index(); + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 1 }, pt.coord()); + try testing.expectEqual(@as(u32, 20), p.source_y); + try testing.expectEqual(@as(u32, 20), p.source_height); + try testing.expectEqual(@as(u32, 1), p.rows); + try testing.expectEqual(@as(u32, 1), p.columns); +} + +test "storage: scroll margins left/right margins respect columns" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // One placement outside the left/right margin columns, one inside. + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 10, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 2 }) }, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 2, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 2, .y = 2 }) }, + }); + + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 8); + + try t.scrollUp(1); + + // Outside the margin columns: stays. + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 2 }, pt.coord()); + } + + // Inside: moves up. + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 2, .y = 1 }, pt.coord()); + } +} + +test "storage: scroll margins insert/delete lines do not move placements" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // Kitty does not scroll images for IL/DL, only for IND/RI/SU/SD. + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 10, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 2 }) }, + }); + t.setTopAndBottomMargin(2, 5); + t.setCursorPos(2, 1); + + t.deleteLines(1); + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 2 }, pt.coord()); + } + + t.insertLines(1); + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 2 }, pt.coord()); + } +} + +test "storage: scroll without margins moves placement into scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // No margins: the placement follows its anchored row into the + // scrollback via pin tracking (kitty's marginless behavior). + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 20, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + t.setCursorPos(6, 1); + + try t.index(); + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + try testing.expect(t.screens.active.pages.pointFromPin( + .active, + p.location.pin.*, + ) == null); + const pt = t.screens.active.pages.pointFromPin(.screen, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 0 }, pt.coord()); +} + +test "storage: scroll margins large scroll deletes inside placement" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 10, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 2 }) }, + }); + t.setTopAndBottomMargin(2, 5); + + try t.scrollUp(10); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); +} + +test "storage: scroll margins straddling placement pin inside region restored" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // 2-row image anchored on the bottom margin row, extending below + // the region: not entirely inside, so it must not move even though + // the region scroll moves every tracked pin within the region rows. + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 20, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 4 }) }, + }); + t.setTopAndBottomMargin(2, 5); + t.setCursorPos(5, 1); + + try t.index(); + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 4 }, pt.coord()); + try testing.expectEqual(@as(u32, 0), p.source_y); + try testing.expectEqual(@as(u32, 0), p.source_height); +} + +test "storage: scroll margins multi-line scroll up with scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 6 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 60; + + // 1-row image inside a region whose top is the screen top, so the + // scroll pushes text into the scrollback (window shift) while the + // image moves within the region. + const storage: *ImageStorage = &t.screens.active.kitty_images; + try storage.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 10, + .height = 10, + }); + try storage.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 2 }) }, + }); + t.setTopAndBottomMargin(1, 4); + + try t.scrollUp(2); + { + const p = storage.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }).?; + const pt = t.screens.active.pages.pointFromPin(.active, p.location.pin.*).?; + try testing.expectEqual(point.Coordinate{ .x = 0, .y = 0 }, pt.coord()); + } + + // Another two rows scrolls it out of the region: deleted. + try t.scrollUp(2); + try testing.expectEqual(@as(usize, 0), storage.placements.count()); +} + +test "storage: resolveChain accumulates offsets to the pin root" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ + .location = .{ .relative = .{ + .parent = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }, + .horizontal_offset = 2, + .vertical_offset = 1, + } }, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 3, .{ + .location = .{ .relative = .{ + .parent = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }, + .horizontal_offset = -1, + .vertical_offset = 4, + } }, + }); + + const grandchild = s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 3 }, + }).?; + const chain = s.resolveChain(grandchild.location.relative).?; + try testing.expect(chain.root_key.eql(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + })); + try testing.expect(chain.root.location == .pin); + try testing.expectEqual(@as(i32, 1), chain.horizontal_offset); + try testing.expectEqual(@as(i32, 5), chain.vertical_offset); +} + +test "storage: resolveChain finds virtual roots" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .virtual = {} }, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 2, .{ + .location = .{ .relative = .{ + .parent = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }, + .horizontal_offset = 1, + } }, + }); + + const child = s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }).?; + const chain = s.resolveChain(child.location.relative).?; + try testing.expect(chain.root.location == .virtual); + try testing.expect(chain.root_key.eql(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + })); + try testing.expectEqual(@as(i32, 1), chain.horizontal_offset); + try testing.expectEqual(@as(i32, 0), chain.vertical_offset); +} + +test "storage: eviction removes orphaned relative placements" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + s.total_limit = 8; + + // Image 1 holds most of the byte budget and has a pin placement. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 2, + .height = 1, + .data = .{ .complete = try alloc.dupe(u8, &.{ 0, 0, 0, 0, 0, 0 }) }, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 1, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) }, + }); + + // Image 2's placement is relative to image 1's placement. + try s.addImage(io, alloc, t.screens.active, .{ .id = 2 }); + try s.addPlacement(io, alloc, t.screens.active, 2, 1, .{ + .location = .{ .relative = .{ .parent = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + } } }, + }); + + // Adding image 3 exceeds the limit and evicts image 1 (oldest), + // removing its placement, which orphans image 2's placement. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 3, + .width = 2, + .height = 1, + .data = .{ .complete = try alloc.dupe(u8, &.{ 0, 0, 0, 0, 0, 0 }) }, + }); + + try testing.expect(s.imageById(1) == null); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expect(s.imageById(2) != null); +} + +test "storage: placeholderTarget lookup" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(io, alloc, t.screens.active, .{ .id = 1 }); + try s.addPlacement(io, alloc, t.screens.active, 1, 5, .{ + .location = .{ .virtual = {} }, + }); + + // Exact external ID match. + { + const target = s.placeholderTarget(1, 5).?; + const expected: ImageStorage.PlacementKey = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 5 }, + }; + try testing.expectEqual(expected, target.key); + try testing.expect(target.placement.location == .virtual); + } + + // Zero placement ID falls back to the image's virtual placement. + { + const target = s.placeholderTarget(1, 0).?; + const expected: ImageStorage.PlacementKey = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 5 }, + }; + try testing.expectEqual(expected, target.key); + } + + try testing.expect(s.placeholderTarget(1, 9) == null); + try testing.expect(s.placeholderTarget(2, 0) == null); + + // With multiple virtual placements, the zero-ID fallback picks + // deterministically by PlacementId.preferredOver: lowest external. + try s.addPlacement(io, alloc, t.screens.active, 1, 3, .{ + .location = .{ .virtual = {} }, + }); + { + const expected: ImageStorage.PlacementKey = .{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 3 }, + }; + try testing.expectEqual(expected, s.placeholderTarget(1, 0).?.key); + } +} + +test "storage: animation tick advances and schedules" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // A running 1x1 RGBA image whose animation has one extra frame. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 1, + .format = .rgba, + .data = .{ .complete = try alloc.dupe(u8, &.{ 255, 0, 0, 255 }) }, + }); + const img = s.images.getPtr(1).?; + const anim = try alloc.create(animation.Animation); + anim.* = .{ .state = .running }; + img.animation = anim; + try anim.frames.append(alloc, .{ + .data = try alloc.dupe(u8, &.{ 0, 0, 255, 255 }), + .gap_ms = 40, + }); + + // Without a placement the animation doesn't advance (our + // approximation of Kitty's visibility gate). + try testing.expect(s.animationTick(io, 0) == null); + try testing.expectEqual(@as(u32, 0), anim.current_index); + + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + const gen1 = img.generation; + s.dirty = false; + + // First tick: the gapless root frame is due immediately and is + // skipped over to frame 2, which is due again in its 40ms gap. + try testing.expectEqual(@as(?u64, 40), s.animationTick(io, 0)); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expect(img.generation > gen1); + try testing.expect(s.dirty); + + // Nothing due yet: no advance, and the delay counts down. + const gen2 = img.generation; + try testing.expectEqual(@as(?u64, 30), s.animationTick(io, 10)); + try testing.expectEqual(gen2, img.generation); + + // Wrapping is fine with an infinite loop budget: the gapless + // root is skipped and frame 2 is shown again. + try testing.expectEqual(@as(?u64, 40), s.animationTick(io, 40)); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expectEqual(@as(u32, 1), anim.current_loop); +} + +test "storage: animation tick loading state parks on last frame" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // A placed 1x1 RGBA image in the loading state (a=a s=2) whose + // animation has one extra frame. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 1, + .format = .rgba, + .data = .{ .complete = try alloc.dupe(u8, &.{ 255, 0, 0, 255 }) }, + }); + const anim = try alloc.create(animation.Animation); + anim.* = .{ .state = .loading }; + s.images.getPtr(1).?.animation = anim; + try anim.frames.append(alloc, .{ + .data = try alloc.dupe(u8, &.{ 0, 0, 255, 255 }), + .gap_ms = 40, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + + // Reach the last frame, then park: no wakeup is scheduled while + // waiting for more frames and the loop counter stays untouched. + try testing.expectEqual(@as(?u64, 40), s.animationTick(io, 0)); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expect(s.animationTick(io, 100) == null); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expectEqual(@as(u32, 0), anim.current_loop); + + // A new frame arriving un-parks playback. + try anim.frames.append(alloc, .{ + .data = try alloc.dupe(u8, &.{ 0, 255, 0, 255 }), + .gap_ms = 25, + }); + try testing.expectEqual(@as(?u64, 25), s.animationTick(io, 150)); + try testing.expectEqual(@as(u32, 2), anim.current_index); +} + +test "storage: animation tick exhausts loop budget" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // A placed, running 1x1 RGBA image with a gapped root frame, one + // extra frame, and a one-loop budget (a=a v=2). + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 1, + .format = .rgba, + .data = .{ .complete = try alloc.dupe(u8, &.{ 255, 0, 0, 255 }) }, + }); + const anim = try alloc.create(animation.Animation); + anim.* = .{ + .state = .running, + .root_gap_ms = 10, + .max_loops = 1, + }; + s.images.getPtr(1).?.animation = anim; + try anim.frames.append(alloc, .{ + .data = try alloc.dupe(u8, &.{ 0, 0, 255, 255 }), + .gap_ms = 40, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + + // Root shows for 10ms, frame 2 for 40ms, then the wrap exhausts + // the budget and playback freezes on the last frame for good. + try testing.expectEqual(@as(?u64, 10), s.animationTick(io, 0)); + try testing.expectEqual(@as(u32, 0), anim.current_index); + try testing.expectEqual(@as(?u64, 40), s.animationTick(io, 10)); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expect(s.animationTick(io, 50) == null); + try testing.expectEqual(@as(u32, 1), anim.current_index); + try testing.expect(s.animationTick(io, 500) == null); +} + +test "storage: animation tick ignores ineligible animations" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // A placed 1x1 RGBA image with one extra frame, in the default + // stopped state. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 1, + .format = .rgba, + .data = .{ .complete = try alloc.dupe(u8, &.{ 255, 0, 0, 255 }) }, + }); + const anim = try alloc.create(animation.Animation); + anim.* = .{}; + s.images.getPtr(1).?.animation = anim; + try anim.frames.append(alloc, .{ + .data = try alloc.dupe(u8, &.{ 0, 0, 255, 255 }), + .gap_ms = 40, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + + // Stopped (the default) never advances. + try testing.expect(s.animationTick(io, 0) == null); + + // An all-gapless animation can never advance either. + anim.state = .running; + anim.frames.items[0].gap_ms = 0; + try testing.expect(s.animationTick(io, 0) == null); + try testing.expectEqual(@as(u32, 0), anim.current_index); +} + +test "storage: animation tick re-anchors a restarted clock" { + const testing = std.testing; + const alloc = testing.allocator; + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + // A placed, running 1x1 RGBA image displaying its extra frame, + // with a shown-at timestamp far ahead of the tick clock. + try s.addImage(io, alloc, t.screens.active, .{ + .id = 1, + .width = 1, + .height = 1, + .format = .rgba, + .data = .{ .complete = try alloc.dupe(u8, &.{ 255, 0, 0, 255 }) }, + }); + const anim = try alloc.create(animation.Animation); + anim.* = .{ + .state = .running, + .current_index = 1, + .frame_shown_at_ms = 1000, + }; + s.images.getPtr(1).?.animation = anim; + try anim.frames.append(alloc, .{ + .data = try alloc.dupe(u8, &.{ 0, 0, 255, 255 }), + .gap_ms = 40, + }); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ + .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) }, + }); + + // A timestamp in the future relative to now means the caller's + // clock restarted; the animation must not stall until the old + // timestamp comes around again. + try testing.expectEqual(@as(?u64, 40), s.animationTick(io, 5)); + try testing.expectEqual(@as(?u64, 5), anim.frame_shown_at_ms); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig index a223797b..b62f8177 100644 --- a/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig @@ -363,29 +363,17 @@ pub const Placement = struct { image: *const Image, cell_width: u32, cell_height: u32, - ) !struct { + ) Error!struct { rows: u32, columns: u32, } { // Get the placement. If an ID is specified we look for the exact one. // If no ID, then we find the first virtual placement for this image. - const placement = if (self.placement_id > 0) storage.placements.get(.{ - .image_id = self.image_id, - .placement_id = .{ .tag = .external, .id = self.placement_id }, - }) orelse { - return Error.PlacementMissingPlacement; - } else placement: { - var it = storage.placements.iterator(); - while (it.next()) |entry| { - if (entry.key_ptr.image_id == self.image_id and - entry.value_ptr.location == .virtual) - { - break :placement entry.value_ptr.*; - } - } - - return Error.PlacementMissingPlacement; - }; + const target = storage.placeholderTarget( + self.image_id, + self.placement_id, + ) orelse return Error.PlacementMissingPlacement; + const placement = target.placement; // Use requested rows/columns if specified // For unspecified rows/columns, calculate based on the image size. @@ -885,7 +873,8 @@ test "unicode diacritic" { test "unicode placement: none" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -900,7 +889,8 @@ test "unicode placement: none" { test "unicode placement: single row/col" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -924,7 +914,8 @@ test "unicode placement: single row/col" { test "unicode placement: continuation break" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 10 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -958,7 +949,8 @@ test "unicode placement: continuation break" { test "unicode placement: continuation with diacritics set" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 10 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -985,7 +977,8 @@ test "unicode placement: continuation with diacritics set" { test "unicode placement: continuation with no col" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 10 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1012,7 +1005,8 @@ test "unicode placement: continuation with no col" { test "unicode placement: continuation with no diacritics" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 10 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1039,7 +1033,8 @@ test "unicode placement: continuation with no diacritics" { test "unicode placement: run ending" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 10 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1066,7 +1061,8 @@ test "unicode placement: run ending" { test "unicode placement: run starting in the middle" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 10 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1093,7 +1089,8 @@ test "unicode placement: run starting in the middle" { test "unicode placement: specifying image id as palette" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1118,7 +1115,8 @@ test "unicode placement: specifying image id as palette" { test "unicode placement: specifying image id with high bits" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1143,7 +1141,8 @@ test "unicode placement: specifying image id with high bits" { test "unicode placement: specifying placement id as palette" { const alloc = testing.allocator; - var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + const io = testing.io; + var t = try terminal.Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 }); defer t.deinit(alloc); t.modes.set(.grapheme_cluster, true); @@ -1174,17 +1173,18 @@ test "unicode placement: specifying placement id as palette" { // printf "\033_Ga=p,i=1,U=1,q=2,c=4,r=2\033\\" test "unicode render placement: dog 4x2" { const alloc = testing.allocator; + const io = testing.io; const cell_width = 36; const cell_height = 80; - var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 100, .rows = 100 }); defer t.deinit(alloc); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); const image: Image = .{ .id = 1, .width = 500, .height = 306 }; - try s.addImage(alloc, image); - try s.addPlacement(alloc, 1, 0, .{ + try s.addImage(io, alloc, t.screens.active, image); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ .location = .{ .virtual = {} }, .columns = 4, .rows = 2, @@ -1241,17 +1241,18 @@ test "unicode render placement: dog 4x2" { // printf "\033_Ga=p,i=1,U=1,q=2,c=2,r=2\033\\" test "unicode render placement: dog 2x2 with blank cells" { const alloc = testing.allocator; + const io = testing.io; const cell_width = 36; const cell_height = 80; - var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 100, .rows = 100 }); defer t.deinit(alloc); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); const image: Image = .{ .id = 1, .width = 500, .height = 306 }; - try s.addImage(alloc, image); - try s.addPlacement(alloc, 1, 0, .{ + try s.addImage(io, alloc, t.screens.active, image); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ .location = .{ .virtual = {} }, .columns = 2, .rows = 2, @@ -1307,17 +1308,18 @@ test "unicode render placement: dog 2x2 with blank cells" { // printf "\033_Ga=p,i=1,U=1,q=2,c=1,r=1\033\\" test "unicode render placement: dog 1x1" { const alloc = testing.allocator; + const io = testing.io; const cell_width = 36; const cell_height = 80; - var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + var t = try terminal.Terminal.init(io, alloc, .{ .cols = 100, .rows = 100 }); defer t.deinit(alloc); var s: ImageStorage = .{}; defer s.deinit(alloc, t.screens.active); const image: Image = .{ .id = 1, .width = 500, .height = 306 }; - try s.addImage(alloc, image); - try s.addPlacement(alloc, 1, 0, .{ + try s.addImage(io, alloc, t.screens.active, image); + try s.addPlacement(io, alloc, t.screens.active, 1, 0, .{ .location = .{ .virtual = {} }, .columns = 1, .rows = 1, diff --git a/vendor/libghostty-vt/src/terminal/kitty/windows.zig b/vendor/libghostty-vt/src/terminal/kitty/windows.zig new file mode 100644 index 00000000..41d2b62d --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/windows.zig @@ -0,0 +1,277 @@ +//! Windows path checks for the Kitty graphics protocol file and +//! temporary file mediums. +//! +//! On POSIX the file transmission blocklist is a few prefixes +//! (`/proc`, `/sys`, `/dev`) applied to the canonical path of the +//! opened file. Windows needs more care because some paths are +//! dangerous to even open: a UNC path makes this process resolve and +//! authenticate to the named SMB server, and the Win32 device and NT +//! object namespaces reach raw volumes and named pipes, where the +//! open or the read can block. +//! +//! Everything here is pure string logic, so it is tested on every host. + +const std = @import("std"); + +pub const Error = error{ + /// A UNC path such as `\\server\share`, in any mix of `\` and `/`. + /// Opening it resolves the host name and authenticates to the + /// server over SMB. + UncPath, + + /// A Win32 device path (`\\.\`, `\\?\`) or an NT object path + /// (`\??\`). These reach raw volumes, named pipes, and through + /// `GLOBALROOT` any kernel object. + DevicePath, + + /// A component names a reserved DOS device such as CON or COM1. + /// Windows resolves these to the device from inside any directory. + ReservedDeviceName, + + /// The canonical path of an opened file is not `X:\...`, so the + /// file is not on a local volume with a drive letter. The canonical + /// path of a file on an SMB share is a UNC path, for example. + NotDriveAbsolute, +}; + +/// Check a path supplied by a client before it is opened. This never +/// touches the filesystem. A plain local path of any shape passes: +/// drive-absolute, drive-relative, rooted, or relative. Whether it +/// resolves to a local regular file is decided after the open with +/// `checkCanonicalPath`. +pub fn checkPath(path: []const u8) Error!void { + if (path.len >= 2 and isSep(path[0]) and isSep(path[1])) { + // `\\?\` and `\\.\` are the Win32 device namespace. Anything + // else after two separators is a server name. + if (path.len >= 4 and + (path[2] == '?' or path[2] == '.') and + isSep(path[3])) return error.DevicePath; + return error.UncPath; + } + + if (path.len >= 4 and + isSep(path[0]) and + path[1] == '?' and + path[2] == '?' and + isSep(path[3])) return error.DevicePath; + + var it = std.mem.splitAny(u8, path, "\\/"); + while (it.next()) |component| { + if (isReservedDeviceName(component)) return error.ReservedDeviceName; + } +} + +/// Check the canonical path of an opened file, as produced by +/// `GetFinalPathNameByHandle`. The file must be on a local volume with +/// a drive letter, and the checks of `checkPath` apply as well. +pub fn checkCanonicalPath(path: []const u8) Error!void { + if (!isDriveAbsolute(path)) return error.NotDriveAbsolute; + try checkPath(path); +} + +/// Returns true if `path` is a drive-absolute path (`C:\...`), the +/// only shape the canonical path of a file on a local volume with a +/// drive letter takes. +pub fn isDriveAbsolute(path: []const u8) bool { + return path.len >= 3 and + std.ascii.isAlphabetic(path[0]) and + path[1] == ':' and + path[2] == '\\'; +} + +/// Returns true if `c` is a Windows path separator. +fn isSep(c: u8) bool { + return std.fs.path.PathType.windows.isSep(u8, c); +} + +/// Returns true if a path component names a reserved DOS device: CON, +/// PRN, AUX, NUL, COM0 to COM9, LPT0 to LPT9, and the superscript digit +/// variants. +fn isReservedDeviceName(component: []const u8) bool { + // The name ends at the extension or stream separator. + const end = std.mem.findAny(u8, component, ".:") orelse component.len; + const stem = std.mem.trimEnd(u8, component[0..end], " "); + if (stem.len < 3) return false; + + const base = stem[0..3]; + const rest = stem[3..]; + if (rest.len == 0) { + return std.ascii.eqlIgnoreCase(base, "CON") or + std.ascii.eqlIgnoreCase(base, "PRN") or + std.ascii.eqlIgnoreCase(base, "AUX") or + std.ascii.eqlIgnoreCase(base, "NUL"); + } + + if (!std.ascii.eqlIgnoreCase(base, "COM") and + !std.ascii.eqlIgnoreCase(base, "LPT")) return false; + return switch (rest.len) { + 1 => std.ascii.isDigit(rest[0]), + // U+00B9, U+00B2, U+00B3 (¹ ² ³) encoded as WTF-8. + 2 => rest[0] == 0xC2 and + (rest[1] == 0xB9 or rest[1] == 0xB2 or rest[1] == 0xB3), + else => false, + }; +} + +test "checkPath rejects UNC paths" { + const testing = std.testing; + + const unc = [_][]const u8{ + "\\\\server\\share\\tty-graphics-protocol-image.data", + "//server/share/tty-graphics-protocol-image.data", + "\\/server/share/image.data", + "/\\server\\share\\image.data", + "\\\\.x\\share\\image.data", + "\\\\", + }; + for (unc) |path| { + try testing.expectError(error.UncPath, checkPath(path)); + } +} + +test "checkPath rejects device and NT namespaces" { + const testing = std.testing; + + const device = [_][]const u8{ + "\\\\?\\UNC\\server\\share\\image.data", + "\\\\?\\C:\\Windows\\Temp\\image.data", + "//?/C:/Windows/Temp/image.data", + "\\\\.\\C:\\Windows\\Temp\\image.data", + "\\\\.\\pipe\\image", + "\\\\.\\PhysicalDrive0", + "\\\\?\\GLOBALROOT\\Device\\HarddiskVolume1\\image.data", + "//?/GLOBALROOT/Device/HarddiskVolume1/image.data", + "\\??\\C:\\Windows\\Temp\\image.data", + "\\??\\Device\\HarddiskVolume1\\image.data", + "\\??\\UNC\\server\\share\\image.data", + "/??/C:/image.data", + }; + for (device) |path| { + try testing.expectError(error.DevicePath, checkPath(path)); + } +} + +test "checkPath accepts plain local paths" { + const accepted = [_][]const u8{ + "C:\\Windows\\Temp\\tty-graphics-protocol-image.data", + "C:/Windows/Temp/tty-graphics-protocol-image.data", + "c:\\image.data", + "C:image.data", + "\\Windows\\Temp\\image.data", + "/Windows/Temp/image.data", + "image.data", + ".zig-cache\\tmp\\image.data", + "C:\\Device\\HarddiskVolume1\\image.data", + "C:\\GLOBALROOT\\image.data", + "C:\\dir\\console.png", + "\\?\\image.data", + "", + }; + for (accepted) |path| { + try checkPath(path); + } +} + +test "checkPath rejects reserved device names in any component" { + const testing = std.testing; + + const reserved = [_][]const u8{ + "CON", + "con", + "CON.png", + "CON.tar.gz", + "CON.", + "CON ", + "CON .png", + "NUL:stream", + "PRN", + "AUX", + "nul", + "COM1", + "COM0", + "COM9.rgba", + "com5", + "LPT1", + "LPT9", + "lpt0.png", + "COM\xC2\xB9", + "LPT\xC2\xB3.png", + "C:\\Windows\\Temp\\NUL.rgba", + "C:\\CON\\image.data", + "dir/aux/image.data", + "C:/Windows/Temp/com1", + "..\\PRN", + }; + for (reserved) |path| { + try testing.expectError(error.ReservedDeviceName, checkPath(path)); + } + + const plain = [_][]const u8{ + "CONSOLE", + "CON1", + "xCON", + " CON", + "COM", + "COM10", + "COMA", + "COM\xC2\xB9\xC2\xB9", + "COM\xC2\xB0", + "LPT", + "LPT.png", + "conx.png", + "C:", + "C:\\", + "image.data", + "C:\\Windows\\Temp\\tty-graphics-protocol-image.data", + "C:\\Windows\\Temp\\console.png", + "", + }; + for (plain) |path| { + try checkPath(path); + } +} + +test "checkCanonicalPath requires a drive-absolute local path" { + const testing = std.testing; + + try checkCanonicalPath("C:\\Windows\\Temp\\image.data"); + try checkCanonicalPath("c:\\image.data"); + + // Shapes GetFinalPathNameByHandle produces for files that are not + // on a local drive-letter volume. + try testing.expectError( + error.NotDriveAbsolute, + checkCanonicalPath("\\\\server\\share\\image.data"), + ); + try testing.expectError( + error.NotDriveAbsolute, + checkCanonicalPath("\\\\?\\UNC\\server\\share\\image.data"), + ); + try testing.expectError( + error.NotDriveAbsolute, + checkCanonicalPath("\\\\?\\Volume{383da0b0-717f-41b6-8c36-00500992b58d}\\image.data"), + ); + + // The raw path checks still apply to the canonical form. + try testing.expectError( + error.ReservedDeviceName, + checkCanonicalPath("C:\\Windows\\Temp\\CON"), + ); +} + +test isDriveAbsolute { + const testing = std.testing; + + try testing.expect(isDriveAbsolute("C:\\Windows\\Temp\\image.data")); + try testing.expect(isDriveAbsolute("c:\\image.data")); + try testing.expect(isDriveAbsolute("Z:\\")); + + try testing.expect(!isDriveAbsolute("\\\\server\\share\\image.data")); + try testing.expect(!isDriveAbsolute("UNC\\server\\share\\image.data")); + try testing.expect(!isDriveAbsolute("C:/Windows/image.data")); + try testing.expect(!isDriveAbsolute("C:image.data")); + try testing.expect(!isDriveAbsolute("\\Windows\\image.data")); + try testing.expect(!isDriveAbsolute("1:\\image.data")); + try testing.expect(!isDriveAbsolute("C:")); + try testing.expect(!isDriveAbsolute("")); +} |
