summaryrefslogtreecommitdiff
path: root/build/patches.zig
diff options
context:
space:
mode:
Diffstat (limited to 'build/patches.zig')
-rw-r--r--build/patches.zig386
1 files changed, 386 insertions, 0 deletions
diff --git a/build/patches.zig b/build/patches.zig
new file mode 100644
index 00000000..84ec4827
--- /dev/null
+++ b/build/patches.zig
@@ -0,0 +1,386 @@
+const std = @import("std");
+const configureRead = @import("core.zig").configureRead;
+
+/// vaxis's input parser, patched here at build time like mvzr so that a
+/// fresh fetch keeps it: no reply, split read or malformed sequence may
+/// reach the editor as typed text, and none may panic or end input.
+/// - A cursor position report that no F3 could have sent is no key: the
+/// startup width queries' `CSI 1;1R` arrived as two F3s, which a shell
+/// pane took for text.
+/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key,
+/// not Alt+Escape followed by `[A` as text.
+/// - An X10 mouse report and a kitty graphics reply cut short by a read
+/// wait for their rest: the first became three bytes of text, the
+/// second sliced past its input.
+/// - A byte no UTF-8 starts with is dropped instead of failing the parse,
+/// which stopped input. (vaxis itself now drops a malformed color or
+/// clipboard reply and ends an OSC at its first terminator.)
+/// - A device report's fields are sought in the sequence, not past it.
+/// A bump that moves an anchor stops the build.
+pub fn vaxis(b: *std.Build, io: std.Io, vaxis_dep: *std.Build.Dependency, vaxis_mod: *std.Build.Module) void {
+ var src = configureRead(b, io, vaxis_dep.builder.root, "src/Parser.zig", 1 << 20) catch @panic("read vaxis Parser.zig");
+ const edits = [_]struct { anchor: []const u8, with: []const u8, count: usize = 1 }{
+ .{
+ .anchor =
+ \\ 0x5F => return parseApc(input),
+ \\ else => {
+ ,
+ .with =
+ \\ 0x5F => return parseApc(input),
+ \\ // pardes's patch (its build.zig): ESC before a key's sequence is Alt on the key.
+ \\ 0x1B => if (input.len > 2 and (input[2] == '[' or input[2] == 'O')) {
+ \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf, self.cursor_position_requests) else parseSs3(input[1..]);
+ \\ if (inner.n == 0) return inner;
+ \\ if (inner.event) |*event| switch (event.*) {
+ \\ .key_press, .key_release => |*key| key.mods.alt = true,
+ \\ else => {},
+ \\ };
+ \\ inner.n += 1;
+ \\ return inner;
+ \\ } else return .{ .event = .{ .key_press = .{ .codepoint = Key.escape, .mods = .{ .alt = true } } }, .n = 2 },
+ \\ else => {
+ ,
+ },
+ .{
+ .anchor = " const first_cp = iter.next() orelse return error.InvalidUTF8;\n",
+ .with = " const first_cp = iter.next() orelse return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n",
+ },
+ .{
+ .anchor = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return error.InvalidUTF8;\n",
+ .with = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n",
+ },
+ .{
+ .anchor =
+ \\ const sequence = input[0 .. end + 1 + 1];
+ \\
+ \\ switch (input[2]) {
+ ,
+ .with =
+ \\ // pardes's patch (its build.zig): an ESC that ends the input is half an ST.
+ \\ if (input.len < end + 2) return .{ .event = null, .n = 0 };
+ \\ const sequence = input[0 .. end + 1 + 1];
+ \\
+ \\ switch (input[2]) {
+ ,
+ },
+ .{
+ .anchor =
+ \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => {
+ \\ // Legacy keys
+ \\
+ ,
+ .with =
+ \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => {
+ \\ // pardes's patch (its build.zig): a cursor position report is no key.
+ \\ if (final == 'R' and cursorReport(sequence)) return null_event;
+ \\ // Legacy keys
+ \\
+ ,
+ },
+ .{
+ .anchor = " std.debug.assert(sequence.len >= 4); // ESC [ ? c == 4 bytes\n",
+ .with = " if (sequence.len < 4) return null_event; // pardes's patch (its build.zig)\n",
+ },
+ .{
+ .anchor = "const delim_idx = std.mem.indexOfScalarPos(u8, input, 3, ';')",
+ .with = "const delim_idx = std.mem.indexOfScalarPos(u8, sequence, 3, ';')",
+ .count = 2,
+ },
+ .{
+ .anchor = "input[delim_idx + 1 .. sequence.len - 2]",
+ .with = "sequence[@min(delim_idx + 1, sequence.len - 2) .. sequence.len - 2]",
+ },
+ .{
+ .anchor = " if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {\n",
+ .with =
+ \\ // pardes's patch (its build.zig): an X10 report still arriving is incomplete, not text.
+ \\ if (input.len == 3 and input[2] == 'M' and full_input.len < 6) return .{ .event = null, .n = 0 };
+ \\ if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {
+ \\
+ ,
+ },
+ };
+ for (edits) |edit| {
+ if (std.mem.count(u8, src, edit.anchor) != edit.count) std.debug.panic("vaxis's Parser.zig changed at `{s}`: redo its patch in build.zig", .{edit.anchor});
+ src = std.mem.replaceOwned(u8, b.allocator, src, edit.anchor, edit.with) catch @panic("OOM");
+ }
+ const cursor_report =
+ \\
+ \\/// pardes's patch (its build.zig): whether `CSI ... R` answers a cursor
+ \\/// position query. Only `CSI 1 ; mods R` with mods past 1 is a modified F3
+ \\/// (a bare F3 is `SS3 R`); a report has another row, or col 1 (mods 1).
+ \\fn cursorReport(sequence: []const u8) bool {
+ \\ const params = sequence[2 .. sequence.len - 1];
+ \\ if (params.len > 0 and params[0] == '?') return true;
+ \\ var fields = std.mem.splitScalar(u8, params, ';');
+ \\ const row = fields.first();
+ \\ const col = fields.next() orelse return false;
+ \\ if (fields.next() != null or row.len == 0 or col.len == 0) return false;
+ \\ for (params) |c| if (c != ';' and !std.ascii.isDigit(c)) return false;
+ \\ return !std.mem.eql(u8, row, "1") or std.mem.eql(u8, col, "1");
+ \\}
+ \\
+ ;
+ // vaxis's render, patched the same way: a blank whose ink alone
+ // changed is not sent, since a blank's ink shows nowhere. A fade
+ // (InactiveDim on a focus change) sent every blank of every pane it
+ // touched again: 7 KB a click for three shell panes. The terminal
+ // keeps the old ink there, and so does vaxis's last frame.
+ var render_src = configureRead(b, io, vaxis_dep.builder.root, "src/Vaxis.zig", 1 << 20) catch @panic("read vaxis Vaxis.zig");
+ const render_anchor =
+ \\ if ((!self.refresh and
+ \\ last.eql(cell) and
+ ;
+ if (std.mem.count(u8, render_src, render_anchor) != 1) std.debug.panic("vaxis's Vaxis.zig changed at `{s}`: redo its patch in build.zig", .{render_anchor});
+ render_src = std.mem.replaceOwned(u8, b.allocator, render_src, render_anchor,
+ \\ if ((!self.refresh and
+ \\ (last.eql(cell) or blankInkOnly(&last, &cell)) and // pardes's patch (its build.zig)
+ \\
+ ) catch @panic("OOM");
+ // And the secondary cursors count as changed when they differ, not
+ // when they are the same: read the other way round, every render
+ // started a frame, ~40 bytes to the terminal with nothing changed.
+ const secondary_anchor = " std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary);\n";
+ if (std.mem.count(u8, render_src, secondary_anchor) != 1) std.debug.panic("vaxis's Vaxis.zig changed at `{s}`: redo its patch in build.zig", .{secondary_anchor});
+ render_src = std.mem.replaceOwned(u8, b.allocator, render_src, secondary_anchor, " !std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary); // pardes's patch (its build.zig)\n") catch @panic("OOM");
+ const blank_ink =
+ \\
+ \\/// pardes's patch (its build.zig): a blank cell (a space, no underline,
+ \\/// strike or reverse) that differs from the last frame's blank in its
+ \\/// ink alone, which shows nowhere.
+ \\inline fn blankInkOnly(last: *const InternalScreen.InternalCell, cell: *const Cell) bool {
+ \\ if (!(cell.char.grapheme.len == 1 and cell.char.grapheme[0] == ' ')) return false;
+ \\ if (last.default or cell.default) return false;
+ \\ if (!(last.char.items.len == 1 and last.char.items[0] == ' ')) return false;
+ \\ const s = cell.style;
+ \\ if (s.reverse or s.strikethrough or s.ul_style != .off) return false;
+ \\ if (!std.mem.eql(u8, last.uri.items, cell.link.uri)) return false;
+ \\ // Field by field: Style.eql is slow, and this runs for every blank
+ \\ // a scrolling shell moves.
+ \\ const l = last.style;
+ \\ return sameColor(l.bg, s.bg) and sameColor(l.ul, s.ul) and l.ul_style == s.ul_style and
+ \\ l.bold == s.bold and l.dim == s.dim and l.italic == s.italic and l.blink == s.blink and
+ \\ !l.reverse and !l.strikethrough and l.invisible == s.invisible;
+ \\}
+ \\
+ \\inline fn sameColor(a: Cell.Color, b: Cell.Color) bool {
+ \\ return switch (a) {
+ \\ .default => b == .default,
+ \\ .index => |i| b == .index and b.index == i,
+ \\ .rgb => |rgb| b == .rgb and rgb[0] == b.rgb[0] and rgb[1] == b.rgb[1] and rgb[2] == b.rgb[2],
+ \\ };
+ \\}
+ \\
+ ;
+ // And its event queue: a pop that makes room woke one blocked
+ // writer, and only on the pop from full. The tui has two writers
+ // (a pane's pty reader, and the input reader posting the frame
+ // ack's wake), so when the loop emptied a full queue in one batch
+ // the writer not woken waited on for good: under `yes` the pane
+ // stopped being read, its program blocked on the pty, while keys
+ // went on working. Every blocked writer is woken now.
+ var queue_src = configureRead(b, io, vaxis_dep.builder.root, "src/queue.zig", 1 << 20) catch @panic("read vaxis queue.zig");
+ const wake_one = "self.not_full.signal(self.io);";
+ if (std.mem.count(u8, queue_src, wake_one) != 2) std.debug.panic("vaxis's queue.zig changed at `{s}`: redo its patch in build.zig", .{wake_one});
+ queue_src = std.mem.replaceOwned(u8, b.allocator, queue_src, wake_one, "self.not_full.broadcast(self.io); // pardes's patch (its build.zig)") catch @panic("OOM");
+ const files = b.addWriteFiles();
+ _ = files.add("Parser.zig", b.fmt("{s}{s}", .{ src, cursor_report }));
+ _ = files.add("Vaxis.zig", b.fmt("{s}{s}", .{ render_src, blank_ink }));
+ _ = files.add("queue.zig", queue_src);
+ _ = files.addCopyFile(vaxis_dep.path("src/widgets/terminal/Parser.zig"), "widgets/terminal/Parser.zig");
+ // Suffixes: this leaves out both Parser.zig files, Vaxis.zig and
+ // queue.zig, written above.
+ _ = files.addCopyDirectory(vaxis_dep.path("src"), "", .{ .exclude_extensions = &.{ "Parser.zig", "Vaxis.zig", "queue.zig" } });
+ vaxis_mod.root_source_file = files.getDirectory().path(b, "main.zig");
+}
+
+/// zstbi with stb_image and its writer cut out: of it only its resize is
+/// left, for a terminal PNG's downscale (build.zig, "One PNG decoder").
+pub fn zstbi(b: *std.Build, io: std.Io, zstbi_dep: *std.Build.Dependency, zstbi_mod: *std.Build.Module) void {
+ var sources: usize = 0;
+ for (zstbi_mod.link_objects.items) |obj| switch (obj) {
+ .c_source_file => |csf| {
+ sources += 1;
+ var src = configureRead(b, io, zstbi_dep.builder.root, "src/zstbi.c", 1 << 20) catch @panic("read zstbi.c");
+ // zstbi.deinit still resets the reader's and the writer's
+ // flip flags, and Image.deinit frees the resize's output.
+ for ([_][2][]const u8{
+ .{ "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" },
+ .{ "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" },
+ }) |cut| {
+ if (std.mem.count(u8, src, cut[0]) != 1) std.debug.panic("zstbi.c changed at `{s}`: redo its patch in build.zig", .{cut[0]});
+ src = std.mem.replaceOwned(u8, b.allocator, src, cut[0], cut[1]) catch @panic("OOM");
+ }
+ csf.file = b.addWriteFiles().add("zstbi.c", src);
+ },
+ else => {},
+ };
+ if (sources != 1) @panic("zstbi's build no longer compiles one C file: redo its patch in build.zig");
+}
+
+/// ghostty's kitty graphics loader (src/terminal/kitty/graphics_image.zig),
+/// patched at build time so a fresh fetch keeps it, for what a program in a
+/// pane may name with t=f, t=t and t=s (test/kitty.zig):
+/// - a path is opened for reading only once it is known to be a regular
+/// file: ghostty opens first and checks after, and the open of a FIFO
+/// waits for a writer (pardes hung) while a device's open may do
+/// something. On Linux an O_PATH probe looks, which opens nothing, and
+/// the same inode is reopened through /proc/self/fd; elsewhere a stat by
+/// path looks first.
+/// - shared memory is opened non-blocking and must be a regular file, so
+/// a FIFO in /dev/shm (or a symlink there to one) neither hangs nor maps.
+/// - an image may be no larger than a screen's storage
+/// (TerminalImages.storage_limit) rather than ghostty's 400 MB, which a
+/// program could make pardes read and hold before refusing it.
+pub fn ghosttyKitty(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, vt: *std.Build.Module) void {
+ const rel = "src/terminal/kitty/graphics_image.zig";
+ var src = configureRead(b, io, dep.builder.root, rel, 1 << 22) catch @panic("read ghostty's graphics_image.zig");
+ const edits = [_][2][]const u8{
+ .{
+ "const max_size = 400 * 1024 * 1024; // 400MB",
+ "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit",
+ },
+ .{
+ \\ var file = std.Io.Dir.cwd().openFile(
+ \\ io,
+ \\ path,
+ \\ .{},
+ \\ ) catch |err| {
+ ,
+ \\ var file = pardesOpenRegular(io, path) catch |err| {
+ },
+ .{
+ " const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), @as(u16, 0));",
+ \\ // pardes (build.zig): a FIFO there must not hang the open, and
+ \\ // on Linux nothing but a regular file is opened at all. FreeBSD's
+ \\ // names are no files, and its shm_open refuses O_NONBLOCK.
+ \\ if (comptime builtin.target.os.tag == .linux) if (path.len > 0 and path[0] == '/') {
+ \\ var dev: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ \\ const full = std.fmt.bufPrint(&dev, "/dev/shm{s}", .{path}) catch return error.InvalidData;
+ \\ const shm_stat = std.Io.Dir.cwd().statFile(io, full, .{}) catch return error.InvalidData;
+ \\ if (shm_stat.kind != .file) return error.InvalidData;
+ \\ };
+ \\ const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY, .NONBLOCK = builtin.target.os.tag != .freebsd })), @as(u16, 0));
+ },
+ .{
+ " if (stat.size <= 0) return error.InvalidData;",
+ " if (stat.kind != .file) return error.InvalidData; // pardes (build.zig)\n if (stat.size <= 0) return error.InvalidData;",
+ },
+ };
+ for (edits) |edit| {
+ if (std.mem.count(u8, src, edit[0]) != 1) std.debug.panic("ghostty's {s} changed at `{s}`: redo its patch in build.zig", .{ rel, edit[0] });
+ src = std.mem.replaceOwned(u8, b.allocator, src, edit[0], edit[1]) catch @panic("OOM");
+ }
+ const helper =
+ \\
+ \\/// pardes (build.zig): `path`, opened for reading only once it is known
+ \\/// to be a regular file. Elsewhere than Linux, a stat by path first.
+ \\fn pardesOpenRegular(io: std.Io, path: []const u8) !std.Io.File {
+ \\ if (comptime builtin.target.os.tag != .linux) {
+ \\ if ((try std.Io.Dir.cwd().statFile(io, path, .{})).kind != .file) return error.NotRegularFile;
+ \\ return std.Io.Dir.cwd().openFile(io, path, .{});
+ \\ }
+ \\ const probe = try std.Io.Dir.cwd().openFile(io, path, .{ .path_only = true });
+ \\ defer probe.close(io);
+ \\ const stat = try probe.stat(io);
+ \\ if (stat.kind != .file) return error.NotRegularFile;
+ \\ var buf: [32]u8 = undefined;
+ \\ const same = std.fmt.bufPrint(&buf, "/proc/self/fd/{d}", .{probe.handle}) catch unreachable;
+ \\ return std.Io.Dir.cwd().openFile(io, same, .{});
+ \\}
+ \\
+ ;
+ const files = b.addWriteFiles();
+ // The rest of src as it is; fonts are the app's, not the library's.
+ _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", ".ttf", ".otf" } });
+ _ = files.add("terminal/kitty/graphics_image.zig", b.fmt("{s}{s}", .{ src, helper }));
+ vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig");
+}
+
+pub fn mvzr(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
+ const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr");
+ const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n";
+ const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len;
+ const spend =
+ \\ if (steps_left == 0) {
+ \\ exhausted = true;
+ \\ return null;
+ \\ }
+ \\ steps_left -= 1;
+ \\
+ ;
+ const budget =
+ \\
+ \\/// pardes's patch (its build.zig): matchPattern entries left before a
+ \\/// match gives up, and whether one did. Set by the caller per search.
+ \\pub threadlocal var steps_left: u64 = std.math.maxInt(u64);
+ \\pub threadlocal var exhausted: bool = false;
+ \\
+ ;
+ const budgeted = b.fmt("{s}{s}{s}{s}", .{ src[0..at], spend, src[at..], budget });
+ // A group's greedy match never gave back to what follows the group:
+ // on `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the
+ // group's own `)` as an alternative, so every group with pattern
+ // after it takes matchGroup's alternatives branch, which tries each
+ // alternative's one (greedy) match and gives up. When the rest fails
+ // after it, try that alternative's shorter matches, longest first
+ // (docs/mvzr-group-backtrack.md is the report for upstream).
+ const group_anchor =
+ \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i);
+ \\ if (next_match) |m2| {
+ \\ // Whole group matches, and we can use m2.j
+ \\ return m2;
+ \\ } else { // Try our next pattern, if any.
+ \\
+ ;
+ const group_backoff =
+ \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i);
+ \\ if (next_match) |m2| {
+ \\ // Whole group matches, and we can use m2.j
+ \\ return m2;
+ \\ } else { // Try our next pattern, if any.
+ \\ // pardes's patch (its build.zig): back the group off.
+ \\ var e = m1.i;
+ \\ while (e > i) {
+ \\ e -= 1;
+ \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue;
+ \\ if (shorter.i != e) continue;
+ \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole;
+ \\ }
+ \\
+ ;
+ if (std.mem.count(u8, budgeted, group_anchor) != 1) @panic("mvzr's matchGroup changed: redo its group backtracking in build.zig");
+ const backed = std.mem.replaceOwned(u8, b.allocator, budgeted, group_anchor, group_backoff) catch @panic("OOM");
+ // `$` is refused anywhere but last, so `h$|zz` was a bad pattern
+ // while `zz|h$` was fine. An alternative or a group ends at `|` and
+ // `)`, and the matcher's `.end` ends the alternative it is in, so
+ // `$` may stand before either (docs/mvzr-group-backtrack.md).
+ const end_anchor =
+ \\ '$' => {
+ \\ if (i + 1 < in.len) {
+ \\
+ ;
+ const end_before_alt =
+ \\ '$' => {
+ \\ // pardes's patch (its build.zig): `$` may end an alternative.
+ \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') {
+ \\
+ ;
+ if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig");
+ var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM");
+ // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream).
+ // A class's range ending at `\xff` counted to 256 in a u8, an
+ // overflow (a panic in a safe build, a runaway loop in a fast one):
+ // `[\x80-\xff]` in any search took the editor down.
+ for ([_][3][]const u8{
+ .{ "for (c1..c2 + 1) |c_range|", "for (c1..@as(usize, c2) + 1) |c_range|", "1" },
+ .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" },
+ .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" },
+ .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" },
+ .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" },
+ }) |edit| {
+ if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]});
+ patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM");
+ }
+ return b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize });
+}