diff options
| author | Can Celik <ogulcancelik@gmail.com> | 2026-04-04 19:22:04 +0300 |
|---|---|---|
| committer | Can Celik <ogulcancelik@gmail.com> | 2026-04-05 01:23:06 +0300 |
| commit | 41dd733ca7123c9ac4bfc6c781697a660e95b052 (patch) | |
| tree | 3fc91815ca139ef2e0b281bba0abda4ef15175f4 /vendor/libghostty-vt/src/synthetic | |
| parent | 55c138263e190a1e79d4b997bfb9397306c0ec1f (diff) | |
feat: finish ghostty pane backend integration
Diffstat (limited to 'vendor/libghostty-vt/src/synthetic')
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/Bytes.zig | 119 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/Generator.zig | 42 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/Osc.zig | 366 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/Utf8.zig | 108 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/cli.zig | 115 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/cli/Ascii.zig | 68 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/cli/Osc.zig | 82 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/cli/Utf8.zig | 58 | ||||
| -rw-r--r-- | vendor/libghostty-vt/src/synthetic/main.zig | 25 |
9 files changed, 983 insertions, 0 deletions
diff --git a/vendor/libghostty-vt/src/synthetic/Bytes.zig b/vendor/libghostty-vt/src/synthetic/Bytes.zig new file mode 100644 index 00000000..7d4c34a3 --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/Bytes.zig @@ -0,0 +1,119 @@ +//! Generates bytes. +const Bytes = @This(); + +const std = @import("std"); +const Generator = @import("Generator.zig"); + +/// Random number generator. +rand: std.Random, + +/// The minimum and maximum length of the generated bytes. +min_len: usize = 1, +max_len: usize = std.math.maxInt(usize), + +/// The possible bytes that can be generated. If a byte is duplicated +/// in the alphabet, it will be more likely to be generated. That's a +/// side effect of the generator, not an intended use case. +alphabet: ?[]const u8 = null, + +/// Generate an alphabet given a function that returns true/false for a +/// given byte. +pub fn generateAlphabet(comptime func: fn (u8) bool) []const u8 { + @setEvalBranchQuota(3000); + var count = 0; + for (0..256) |c| { + if (func(c)) count += 1; + } + var alphabet: [count]u8 = undefined; + var i = 0; + for (0..256) |c| { + if (func(c)) { + alphabet[i] = c; + i += 1; + } + } + const result = alphabet; + return &result; +} + +pub fn generator(self: *Bytes) Generator { + return .init(self, next); +} + +/// Return a copy of the Bytes, but with a new alphabet. +pub fn newAlphabet(self: *const Bytes, new_alphabet: ?[]const u8) Bytes { + return .{ + .rand = self.rand, + .alphabet = new_alphabet, + .min_len = self.min_len, + .max_len = self.max_len, + }; +} + +/// Return a copy of the Bytes, but with a new min_len. The new min +/// len cannot be more than the previous max_len. +pub fn atLeast(self: *const Bytes, new_min_len: usize) Bytes { + return .{ + .rand = self.rand, + .alphabet = self.alphabet, + .min_len = @min(self.max_len, new_min_len), + .max_len = self.max_len, + }; +} + +/// Return a copy of the Bytes, but with a new max_len. The new max_len cannot +/// be more the previous max_len. +pub fn atMost(self: *const Bytes, new_max_len: usize) Bytes { + return .{ + .rand = self.rand, + .alphabet = self.alphabet, + .min_len = @min(self.min_len, @min(self.max_len, new_max_len)), + .max_len = @min(self.max_len, new_max_len), + }; +} + +pub fn next(self: *const Bytes, writer: *std.Io.Writer, max_len: usize) std.Io.Writer.Error!void { + _ = try self.atMost(max_len).write(writer); +} + +pub fn format(self: *const Bytes, writer: *std.Io.Writer) std.Io.Writer.Error!void { + _ = try self.write(writer); +} + +/// Write some random data and return the number of bytes written. +pub fn write(self: *const Bytes, writer: *std.Io.Writer) std.Io.Writer.Error!usize { + std.debug.assert(self.min_len >= 1); + std.debug.assert(self.max_len >= self.min_len); + + const len = self.rand.intRangeAtMostBiased(usize, self.min_len, self.max_len); + + var buf: [8]u8 = undefined; + + var remaining = len; + while (remaining > 0) { + const data = buf[0..@min(remaining, buf.len)]; + self.rand.bytes(data); + if (self.alphabet) |alphabet| { + for (data) |*byte| byte.* = alphabet[byte.* % alphabet.len]; + } + try writer.writeAll(data); + remaining -= data.len; + } + + return len; +} + +test "bytes" { + const testing = std.testing; + var prng = std.Random.DefaultPrng.init(0); + var buf: [256]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + var v: Bytes = .{ + .rand = prng.random(), + .min_len = buf.len, + .max_len = buf.len, + }; + const gen = v.generator(); + try gen.next(&writer, buf.len); + try testing.expectEqual(buf.len, writer.buffered().len); +} diff --git a/vendor/libghostty-vt/src/synthetic/Generator.zig b/vendor/libghostty-vt/src/synthetic/Generator.zig new file mode 100644 index 00000000..28929ecb --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/Generator.zig @@ -0,0 +1,42 @@ +/// A common interface for all generators. +const Generator = @This(); + +const std = @import("std"); +const assert = std.debug.assert; + +/// For generators, this is the only error that is allowed to be +/// returned by the next function. +pub const Error = error{WriteFailed}; + +/// The vtable for the generator. +ptr: *anyopaque, +nextFn: *const fn (ptr: *anyopaque, *std.Io.Writer, usize) Error!void, + +/// Create a new generator from a pointer and a function pointer. +/// This usually is only called by generator implementations, not +/// generator users. +pub fn init( + pointer: anytype, + comptime nextFn: fn (ptr: @TypeOf(pointer), *std.Io.Writer, usize) Error!void, +) Generator { + const Ptr = @TypeOf(pointer); + assert(@typeInfo(Ptr) == .pointer); // Must be a pointer + assert(@typeInfo(Ptr).pointer.size == .one); // Must be a single-item pointer + assert(@typeInfo(@typeInfo(Ptr).pointer.child) == .@"struct"); // Must point to a struct + const gen = struct { + fn next(ptr: *anyopaque, writer: *std.Io.Writer, max_len: usize) Error!void { + const self: Ptr = @ptrCast(@alignCast(ptr)); + try nextFn(self, writer, max_len); + } + }; + + return .{ + .ptr = pointer, + .nextFn = gen.next, + }; +} + +/// Get the next value from the generator. Returns the data written. +pub fn next(self: Generator, writer: *std.Io.Writer, max_size: usize) Error!void { + try self.nextFn(self.ptr, writer, max_size); +} diff --git a/vendor/libghostty-vt/src/synthetic/Osc.zig b/vendor/libghostty-vt/src/synthetic/Osc.zig new file mode 100644 index 00000000..00de43f7 --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/Osc.zig @@ -0,0 +1,366 @@ +/// Generates random terminal OSC requests. +const Osc = @This(); + +const std = @import("std"); +const assert = std.debug.assert; +const Generator = @import("Generator.zig"); +const Bytes = @import("Bytes.zig"); +const urlPercentEncode = @import("../os/string_encoding.zig").urlPercentEncode; + +/// Valid OSC request kinds that can be generated. +pub const ValidKind = enum { + change_window_title, + prompt_start, + prompt_end, + end_of_input, + end_of_command, + rxvt_notify, + mouse_shape, + clipboard_operation, + report_pwd, + hyperlink_start, + hyperlink_end, + conemu_progress, + iterm2_notification, +}; + +/// Invalid OSC request kinds that can be generated. +pub const InvalidKind = enum { + /// Literally random bytes. Might even be valid, but probably not. + random, + + /// A good prefix, but ultimately invalid format. + good_prefix, +}; + +/// Random number generator. +rand: std.Random, + +/// Probability of a valid OSC sequence being generated. +p_valid: f64 = 1.0, + +/// Probabilities of specific valid or invalid OSC request kinds. +/// The probabilities are weighted relative to each other, so they +/// can sum greater than 1.0. A kind of weight 1.0 and a kind of +/// weight 2.0 will have a 2:1 chance of the latter being selected. +p_valid_kind: std.enums.EnumArray(ValidKind, f64) = .initFill(1.0), +p_invalid_kind: std.enums.EnumArray(InvalidKind, f64) = .initFill(1.0), + +fn checkKvAlphabet(c: u8) bool { + return switch (c) { + std.ascii.control_code.esc, std.ascii.control_code.bel, ';', '=' => false, + else => std.ascii.isPrint(c), + }; +} + +/// The alphabet for random bytes in OSC key/value pairs (omitting 0x1B, +/// 0x07, ';', '='). +pub const kv_alphabet = Bytes.generateAlphabet(checkKvAlphabet); + +fn checkOscAlphabet(c: u8) bool { + return switch (c) { + std.ascii.control_code.esc, std.ascii.control_code.bel => false, + else => true, + }; +} + +/// The alphabet for random bytes in OSCs (omitting 0x1B and 0x07). +pub const osc_alphabet = Bytes.generateAlphabet(checkOscAlphabet); +pub const ascii_alphabet = Bytes.generateAlphabet(std.ascii.isPrint); +pub const alphabetic_alphabet = Bytes.generateAlphabet(std.ascii.isAlphabetic); +pub const alphanumeric_alphabet = Bytes.generateAlphabet(std.ascii.isAlphanumeric); + +pub fn generator(self: *Osc) Generator { + return .init(self, next); +} + +const osc = std.fmt.comptimePrint("{c}]", .{std.ascii.control_code.esc}); +const st = std.fmt.comptimePrint("{c}", .{std.ascii.control_code.bel}); + +/// Get the next OSC request in bytes. The generated OSC request will +/// have the prefix `ESC ]` and the terminator `BEL` (0x07). +/// +/// This will generate both valid and invalid OSC requests (based on +/// the `p_valid` probability value). Invalid requests still have the +/// prefix and terminator, but the content in between is not a valid +/// OSC request. +/// +/// The buffer must be at least 3 bytes long to accommodate the +/// prefix and terminator. +pub fn next(self: *Osc, writer: *std.Io.Writer, max_len: usize) Generator.Error!void { + assert(max_len >= 3); + try writer.writeAll(osc); + try self.nextUnwrapped(writer, max_len - (osc.len + st.len)); + try writer.writeAll(st); +} + +fn nextUnwrapped(self: *Osc, writer: *std.Io.Writer, max_len: usize) Generator.Error!void { + return switch (self.chooseValidity()) { + .valid => valid: { + const Indexer = @TypeOf(self.p_valid_kind).Indexer; + const idx = self.rand.weightedIndex(f64, &self.p_valid_kind.values); + break :valid try self.nextUnwrappedValidExact( + writer, + Indexer.keyForIndex(idx), + max_len, + ); + }, + + .invalid => invalid: { + const Indexer = @TypeOf(self.p_invalid_kind).Indexer; + const idx = self.rand.weightedIndex(f64, &self.p_invalid_kind.values); + break :invalid try self.nextUnwrappedInvalidExact( + writer, + Indexer.keyForIndex(idx), + max_len, + ); + }, + }; +} + +fn nextUnwrappedValidExact(self: *const Osc, writer: *std.Io.Writer, k: ValidKind, max_len: usize) Generator.Error!void { + switch (k) { + .change_window_title => change_window_title: { + if (max_len < 3) break :change_window_title; + try writer.print("0;{f}", .{self.bytes().atMost(max_len - 3)}); // Set window title + }, + + .prompt_start => prompt_start: { + if (max_len < 4) break :prompt_start; + var remaining = max_len; + + try writer.writeAll("133;A"); // Start prompt + remaining -= 4; + + // aid + if (self.rand.boolean()) aid: { + if (remaining < 6) break :aid; + try writer.writeAll(";aid="); + remaining -= 5; + remaining -= try self.bytes().newAlphabet(kv_alphabet).atMost(@min(16, remaining)).write(writer); + } + + // redraw + if (self.rand.boolean()) redraw: { + if (remaining < 9) break :redraw; + try writer.writeAll(";redraw="); + if (self.rand.boolean()) { + try writer.writeAll("1"); + } else { + try writer.writeAll("0"); + } + remaining -= 9; + } + }, + + .prompt_end => prompt_end: { + if (max_len < 4) break :prompt_end; + try writer.writeAll("133;B"); // End prompt + }, + + .end_of_input => end_of_input: { + if (max_len < 5) break :end_of_input; + var remaining = max_len; + try writer.writeAll("133;C"); // End prompt + remaining -= 5; + if (self.rand.boolean()) cmdline: { + const prefix = ";cmdline_url="; + if (remaining < prefix.len + 1) break :cmdline; + try writer.writeAll(prefix); + remaining -= prefix.len; + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try self.bytes().newAlphabet(ascii_alphabet).atMost(@min(remaining, buf.len)).format(&w); + try urlPercentEncode(writer, w.buffered()); + remaining -= w.buffered().len; + } + }, + + .end_of_command => end_of_command: { + if (max_len < 4) break :end_of_command; + try writer.writeAll("133;D"); // End prompt + if (self.rand.boolean()) exit_code: { + if (max_len < 7) break :exit_code; + try writer.print(";{d}", .{self.rand.int(u8)}); + } + }, + + .mouse_shape => mouse_shape: { + if (max_len < 4) break :mouse_shape; + try writer.print("22;{f}", .{self.bytes().newAlphabet(alphabetic_alphabet).atMost(@min(32, max_len - 3))}); // Start prompt + }, + + .rxvt_notify => rxvt_notify: { + const prefix = "777;notify;"; + if (max_len < prefix.len) break :rxvt_notify; + var remaining = max_len; + try writer.writeAll(prefix); + remaining -= prefix.len; + remaining -= try self.bytes().newAlphabet(kv_alphabet).atMost(@min(remaining - 2, 32)).write(writer); + try writer.writeByte(';'); + remaining -= 1; + remaining -= try self.bytes().newAlphabet(osc_alphabet).atMost(remaining).write(writer); + }, + + .clipboard_operation => { + try writer.writeAll("52;"); + var remaining = max_len - 3; + if (self.rand.boolean()) { + remaining -= try self.bytes().newAlphabet(alphabetic_alphabet).atMost(1).write(writer); + } + try writer.writeByte(';'); + remaining -= 1; + if (self.rand.boolean()) { + remaining -= try self.bytes().newAlphabet(osc_alphabet).atMost(remaining).write(writer); + } + }, + + .report_pwd => report_pwd: { + const prefix = "7;file://localhost"; + if (max_len < prefix.len) break :report_pwd; + var remaining = max_len; + try writer.writeAll(prefix); + remaining -= prefix.len; + for (0..self.rand.intRangeAtMost(usize, 2, 5)) |_| { + try writer.writeByte('/'); + remaining -= 1; + remaining -= try self.bytes().newAlphabet(alphanumeric_alphabet).atMost(@min(16, remaining)).write(writer); + } + }, + + .hyperlink_start => { + try writer.writeAll("8;"); + if (self.rand.boolean()) { + try writer.print("id={f}", .{self.bytes().newAlphabet(alphanumeric_alphabet).atMost(16)}); + } + try writer.writeAll(";https://localhost"); + for (0..self.rand.intRangeAtMost(usize, 2, 5)) |_| { + try writer.print("/{f}", .{self.bytes().newAlphabet(alphanumeric_alphabet).atMost(16)}); + } + }, + + .hyperlink_end => hyperlink_end: { + if (max_len < 3) break :hyperlink_end; + try writer.writeAll("8;;"); + }, + + .conemu_progress => { + try writer.writeAll("9;"); + switch (self.rand.intRangeAtMost(u3, 0, 4)) { + 0, 3 => |c| { + try writer.print(";{d}", .{c}); + }, + 1, 2, 4 => |c| { + if (self.rand.boolean()) { + try writer.print(";{d}", .{c}); + } else { + try writer.print(";{d};{d}", .{ c, self.rand.intRangeAtMost(u8, 0, 100) }); + } + }, + else => unreachable, + } + }, + + .iterm2_notification => iterm2_notification: { + if (max_len < 3) break :iterm2_notification; + // add a prefix to ensure that this is not interpreted as a ConEmu OSC + try writer.print("9;_{f}", .{self.bytes().newAlphabet(ascii_alphabet).atMost(max_len - 3)}); + }, + } +} + +fn nextUnwrappedInvalidExact( + self: *const Osc, + writer: *std.Io.Writer, + k: InvalidKind, + max_len: usize, +) Generator.Error!void { + switch (k) { + .random => { + try self.bytes().atMost(max_len).format(writer); + }, + + .good_prefix => { + try writer.print("133;{f}", .{self.bytes().atMost(max_len - 4)}); + }, + } +} + +fn bytes(self: *const Osc) Bytes { + return .{ + .rand = self.rand, + .alphabet = osc_alphabet, + }; +} + +/// Choose whether to generate a valid or invalid OSC request based +/// on the validity probability. +fn chooseValidity(self: *const Osc) Validity { + return if (self.rand.float(f64) > self.p_valid) + .invalid + else + .valid; +} + +const Validity = enum { valid, invalid }; + +/// A fixed seed we can use for our tests to avoid flakes. +const test_seed = 0xC0FFEEEEEEEEEEEE; + +test "OSC generator" { + const testing = std.testing; + var prng = std.Random.DefaultPrng.init(test_seed); + var buf: [256]u8 = undefined; + { + var v: Osc = .{ + .rand = prng.random(), + }; + const gen = v.generator(); + for (0..50) |_| { + var writer: std.Io.Writer = .fixed(&buf); + try gen.next(&writer, buf.len); + const result = writer.buffered(); + try testing.expect(result.len > 0); + } + } +} + +test "OSC generator valid" { + const testing = std.testing; + const terminal = @import("../terminal/main.zig"); + + var prng = std.Random.DefaultPrng.init(test_seed); + var buf: [256]u8 = undefined; + var gen: Osc = .{ + .rand = prng.random(), + .p_valid = 1.0, + }; + for (0..50) |_| { + var writer: std.Io.Writer = .fixed(&buf); + try gen.next(&writer, buf.len); + const seq = writer.buffered(); + var parser: terminal.osc.Parser = .init(null); + for (seq[2 .. seq.len - 1]) |c| parser.next(c); + try testing.expect(parser.end(null) != null); + } +} + +test "OSC generator invalid" { + const testing = std.testing; + const terminal = @import("../terminal/main.zig"); + + var prng = std.Random.DefaultPrng.init(test_seed); + var buf: [256]u8 = undefined; + var gen: Osc = .{ + .rand = prng.random(), + .p_valid = 0.0, + }; + for (0..50) |_| { + var writer: std.Io.Writer = .fixed(&buf); + try gen.next(&writer, buf.len); + const seq = writer.buffered(); + var parser: terminal.osc.Parser = .init(null); + for (seq[2 .. seq.len - 1]) |c| parser.next(c); + try testing.expect(parser.end(null) == null); + } +} diff --git a/vendor/libghostty-vt/src/synthetic/Utf8.zig b/vendor/libghostty-vt/src/synthetic/Utf8.zig new file mode 100644 index 00000000..0d72a8bb --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/Utf8.zig @@ -0,0 +1,108 @@ +/// Generates UTF-8. +/// +/// This doesn't yet generate multi-codepoint graphemes, but it +/// has the ability to generate a custom distribution of UTF-8 +/// encoding lengths (1, 2, 3, or 4 bytes). +const Utf8 = @This(); + +const std = @import("std"); +const assert = std.debug.assert; +const Generator = @import("Generator.zig"); + +/// Possible UTF-8 encoding lengths. +pub const Utf8Len = enum(u3) { + one = 1, + two = 2, + three = 3, + four = 4, +}; + +/// Random number generator. +rand: std.Random, + +/// The minimum and maximum length of the generated bytes. The maximum +/// length will be capped to the length of the buffer passed in if the +/// buffer length is smaller. +min_len: usize = 1, +max_len: usize = std.math.maxInt(usize), + +/// Probability of a specific UTF-8 encoding length being generated. +/// The probabilities are weighted relative to each other, so they +/// can sum greater than 1.0. A length of weight 1.0 and a length +/// of weight 2.0 will have a 2:1 chance of the latter being +/// selected. +/// +/// If a UTF-8 encoding of a chosen length can't fit into the remaining +/// buffer, a smaller length will be chosen. For small buffers this may +/// skew the distribution of lengths. +p_length: std.enums.EnumArray(Utf8Len, f64) = .initFill(1.0), + +pub fn generator(self: *Utf8) Generator { + return .init(self, next); +} + +pub fn next(self: *Utf8, writer: *std.Io.Writer, max_len: usize) Generator.Error!void { + const len = @min( + self.rand.intRangeAtMostBiased(usize, self.min_len, self.max_len), + max_len, + ); + + var rem: usize = len; + while (rem > 0) { + // Pick a utf8 byte count to generate. + const utf8_len: Utf8Len = len: { + const Indexer = @TypeOf(self.p_length).Indexer; + const idx = self.rand.weightedIndex(f64, &self.p_length.values); + var utf8_len = Indexer.keyForIndex(idx); + assert(rem > 0); + while (@intFromEnum(utf8_len) > rem) { + // If the chosen length can't fit into the remaining buffer, + // choose a smaller length. + utf8_len = @enumFromInt(@intFromEnum(utf8_len) - 1); + } + break :len utf8_len; + }; + + // Generate a UTF-8 sequence that encodes to this length. + const cp: u21 = switch (utf8_len) { + .one => self.rand.intRangeAtMostBiased(u21, 0x00, 0x7F), + .two => self.rand.intRangeAtMostBiased(u21, 0x80, 0x7FF), + .three => self.rand.intRangeAtMostBiased(u21, 0x800, 0xFFFF), + .four => self.rand.intRangeAtMostBiased(u21, 0x10000, 0x10FFFF), + }; + + assert(std.unicode.utf8CodepointSequenceLength( + cp, + ) catch unreachable == @intFromEnum(utf8_len)); + + var buf: [4]u8 = undefined; + const l = std.unicode.utf8Encode( + cp, + &buf, + ) catch |err| switch (err) { + // Impossible because our generation above is hardcoded to + // produce a valid range. If not, a bug. + error.CodepointTooLarge => unreachable, + + // Possible, in which case we redo the loop and encode nothing. + error.Utf8CannotEncodeSurrogateHalf => continue, + }; + try writer.writeAll(buf[0..l]); + rem -= l; + } +} + +test "utf8" { + const testing = std.testing; + var prng = std.Random.DefaultPrng.init(0); + var buf: [256]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + var v: Utf8 = .{ .rand = prng.random() }; + v.min_len = buf.len; + v.max_len = buf.len; + const gen = v.generator(); + try gen.next(&writer, buf.len); + const result = writer.buffered(); + try testing.expectEqual(256, result.len); + try testing.expect(std.unicode.utf8ValidateSlice(result)); +} diff --git a/vendor/libghostty-vt/src/synthetic/cli.zig b/vendor/libghostty-vt/src/synthetic/cli.zig new file mode 100644 index 00000000..d9b6a659 --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/cli.zig @@ -0,0 +1,115 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const cli = @import("../cli.zig"); + +/// The available actions for the CLI. This is the list of available +/// synthetic generators. View docs for each individual one in the +/// predictably named files under `cli/`. +pub const Action = enum { + ascii, + osc, + utf8, + + /// Returns the struct associated with the action. The struct + /// should have a few decls: + /// + /// - `const Options`: The CLI options for the action. + /// - `fn create`: Create a new instance of the action from options. + /// - `fn destroy`: Destroy the instance of the action. + /// + /// See TerminalStream for an example. + pub fn Struct(comptime action: Action) type { + return switch (action) { + .ascii => @import("cli/Ascii.zig"), + .osc => @import("cli/Osc.zig"), + .utf8 => @import("cli/Utf8.zig"), + }; + } +}; + +/// An entrypoint for the synthetic generator CLI. +pub fn main() !void { + const alloc = std.heap.c_allocator; + const action_ = try cli.action.detectArgs(Action, alloc); + const action = action_ orelse return error.NoAction; + try mainAction(alloc, action, .cli); +} + +pub const Args = union(enum) { + /// The arguments passed to the CLI via argc/argv. + cli, + + /// Simple string arguments, parsed via std.process.ArgIteratorGeneral. + string: []const u8, +}; + +pub fn mainAction( + alloc: Allocator, + action: Action, + args: Args, +) !void { + switch (action) { + inline else => |comptime_action| { + const Impl = Action.Struct(comptime_action); + try mainActionImpl(Impl, alloc, args); + }, + } +} + +fn mainActionImpl( + comptime Impl: type, + alloc: Allocator, + args: Args, +) !void { + // First, parse our CLI options. + const Options = Impl.Options; + var opts: Options = .{}; + defer if (@hasDecl(Options, "deinit")) opts.deinit(); + switch (args) { + .cli => { + var iter = try cli.args.argsIterator(alloc); + defer iter.deinit(); + try cli.args.parse(Options, alloc, &opts, &iter); + }, + .string => |str| { + var iter = try std.process.ArgIteratorGeneral(.{}).init( + alloc, + str, + ); + defer iter.deinit(); + try cli.args.parse(Options, alloc, &opts, &iter); + }, + } + + // TODO: Make this a command line option. + const seed: u64 = @truncate(@as( + u128, + @bitCast(std.time.nanoTimestamp()), + )); + var prng = std.Random.DefaultPrng.init(seed); + const rand = prng.random(); + + // Our output always goes to stdout. + var buffer: [2048]u8 = undefined; + var stdout_writer = std.fs.File.stdout().writer(&buffer); + const writer = &stdout_writer.interface; + + // Create our implementation + const impl = try Impl.create(alloc, opts); + defer impl.destroy(alloc); + try impl.run(writer, rand); + + // Always flush + writer.flush() catch |err| switch (err) { + error.WriteFailed => return, + }; +} + +test { + // Make sure we ref all our actions + inline for (@typeInfo(Action).@"enum".fields) |field| { + const action = @field(Action, field.name); + const Impl = Action.Struct(action); + _ = Impl; + } +} diff --git a/vendor/libghostty-vt/src/synthetic/cli/Ascii.zig b/vendor/libghostty-vt/src/synthetic/cli/Ascii.zig new file mode 100644 index 00000000..d416189c --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/cli/Ascii.zig @@ -0,0 +1,68 @@ +const Ascii = @This(); + +const std = @import("std"); +const assert = std.debug.assert; +const Allocator = std.mem.Allocator; +const Bytes = @import("../Bytes.zig"); + +const log = std.log.scoped(.@"terminal-stream-bench"); + +pub const Options = struct {}; + +fn checkAsciiAlphabet(c: u8) bool { + return switch (c) { + ' ' => false, + else => std.ascii.isPrint(c), + }; +} + +pub const ascii = Bytes.generateAlphabet(checkAsciiAlphabet); + +/// Create a new terminal stream handler for the given arguments. +pub fn create( + alloc: Allocator, + _: Options, +) !*Ascii { + const ptr = try alloc.create(Ascii); + errdefer alloc.destroy(ptr); + return ptr; +} + +pub fn destroy(self: *Ascii, alloc: Allocator) void { + alloc.destroy(self); +} + +pub fn run(_: *Ascii, writer: *std.Io.Writer, rand: std.Random) !void { + var gen: Bytes = .{ + .rand = rand, + .alphabet = ascii, + .min_len = 1024, + .max_len = 1024, + }; + + while (true) { + _ = gen.write(writer) catch |err| { + const Error = error{ WriteFailed, BrokenPipe } || @TypeOf(err); + switch (@as(Error, err)) { + error.BrokenPipe => return, // stdout closed + error.WriteFailed => return, // fixed buffer full + else => return err, + } + }; + } +} + +test Ascii { + const testing = std.testing; + const alloc = testing.allocator; + + const impl: *Ascii = try .create(alloc, .{}); + defer impl.destroy(alloc); + + var prng = std.Random.DefaultPrng.init(1); + const rand = prng.random(); + + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try impl.run(&writer, rand); +} diff --git a/vendor/libghostty-vt/src/synthetic/cli/Osc.zig b/vendor/libghostty-vt/src/synthetic/cli/Osc.zig new file mode 100644 index 00000000..686563fc --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/cli/Osc.zig @@ -0,0 +1,82 @@ +const Osc = @This(); + +const std = @import("std"); +const assert = std.debug.assert; +const Allocator = std.mem.Allocator; +const synthetic = @import("../main.zig"); + +const log = std.log.scoped(.@"terminal-stream-bench"); + +pub const Options = struct { + /// Probability of generating a valid value. + @"p-valid": f64 = 0.5, + + style: enum { + /// Write all OSC data, including ESC ] and ST for end-to-end tests + streaming, + /// Only write data, prefixed with a length, used for testing just the + /// OSC parser. + parser, + } = .streaming, +}; + +opts: Options, + +/// Create a new terminal stream handler for the given arguments. +pub fn create( + alloc: Allocator, + opts: Options, +) !*Osc { + const ptr = try alloc.create(Osc); + errdefer alloc.destroy(ptr); + ptr.* = .{ .opts = opts }; + return ptr; +} + +pub fn destroy(self: *Osc, alloc: Allocator) void { + alloc.destroy(self); +} + +pub fn run(self: *Osc, writer: *std.Io.Writer, rand: std.Random) !void { + var gen: synthetic.Osc = .{ + .rand = rand, + .p_valid = self.opts.@"p-valid", + }; + + var buf: [1024]u8 = undefined; + while (true) { + var fixed: std.Io.Writer = .fixed(&buf); + try gen.next(&fixed, buf.len); + const data = fixed.buffered(); + switch (self.opts.style) { + .streaming => { + writer.writeAll(data) catch |err| switch (err) { + error.WriteFailed => return, + }; + }, + .parser => { + writer.writeInt(usize, data.len - 3, .little) catch |err| switch (err) { + error.WriteFailed => return, + }; + writer.writeAll(data[2 .. data.len - 1]) catch |err| switch (err) { + error.WriteFailed => return, + }; + }, + } + } +} + +test Osc { + const testing = std.testing; + const alloc = testing.allocator; + + const impl: *Osc = try .create(alloc, .{}); + defer impl.destroy(alloc); + + var prng = std.Random.DefaultPrng.init(1); + const rand = prng.random(); + + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try impl.run(&writer, rand); +} diff --git a/vendor/libghostty-vt/src/synthetic/cli/Utf8.zig b/vendor/libghostty-vt/src/synthetic/cli/Utf8.zig new file mode 100644 index 00000000..63570475 --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/cli/Utf8.zig @@ -0,0 +1,58 @@ +const Utf8 = @This(); + +const std = @import("std"); +const assert = std.debug.assert; +const Allocator = std.mem.Allocator; +const synthetic = @import("../main.zig"); + +const log = std.log.scoped(.@"terminal-stream-bench"); + +pub const Options = struct {}; + +/// Create a new terminal stream handler for the given arguments. +pub fn create( + alloc: Allocator, + _: Options, +) !*Utf8 { + const ptr = try alloc.create(Utf8); + errdefer alloc.destroy(ptr); + return ptr; +} + +pub fn destroy(self: *Utf8, alloc: Allocator) void { + alloc.destroy(self); +} + +pub fn run(self: *Utf8, writer: *std.Io.Writer, rand: std.Random) !void { + _ = self; + + var gen: synthetic.Utf8 = .{ + .rand = rand, + }; + + while (true) { + gen.next(writer, 1024) catch |err| { + const Error = error{ WriteFailed, BrokenPipe } || @TypeOf(err); + switch (@as(Error, err)) { + error.BrokenPipe => return, // stdout closed + error.WriteFailed => return, // fixed buffer full + else => return err, + } + }; + } +} + +test Utf8 { + const testing = std.testing; + const alloc = testing.allocator; + + const impl: *Utf8 = try .create(alloc, .{}); + defer impl.destroy(alloc); + + var prng = std.Random.DefaultPrng.init(1); + const rand = prng.random(); + + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try impl.run(&writer, rand); +} diff --git a/vendor/libghostty-vt/src/synthetic/main.zig b/vendor/libghostty-vt/src/synthetic/main.zig new file mode 100644 index 00000000..85f9f7d3 --- /dev/null +++ b/vendor/libghostty-vt/src/synthetic/main.zig @@ -0,0 +1,25 @@ +//! The synthetic package contains an abstraction for generating +//! synthetic data. The motivating use case for this package is to +//! generate synthetic data for benchmarking, but it may also expand +//! to other use cases such as fuzzing (e.g. to generate a corpus +//! rather than directly fuzzing). +//! +//! The generators in this package are typically not performant +//! enough to be streamed in real time. They should instead be +//! used to generate a large amount of data in a single go +//! and then streamed from there. +//! +//! The generators are aimed for terminal emulation, but the package +//! is not limited to that and we may want to extract this to a +//! standalone package one day. + +pub const cli = @import("cli.zig"); + +pub const Generator = @import("Generator.zig"); +pub const Bytes = @import("Bytes.zig"); +pub const Utf8 = @import("Utf8.zig"); +pub const Osc = @import("Osc.zig"); + +test { + @import("std").testing.refAllDecls(@This()); +} |
