diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 14:07:18 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 14:25:10 -0300 |
| commit | 73e324a8dc89837b5de35b5cedee3a112fad5ec4 (patch) | |
| tree | 04ba2c85a092fe4d01721013a3b4245b0bf093e6 /build | |
| parent | 20f75e147d720a6a4c98c4c3b4db067bbf55ee32 (diff) | |
| download | pardes-73e324a8dc89837b5de35b5cedee3a112fad5ec4.tar.gz pardes-73e324a8dc89837b5de35b5cedee3a112fad5ec4.zip | |
build: the upstream patches as data, applied at make time by tools/patch.zig
Each of the four upstream patches (vaxis's parser, render and queue,
zstbi, ghostty's kitty loader, mvzr) is a table of edits in
build/patches.zig: the text to find, how many times it occurs, its
replacement. tools/patch.zig (39 lines, the shape of sketchbook's
reload_edit) applies one file's table at make time, and appends what the
patch adds as a real Zig file of build/patches/ (vaxis_parser.zig,
vaxis_render.zig, ghostty_kitty.zig, mvzr_budget.zig); an edit whose text
moved or doubled writes nothing and fails that file's step. The
configure no longer reads or carries ~300 KB of patched sources: the
binary configuration halves (tui 607,524 -> 302,049 bytes, gui 643,248
-> 337,769). build/patches.zig 386 -> 338 lines, plus 57 in its four
appended files.
Gates: zig build -l and -h byte-identical, whole matrix and test/lib.
The patched files byte-identical to the base's (Parser.zig, Vaxis.zig,
queue.zig, graphics_image.zig, mvzr.zig, zstbi.c), and the four module
directories the compiles read (vaxis 53 files, ghostty 1,009, mvzr,
zstbi) identical file for file (sha256). The warm rebuild cannot be all
cached: a module root in another directory is another compile, though
its bytes are the same (a 10-line experiment shows it), so this was
built from a wiped cache: install addons, core-test shell-test unit-test
process-test on tui and gui give the base's counts (tui 2339/2486, gui
2398/2545, the same failures). pardes and pardes-gui differ from the
base's in layout only: section sizes equal, every named symbol the same
name, size and kind (tui 37,228; gui 79,507 against the base tree
relinked cold), anonymous symbols the same sizes; image.so and pdf.so
identical once their debug info is stripped. (A cold relink of the base
tree itself takes operator new from libc++abi.a rather than libc++.a,
as this one does: the base's binary was linked in another order.) A
second build is all cached, the patch runs too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'build')
| -rw-r--r-- | build/core.zig | 27 | ||||
| -rw-r--r-- | build/library.zig | 2 | ||||
| -rw-r--r-- | build/patches.zig | 544 | ||||
| -rw-r--r-- | build/patches/ghostty_kitty.zig | 15 | ||||
| -rw-r--r-- | build/patches/mvzr_budget.zig | 4 | ||||
| -rw-r--r-- | build/patches/vaxis_parser.zig | 13 | ||||
| -rw-r--r-- | build/patches/vaxis_render.zig | 25 |
7 files changed, 318 insertions, 312 deletions
diff --git a/build/core.zig b/build/core.zig index 8fced4ce..6656481a 100644 --- a/build/core.zig +++ b/build/core.zig @@ -403,8 +403,8 @@ pub fn assemble(b: *std.Build, c: struct { const target = c.target; const optimize = c.optimize; const c_optimize = c.c_optimize; - // build-time IO: slurps the grammars' highlights.scm queries, and reads - // vendor/themes to find the theme sources + // build-time IO: slurps the grammars' highlights.scm queries, reads + // vendor/themes to find the theme sources, and walks MuPDF's tree var threaded: std.Io.Threaded = .init(b.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); @@ -431,14 +431,11 @@ pub fn assemble(b: *std.Build, c: struct { const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize }); const zstbi_mod = zstbi_dep.module("root"); - // 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), and pardes searches - // with it holding the editor. Its matcher gets a step budget, patched into - // the fetched source here at build time so that a fresh fetch keeps it: - // 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 bump that moves the anchor stops the build. - const mvzr_mod = patches.mvzr(b, io, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize); + // vaxis, ghostty, mvzr and zstbi are patched as they are fetched + // (build/patches.zig), by one tool made once. + const patch = patches.tool(b); + // mvzr with a step budget, its group backtracking and `$` before `|`. + const mvzr_mod = patches.mvzr(b, patch, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize); // The C heap every C library with an allocator hook is handed: the core's // tree-sitter and fonts, and pdf.zig's MuPDF, which is a module of its own. @@ -488,7 +485,7 @@ pub fn assemble(b: *std.Build, c: struct { .external_uucode = true, }); const vaxis_mod = vaxis_dep.module("vaxis"); - patches.vaxis(b, io, vaxis_dep, vaxis_mod); + patches.vaxis(b, patch, vaxis_dep, vaxis_mod); var ghostty_vt_for_tests: ?*std.Build.Module = null; const ghostty_simd = !target.result.os.tag.isDarwin() or b.graph.host.result.os.tag.isDarwin(); @@ -498,7 +495,7 @@ pub fn assemble(b: *std.Build, c: struct { const ghostty_vt = dep.module("ghostty-vt"); ghostty_vt_for_tests = ghostty_vt; ghostty_vt.addImport("uucode", uucode_mod); - patches.ghosttyKitty(b, io, dep, ghostty_vt); + patches.ghosttyKitty(b, patch, dep, ghostty_vt); } // override uucode on vaxis LAST so it wins over ghostty's build() wiring. vaxis_mod.addImport("uucode", uucode_mod); @@ -507,10 +504,10 @@ pub fn assemble(b: *std.Build, c: struct { // ghostty-vt links for kitty graphics whatever pardes does; a terminal's // PNG is decoded through it (TerminalImages.zig), and of zstbi only its // resize is left, for the PNG's downscale: stb_image and its writer - // (with the deflate it carries) are patched out, here at build time so - // a fresh fetch keeps it. The image addon has its own (addons/image). + // (with the deflate it carries) are patched out (build/patches.zig). + // The image addon has its own (addons/image). const wuffs_mod: ?*std.Build.Module = if (ghostty_vt_for_tests) |vt| vt.import_table.get("wuffs") else null; - patches.zstbi(b, io, zstbi_dep, zstbi_mod); + patches.zstbi(b, patch, zstbi_dep, zstbi_mod); // One zstd (docs/shared-libs.md): a far replica's stream, compressed by // its session and read by its client (src/replica.zig). The library's diff --git a/build/library.zig b/build/library.zig index 7bcd6c5c..7d924fab 100644 --- a/build/library.zig +++ b/build/library.zig @@ -35,7 +35,7 @@ pub fn build(b: *std.Build) void { // then. Of vaxis it takes the grapheme width, which uucode alone feeds. if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return; const uucode = core.uucodeModule(b, target, optimize) orelse return; - const mvzr = patches.mvzr(b, io, b.lazyDependency("mvzr", .{ .target = target, .optimize = optimize }) orelse return, target, optimize); + const mvzr = patches.mvzr(b, patches.tool(b), b.lazyDependency("mvzr", .{ .target = target, .optimize = optimize }) orelse return, target, optimize); const vaxis_dep = b.lazyDependency("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) orelse return; const width = b.addWriteFiles(); _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig"); diff --git a/build/patches.zig b/build/patches.zig index 84ec4827..b6b6b86d 100644 --- a/build/patches.zig +++ b/build/patches.zig @@ -1,12 +1,38 @@ 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 +/// 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. +/// 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 @@ -16,177 +42,129 @@ const configureRead = @import("core.zig").configureRead; /// 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 = +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 \\ - \\/// 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"); - \\} + , + .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 \\ - ; - // 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 = + , + }, + .{ + .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 - ; - 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, + , + .new = \\ 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"); + , + }, + .{ + .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.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(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. @@ -195,145 +173,130 @@ pub fn vaxis(b: *std.Build, io: std.Io, vaxis_dep: *std.Build.Dependency, vaxis_ } /// 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 { +/// 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; - 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); + 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.zig"); + 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), -/// 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): +/// 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. +/// 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. -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 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.add("terminal/kitty/graphics_image.zig", b.fmt("{s}{s}", .{ src, helper })); + _ = 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"); } -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 = +/// 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; \\ - ; - 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 = + , + }, + .{ + .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. \\ - ; - const group_backoff = + , + .new = \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); \\ if (next_match) |m2| { \\ // Whole group matches, and we can use m2.j @@ -348,39 +311,28 @@ pub fn mvzr(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, target: std.B \\ 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 = + , + }, + .{ + .old = \\ '$' => { \\ if (i + 1 < in.len) { \\ - ; - const end_before_alt = + , + .new = \\ '$' => { \\ // 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 }); + , + }, + .{ .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 }); } diff --git a/build/patches/ghostty_kitty.zig b/build/patches/ghostty_kitty.zig new file mode 100644 index 00000000..a86d62d3 --- /dev/null +++ b/build/patches/ghostty_kitty.zig @@ -0,0 +1,15 @@ +/// 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, .{}); +} diff --git a/build/patches/mvzr_budget.zig b/build/patches/mvzr_budget.zig new file mode 100644 index 00000000..e1d14c12 --- /dev/null +++ b/build/patches/mvzr_budget.zig @@ -0,0 +1,4 @@ +/// 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; diff --git a/build/patches/vaxis_parser.zig b/build/patches/vaxis_parser.zig new file mode 100644 index 00000000..90b09025 --- /dev/null +++ b/build/patches/vaxis_parser.zig @@ -0,0 +1,13 @@ +/// 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"); +} diff --git a/build/patches/vaxis_render.zig b/build/patches/vaxis_render.zig new file mode 100644 index 00000000..b6c56f4e --- /dev/null +++ b/build/patches/vaxis_render.zig @@ -0,0 +1,25 @@ +/// 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], + }; +} |
