summaryrefslogtreecommitdiff
path: root/build/patches.zig
diff options
context:
space:
mode:
Diffstat (limited to 'build/patches.zig')
-rw-r--r--build/patches.zig338
1 files changed, 338 insertions, 0 deletions
diff --git a/build/patches.zig b/build/patches.zig
new file mode 100644
index 00000000..b6b6b86d
--- /dev/null
+++ b/build/patches.zig
@@ -0,0 +1,338 @@
+const std = @import("std");
+
+/// The upstream patches: each a table of edits to one fetched file, applied
+/// at make time by tools/patch.zig, with what it appends a file of its own
+/// in build/patches/. Each is applied so that a fresh fetch keeps it, and a
+/// bump that moves an anchor fails that file's step.
+const Edit = struct { old: []const u8, new: []const u8, count: u8 = 1 };
+
+/// tools/patch.zig, made once and handed to each patch below.
+pub fn tool(b: *std.Build) *std.Build.Step.Compile {
+ return b.addExecutable(.{ .name = "pardes-patch", .root_module = b.createModule(.{
+ .root_source_file = b.path("tools/patch.zig"),
+ .target = b.graph.host,
+ }) });
+}
+
+/// `file` of `dep` with `edits` applied, and build/patches/`append` after them.
+fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, file: []const u8, edits: []const Edit, append: ?[]const u8) std.Build.LazyPath {
+ const run = b.addRunArtifact(patch);
+ run.setName(b.fmt("patch {s}", .{file}));
+ run.addFileArg(dep.path(file));
+ const out = run.addOutputFileArg(std.fs.path.basename(file));
+ if (append) |name| {
+ run.addArg("--append");
+ run.addFileArg(b.path(b.fmt("build/patches/{s}", .{name})));
+ }
+ for (edits) |e| run.addArgs(&.{ b.fmt("{d}", .{e.count}), e.old, e.new });
+ return out;
+}
+
+/// vaxis's input parser: 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 (build/patches/vaxis_parser.zig).
+/// - 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.
+const vaxis_parser = [_]Edit{
+ .{
+ .old =
+ \\ 0x5F => return parseApc(input),
+ \\ else => {
+ ,
+ .new =
+ \\ 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 => {
+ ,
+ },
+ .{
+ .old = " const first_cp = iter.next() orelse return error.InvalidUTF8;\n",
+ .new = " const first_cp = iter.next() orelse return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n",
+ },
+ .{
+ .old = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return error.InvalidUTF8;\n",
+ .new = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n",
+ },
+ .{
+ .old =
+ \\ const sequence = input[0 .. end + 1 + 1];
+ \\
+ \\ switch (input[2]) {
+ ,
+ .new =
+ \\ // 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]) {
+ ,
+ },
+ .{
+ .old =
+ \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => {
+ \\ // Legacy keys
+ \\
+ ,
+ .new =
+ \\ '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
+ \\
+ ,
+ },
+ .{
+ .old = " std.debug.assert(sequence.len >= 4); // ESC [ ? c == 4 bytes\n",
+ .new = " if (sequence.len < 4) return null_event; // pardes's patch (its build.zig)\n",
+ },
+ .{
+ .old = "const delim_idx = std.mem.indexOfScalarPos(u8, input, 3, ';')",
+ .new = "const delim_idx = std.mem.indexOfScalarPos(u8, sequence, 3, ';')",
+ .count = 2,
+ },
+ .{
+ .old = "input[delim_idx + 1 .. sequence.len - 2]",
+ .new = "sequence[@min(delim_idx + 1, sequence.len - 2) .. sequence.len - 2]",
+ },
+ .{
+ .old = " if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {\n",
+ .new =
+ \\ // 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) {
+ \\
+ ,
+ },
+};
+
+/// vaxis's render: a blank whose ink alone changed is not sent, since a
+/// blank's ink shows nowhere (build/patches/vaxis_render.zig). 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. 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 vaxis_render = [_]Edit{
+ .{
+ .old =
+ \\ if ((!self.refresh and
+ \\ last.eql(cell) and
+ ,
+ .new =
+ \\ if ((!self.refresh and
+ \\ (last.eql(cell) or blankInkOnly(&last, &cell)) and // pardes's patch (its build.zig)
+ \\
+ ,
+ },
+ .{
+ .old = " std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary);\n",
+ .new = " !std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary); // pardes's patch (its build.zig)\n",
+ },
+};
+
+/// vaxis's 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.
+const vaxis_queue = [_]Edit{
+ .{ .old = "self.not_full.signal(self.io);", .new = "self.not_full.broadcast(self.io); // pardes's patch (its build.zig)", .count = 2 },
+};
+
+pub fn vaxis(b: *std.Build, patch: *std.Build.Step.Compile, vaxis_dep: *std.Build.Dependency, vaxis_mod: *std.Build.Module) void {
+ const files = b.addWriteFiles();
+ _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/Parser.zig", &vaxis_parser, "vaxis_parser.zig"), "Parser.zig");
+ _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/Vaxis.zig", &vaxis_render, "vaxis_render.zig"), "Vaxis.zig");
+ _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/queue.zig", &vaxis_queue, null), "queue.zig");
+ _ = 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/core.zig, "One PNG
+/// decoder"). zstbi.deinit still resets the reader's and the writer's flip
+/// flags, and Image.deinit frees the resize's output.
+const zstbi_cut = [_]Edit{
+ .{ .old = "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", .new = "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" },
+ .{ .old = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", .new = "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" },
+};
+
+pub fn zstbi(b: *std.Build, patch: *std.Build.Step.Compile, 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;
+ csf.file = apply(b, patch, zstbi_dep, "src/zstbi.c", &zstbi_cut, null);
+ },
+ else => {},
+ };
+ if (sources != 1) @panic("zstbi's build no longer compiles one C file: redo its patch in build/patches.zig");
+}
+
+/// ghostty's kitty graphics loader (src/terminal/kitty/graphics_image.zig),
+/// 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 (build/patches/ghostty_kitty.zig).
+/// - 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.
+const ghostty_kitty = [_]Edit{
+ .{
+ .old = "const max_size = 400 * 1024 * 1024; // 400MB",
+ .new = "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit",
+ },
+ .{
+ .old =
+ \\ var file = std.Io.Dir.cwd().openFile(
+ \\ io,
+ \\ path,
+ \\ .{},
+ \\ ) catch |err| {
+ ,
+ .new =
+ \\ var file = pardesOpenRegular(io, path) catch |err| {
+ ,
+ },
+ .{
+ .old = " const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), @as(u16, 0));",
+ .new =
+ \\ // 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));
+ ,
+ },
+ .{
+ .old = " if (stat.size <= 0) return error.InvalidData;",
+ .new = " if (stat.kind != .file) return error.InvalidData; // pardes (build.zig)\n if (stat.size <= 0) return error.InvalidData;",
+ },
+};
+
+pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, vt: *std.Build.Module) void {
+ 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.addCopyFile(apply(b, patch, dep, "src/terminal/kitty/graphics_image.zig", &ghostty_kitty, "ghostty_kitty.zig"), "terminal/kitty/graphics_image.zig");
+ vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig");
+}
+
+/// mvzr, whose matcher pardes searches with while holding the editor:
+/// - A step budget (build/patches/mvzr_budget.zig): mvzr backtracks with
+/// no bound on its work (its own test "do not make this test any
+/// longer": `a?` n times is 2^n steps), so each entry to matchPattern,
+/// which its backtracking recurses through, spends a step, and with none
+/// left the match fails and says so (src/regexp.zig).
+/// - 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).
+/// - `$` 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).
+/// - 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.
+const mvzr_edits = [_]Edit{
+ .{
+ .old = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n",
+ .new =
+ \\fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {
+ \\ if (steps_left == 0) {
+ \\ exhausted = true;
+ \\ return null;
+ \\ }
+ \\ steps_left -= 1;
+ \\
+ ,
+ },
+ .{
+ .old =
+ \\ 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.
+ \\
+ ,
+ .new =
+ \\ 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;
+ \\ }
+ \\
+ ,
+ },
+ .{
+ .old =
+ \\ '$' => {
+ \\ if (i + 1 < in.len) {
+ \\
+ ,
+ .new =
+ \\ '$' => {
+ \\ // pardes's patch (its build.zig): `$` may end an alternative.
+ \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') {
+ \\
+ ,
+ },
+ .{ .old = "for (c1..c2 + 1) |c_range|", .new = "for (c1..@as(usize, c2) + 1) |c_range|" },
+ .{ .old = "[1]RegOp{.{ .unused = {} }} ** ops", .new = "@splat(.{ .unused = {} })" },
+ .{ .old = "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", .new = "@splat(.{ .low = 0, .hi = 0 })" },
+ .{ .old = "\"a\" ** 2048", .new = "&@as([2048]u8, @splat('a'))", .count = 2 },
+ .{ .old = "\"12345,\" ** 255", .new = "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))" },
+};
+
+pub fn mvzr(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
+ return b.createModule(.{ .root_source_file = apply(b, patch, dep, "src/mvzr.zig", &mvzr_edits, "mvzr_budget.zig"), .target = target, .optimize = optimize });
+}