diff options
| -rw-r--r-- | abi/addon.zig | 23 | ||||
| -rw-r--r-- | abi/pardes_addon.h | 9 | ||||
| -rw-r--r-- | addons/image/image.zig | 1 | ||||
| -rw-r--r-- | addons/life/life.zig | 1 | ||||
| -rw-r--r-- | addons/pdf/pdf.out | 33 | ||||
| -rw-r--r-- | addons/pdf/pdf.script | 8 | ||||
| -rw-r--r-- | addons/pdf/pdf.zig | 10 | ||||
| -rw-r--r-- | addons/pdf/pdf_bridge.c | 2 | ||||
| -rw-r--r-- | addons/pdf/pdf_bridge.h | 7 | ||||
| -rw-r--r-- | addons/snake/snake.zig | 1 | ||||
| -rw-r--r-- | addons/snake_shader/snake_shader.zig | 1 | ||||
| -rw-r--r-- | core/Jump.zig | 33 | ||||
| -rw-r--r-- | core/Kind.zig | 11 | ||||
| -rw-r--r-- | core/Messages.zig | 21 | ||||
| -rw-r--r-- | core/Query.zig | 30 | ||||
| -rw-r--r-- | core/Stream.zig | 51 | ||||
| -rw-r--r-- | core/colors.zig | 52 | ||||
| -rw-r--r-- | core/diff.zig | 7 | ||||
| -rw-r--r-- | core/fuzz.zig | 98 | ||||
| -rw-r--r-- | core/hunks.zig | 6 | ||||
| -rw-r--r-- | core/look.zig | 134 | ||||
| -rw-r--r-- | core/replica.zig | 32 | ||||
| -rw-r--r-- | core/walk.zig | 39 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 238 | ||||
| -rw-r--r-- | runtime/main.zig | 3 | ||||
| -rw-r--r-- | runtime/upgrade.zig | 102 | ||||
| -rw-r--r-- | test/behaviour/addons.zig | 8 | ||||
| -rw-r--r-- | test/behaviour/addons_pdf.zig | 2 | ||||
| -rw-r--r-- | test/daemon.py | 4 | ||||
| -rw-r--r-- | test/liar.zig | 1 | ||||
| -rw-r--r-- | test/pdf-fixtures/huge-pages.pdf | 61 | ||||
| -rw-r--r-- | test/veil.zig | 1 |
32 files changed, 972 insertions, 58 deletions
diff --git a/abi/addon.zig b/abi/addon.zig index 059e016d..53227fbb 100644 --- a/abi/addon.zig +++ b/abi/addon.zig @@ -20,9 +20,10 @@ //! //! and pardes's side (pa_api) as the functions below: `arena` and `heap` //! as Allocators, `seed`, `say`, `job`, `draw`, `cancel`, `look`, `text`, `exec`, -//! `select` and `found`. A body written is at most `body_max` bytes. +//! `select`, `found` and `panic`. A body written is at most `body_max` bytes. //! //! pub const pardes_addon = addon.ops(Snake); +//! pub const panic = addon.panic; //! comptime { //! addon.exportLib(&pardes_addon); //! } @@ -36,9 +37,9 @@ pub const c = @import("pardes_addon"); const Allocator = std.mem.Allocator; /// The ABI this file speaks: a header of another needs it brought along. -pub const abi = 0x30002; +pub const abi = 0x30003; comptime { - if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.2 and the header another"); + if (c.PA_ABI != abi) @compileError("addon.zig speaks ABI 3.3 and the header another"); } /// A word the kind brings: `opens` a pane of it, else goes to the pane's @@ -51,6 +52,19 @@ pub const Head = struct { name: []const u8, version: u32, exts: [:0]const u8 = " /// pardes's side, kept from init: about the pane of the current call. pub var api: *const c.pa_api = undefined; +/// pardes's panic (pa_api.panic), from init, when its pardes has one. +var host_panic: ?*const fn ([*c]const u8, u32) callconv(.c) void = null; + +/// A library kind's panic handler (its root's `pub const panic = +/// addon.panic;`): pardes's own, so the panic ends the process as one of +/// pardes's does (its crash record, its terminal put back, its clients +/// told); std's where its pardes is older than ABI 3.3, or before init. +pub const panic = std.debug.FullPanic(struct { + fn call(msg: []const u8, ret_addr: ?usize) noreturn { + if (host_panic) |f| f(msg.ptr, @intCast(@min(msg.len, std.math.maxInt(u32)))); + std.debug.defaultPanic(msg, ret_addr); + } +}.call); /// The pane's arena: 16-aligned zeroed memory, all of it freed at the /// pane's close (a free frees nothing). @@ -91,7 +105,7 @@ pub fn job(in: []const u8) u32 { /// of the process that shows the pane, its answer to `jobDone` there alone /// (`token & drawn`), which keeps it for `paint` only. 0 when refused. pub fn draw(in: []const u8) u32 { - if (api.size < @sizeOf(c.pa_api)) return 0; + if (api.size < @offsetOf(c.pa_api, "draw") + @sizeOf(@TypeOf(api.draw))) return 0; return api.draw.?(in.ptr, @intCast(in.len)); } pub const drawn = c.PA_DRAWN; @@ -283,6 +297,7 @@ pub fn ops(comptime T: type) c.pa_ops { } fn init(a: [*c]const c.pa_api) callconv(.c) c_int { api = a; + if (a.*.size >= @offsetOf(c.pa_api, "panic") + @sizeOf(@TypeOf(a.*.panic))) host_panic = a.*.panic; return if (!@hasDecl(T, "init") or T.init()) c.PA_OK else 1; } fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque { diff --git a/abi/pardes_addon.h b/abi/pardes_addon.h index 2f5c53de..d8257a0b 100644 --- a/abi/pardes_addon.h +++ b/abi/pardes_addon.h @@ -37,7 +37,7 @@ /* Major in the high half: an addon of another major is refused. */ #define PA_ABI_MAJOR 3u -#define PA_ABI_MINOR 2u +#define PA_ABI_MINOR 3u #define PA_ABI ((PA_ABI_MAJOR << 16) | PA_ABI_MINOR) #define PA_OK 0 #define PA_RASTER_MAX (32u << 20) /* a placement's w*h*4 above this is dropped, said once */ @@ -234,6 +234,11 @@ typedef struct pa_api { * PA_PLAIN kind's block, nor its token) `paint` alone reads; no other * call reads it, or anything made from it. 0: refused. */ uint32_t (*draw)(const void *in, uint32_t n); + /* Since 3.3 (check api->size): the addon panicked (a Zig addon's + * `pub const panic = addon.panic;`, a C addon's fatal error). pardes ends + * as at a panic of its own: its crash record written, its terminal put + * back, its clients told; it does not return. */ + void (*panic)(const char *msg, uint32_t n); } pa_api; /* A token of api->draw's. */ #define PA_DRAWN 0x80000000u @@ -390,7 +395,7 @@ _Static_assert(sizeof(pa_rect) == 16 && sizeof(pa_cells) == 8, "pa_rect"); _Static_assert(sizeof(pa_placement) == 80, "pa_placement"); _Static_assert(sizeof(pa_paint) == 48 && sizeof(pa_view) == 32 && sizeof(pa_tick) == 128, "pa_paint"); _Static_assert(sizeof(pa_key) == 8 && sizeof(pa_mouse) == 16, "pa_key"); -_Static_assert(sizeof(pa_api) == 120 && sizeof(pa_out) == 16, "pa_api"); +_Static_assert(sizeof(pa_api) == 128 && sizeof(pa_out) == 16, "pa_api"); _Static_assert(sizeof(pa_word) == 32 && sizeof(pa_head) == 56, "pa_head"); _Static_assert(sizeof(pa_ops) == 208, "pa_ops"); #endif diff --git a/addons/image/image.zig b/addons/image/image.zig index 8e2cb32a..5b7976ac 100644 --- a/addons/image/image.zig +++ b/addons/image/image.zig @@ -128,6 +128,7 @@ pub const Image = extern struct { }; pub const pardes_addon = addon.ops(Image); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } diff --git a/addons/life/life.zig b/addons/life/life.zig index 254f248d..c49878cd 100644 --- a/addons/life/life.zig +++ b/addons/life/life.zig @@ -5,6 +5,7 @@ const std = @import("std"); const addon = @import("addon"); pub const pardes_addon = addon.ops(Life); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } diff --git a/addons/pdf/pdf.out b/addons/pdf/pdf.out index 49ba2a88..2d4566b1 100644 --- a/addons/pdf/pdf.out +++ b/addons/pdf/pdf.out @@ -201,3 +201,36 @@ tag [3/16] petscii:on palette:commodore ascii:on docs/design.pdf |the native macOS host watches with debounced DispatchSourc |instead, then restats the exact path under a pane-generati |guard. All three macOS watchers mark the same two things f +> open test/pdf-fixtures/huge-pages.pdf +window 58x1 +tag [1/4] petscii:on palette:commodore ascii:on test/pdf-fixtures/huge-pages.pdf +| a page past 16777216 pt on a side: laid out at that size +| +> graphics on +tag [1/4] petscii:off palette:commodore ascii:on test/pdf-fixtures/huge-pages.pdf +| a page past 16777216 pt on a side: laid out at that size +| +placement 1x1 src 0,0 1x1 over 0,1 58x1 key fb85a0e4117bdb75 at 0,0 464x1 +placement 1200x1200 src 0,0 1200x19 over 0,1 58x1 key a44f40e9b170318e at 0,9 464x7 +> size 60 20 +window 58x1 +tag [1/4] petscii:off palette:commodore ascii:on test/pdf-fixtures/huge-pages.pdf +| a page past 16777216 pt on a side: laid out at that size +| +placement 1x1 src 0,0 1x1 over 0,1 58x1 key fb85a0e4117bdb75 at 0,0 464x1 +placement 1200x1200 src 0,0 1200x19 over 0,1 58x1 key a44f40e9b170318e at 0,9 464x7 +> key j +tag [2/4] petscii:off palette:commodore ascii:on test/pdf-fixtures/huge-pages.pdf +| a page past 16777216 pt on a side: laid out at that size +| +placement 1200x1200 src 0,18 1200x42 over 0,1 58x1 key a44f40e9b170318e at 0,0 464x16 +> key 2j +tag [2/4] petscii:off palette:commodore ascii:on test/pdf-fixtures/huge-pages.pdf +| a page past 16777216 pt on a side: laid out at that size +| +placement 1200x1200 src 0,100 1200x43 over 0,1 58x1 key a44f40e9b170318e at 0,0 464x16 +> key G +tag [4/4] petscii:off palette:commodore ascii:on test/pdf-fixtures/huge-pages.pdf +| a page past 16777216 pt on a side: laid out at that size +| +placement 816x64 src 0,0 816x29 over 0,1 58x1 key aa6de78f475e58f7 at 0,0 464x16 diff --git a/addons/pdf/pdf.script b/addons/pdf/pdf.script index 60e4bfca..62629ded 100644 --- a/addons/pdf/pdf.script +++ b/addons/pdf/pdf.script @@ -23,3 +23,11 @@ key 3gj key gk key 999gj key gj +# pages past any size (a side of 1e9 pt, one past a float, a UserUnit +# past a float): laid out and drawn at the bridge's bound, never a panic +open test/pdf-fixtures/huge-pages.pdf +graphics on +size 60 20 +key j +key 2j +key G diff --git a/addons/pdf/pdf.zig b/addons/pdf/pdf.zig index bc75e039..7ee3400a 100644 --- a/addons/pdf/pdf.zig +++ b/addons/pdf/pdf.zig @@ -35,6 +35,7 @@ const m = @import("pdf_bridge"); const c = addon.c; pub const pardes_addon = addon.ops(Pdf); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } @@ -270,6 +271,7 @@ pub const Pdf = extern struct { return addon.say("not a PDF pardes can read", .err); } o.d = d; + sayHuge(o.size[0..1]); st.pages = @intCast(pages); // every page the first's size until a lane measures them o.measured = st.pages == 1; @@ -812,6 +814,7 @@ pub const Pdf = extern struct { if (res.n != st.pages or sizes.len != st.pages) return; for (o.size, sizes) |*to, from| to.* = from; o.measured = true; + sayHuge(o.size); // laid again where a page is not the first's size for (o.size) |s| if (!std.meta.eql(s, o.size[0])) { for (&st.views) |*l| l.laid = false; @@ -958,6 +961,13 @@ fn ownOf(st: *const Pdf) *Own { } /// Page `p`'s size as the strip is laid with it. +/// A page the bridge held to its bound (a crafted MediaBox) is said. +fn sayHuge(sizes: []const m.pardes_pdf_page_size) void { + const most: f32 = m.PARDES_PDF_MAX_PAGE_POINTS; + for (sizes) |s| if (s.width >= most or s.height >= most) + return addon.say(std.fmt.comptimePrint("a page past {d} pt on a side: laid out at that size", .{m.PARDES_PDF_MAX_PAGE_POINTS}), .note); +} + fn sizeOf(st: *const Pdf, o: *Own, p: usize) m.pardes_pdf_page_size { if (st.sizes != .measured) return o.size[0]; // A client joined after the lane measured them: measured here. diff --git a/addons/pdf/pdf_bridge.c b/addons/pdf/pdf_bridge.c index 3b326655..e1279f51 100644 --- a/addons/pdf/pdf_bridge.c +++ b/addons/pdf/pdf_bridge.c @@ -591,6 +591,8 @@ pardes_pdf_get_page_size( out->height = bounds.y1 - bounds.y0; if (!(out->width > 0.0f) || !(out->height > 0.0f)) fz_throw(ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); + out->width = fminf(out->width, PARDES_PDF_MAX_PAGE_POINTS); + out->height = fminf(out->height, PARDES_PDF_MAX_PAGE_POINTS); } fz_catch(ctx) { diff --git a/addons/pdf/pdf_bridge.h b/addons/pdf/pdf_bridge.h index fd5d05d0..0e52c505 100644 --- a/addons/pdf/pdf_bridge.h +++ b/addons/pdf/pdf_bridge.h @@ -203,7 +203,12 @@ enum { PARDES_PDF_MAX_LINK_URI_BYTES = 64 * 1024, /* No page raster is taller than this, whatever it is shown at. */ - PARDES_PDF_MAX_RASTER_ROWS = 1 << 20 + PARDES_PDF_MAX_RASTER_ROWS = 1 << 20, + + /* No page is laid out wider or taller than this, in points (5.9 km): a + * crafted MediaBox or UserUnit has any size, a float's infinity too, and + * MuPDF bounds neither; pdf.zig counts a page's pixels in u32s. */ + PARDES_PDF_MAX_PAGE_POINTS = 1 << 24 }; pardes_pdf_document *pardes_pdf_open_memory(const unsigned char *bytes, size_t length, int *page_count); diff --git a/addons/snake/snake.zig b/addons/snake/snake.zig index ef2283ac..9f2bdd4e 100644 --- a/addons/snake/snake.zig +++ b/addons/snake/snake.zig @@ -131,6 +131,7 @@ pub const Snake = extern struct { }; pub const pardes_addon = addon.ops(Snake); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } diff --git a/addons/snake_shader/snake_shader.zig b/addons/snake_shader/snake_shader.zig index 039e07b0..65e1dd44 100644 --- a/addons/snake_shader/snake_shader.zig +++ b/addons/snake_shader/snake_shader.zig @@ -372,6 +372,7 @@ pub const Snake = extern struct { }; pub const pardes_addon = addon.ops(Snake); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } diff --git a/core/Jump.zig b/core/Jump.zig index b68da32d..ccdb8fdc 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -203,12 +203,15 @@ pub fn trackJump(p: *Pardes) void { }; } // Two in a row the same (a closed one reopened beside its own, - // or the entry between them gone): one entry, one step. - if (w > 0 and std.meta.eql(v.jumps.list[w - 1], kept)) { + // or the entry between them gone): one entry, one step; the same + // as the digest sees them (a text's `place` is bytes undefined). + // Compared where it is stored (w <= i: read already): a pointer + // to `kept` put it on the stack for every entry of every step. + v.jumps.list[w] = kept; + if (w > 0 and pardes.walk.eql(Loc, &v.jumps.list[w - 1], &v.jumps.list[w])) { if (i == v.jumps.cur) cur = w - 1; continue; } - v.jumps.list[w] = kept; w += 1; } v.jumps.n = w; @@ -361,12 +364,34 @@ test "the jump list never holds two entries in a row the same, when the one betw p.view().jumps.cur = 3; pane.body.cur_row = 80; // where you are now: far from both trackJump(p); - for (1..p.view().jumps.n) |i| try std.testing.expect(!std.meta.eql(p.view().jumps.list[i - 1], p.view().jumps.list[i])); + for (1..p.view().jumps.n) |i| try std.testing.expect(!pardes.walk.eql(Loc, &p.view().jumps.list[i - 1], &p.view().jumps.list[i])); try std.testing.expectEqual(@as(usize, 3), p.view().jumps.n); try std.testing.expectEqual(@as(u32, 1), p.view().jumps.list[0].line); try std.testing.expectEqual(@as(u32, 150), p.view().jumps.list[1].line); } +test "two entries the same but for the bytes past their place's length are one entry, as the digest sees them, on every build" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile(std.mem.asBytes(&@as([200][2]u8, @splat("a\n".*)))); + // A text's entry has no place: `.place = .{}`, its bytes undefined, + // 0xAA on every Debug process and each release process's own (the + // stack's, a load's): one entry on every side or a client parts. + var a: Loc = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 1 }; + var b = a; + @memset(&a.place.bytes, 0x11); + @memset(&b.place.bytes, 0x22); + p.view().jumps.list[0] = a; + p.view().jumps.list[1] = .{ .pane = 5, .serial = 999, .line = 1, .col = 1 }; + p.view().jumps.list[2] = b; + p.view().jumps.list[3] = .{ .pane = 0, .serial = pane.serial, .line = 150, .col = 1 }; + p.view().jumps.n = 4; + p.view().jumps.cur = 3; + pane.body.cur_row = 80; + trackJump(p); + try std.testing.expectEqual(@as(usize, 3), p.view().jumps.n); +} + test "jump history skips an entry whose pane slot or serial is gone, leaving the selection" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); diff --git a/core/Kind.zig b/core/Kind.zig index 5d2dcdb0..764b6f06 100644 --- a/core/Kind.zig +++ b/core/Kind.zig @@ -41,7 +41,7 @@ comptime { if (@sizeOf(usize) == 8) for (.{ .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 }, .{ c.pa_placement, 80 }, .{ c.pa_paint, 48 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 16 }, - .{ c.pa_api, 120 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, + .{ c.pa_api, 128 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, .{ c.pa_ops, 208 }, .{ c.pa_view, 32 }, .{ c.pa_tick, 128 }, }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] })); } @@ -1229,6 +1229,15 @@ pub const api: c.pa_api = .{ return token; } }.f, + .panic = struct { + /// An addon's panic is pardes's (its root's handler: the crash + /// record, the terminal, the clients): a call into it never returns. + fn f(msg: [*c]const u8, n: u32) callconv(.c) void { + var buf: [512]u8 = undefined; + const said = cSlice(msg, n); + @panic(std.fmt.bufPrint(&buf, "an addon's panic: {s}", .{said}) catch said); + } + }.f, .found = struct { /// Gathered in the call: the search's answer, or onto its +Search after. fn f(rows: [*c]const u8, n: u32) callconv(.c) void { diff --git a/core/Messages.zig b/core/Messages.zig index 46dab136..18b10ff8 100644 --- a/core/Messages.zig +++ b/core/Messages.zig @@ -192,6 +192,7 @@ pub fn expireUnattended(p: *Pardes) void { for (p.panes) |slot| { const pane = slot orelse continue; if (pane.msg_len == 0 and pane.msg_older_len == 0) continue; + if (awaited(p, pane)) continue; if (now - pane.msg_said_ms < p.settings.message_linger_ms) continue; pane.msg_len = 0; pane.msg_life = .{}; @@ -200,10 +201,30 @@ pub fn expireUnattended(p: *Pardes) void { } } +/// A message waits for someone to see it, and a view kept for its client's +/// return (views.away: an Upgrade's clients, a divergence's) is someone +/// on the way: what its keyboard's pane says (an Upgrade's outcome, +/// upgrade.zig `tellEveryView`) is that client's until it is back for its +/// view (Pardes.rejoinView: its join's dump has it) or the view's kept +/// time is up; no other view's input and no unattended clock take it. A +/// pair's one client is such a client; the session's own frontend is +/// none (its view is never away). A session no build could load starts +/// afresh with no view kept: a pair's is held attended for its client +/// instead (tui.zig `Own.start`). +fn awaited(p: *const Pardes, pane: *const Pane) bool { + if (p.views_away == 0) return false; + for (p.views, 0..) |slot, k| if (slot) |v| { + if (pardes.views.isAway(p, @intCast(k)) and p.panes[v.active] == pane and + p.clock.now_ns -| v.away_ns < pardes.views.away_kept_ns) return true; + }; + return false; +} + /// The key or click that used to clear the message row now starts each /// line's exit: it stays `message_linger_ms`, then goes. A line already /// on its way out keeps its own timing. pub fn dismissMessage(p: *Pardes, pane: *Pane) void { + if (awaited(p, pane)) return; if (pane.msg_len > 0 and dismissLine(p, &pane.msg_life)) { pane.msg_len = 0; pane.msg_life = .{}; diff --git a/core/Query.zig b/core/Query.zig index 228cdd0e..3023cc60 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -486,7 +486,12 @@ fn makeNameRows(p: *Pardes, id: usize) !void { var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; var pathbuf: [4096 + 32]u8 = undefined; switch (q.source) { - .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .find => { + // A name the worker quoted (look.quoted) opens as it is named. + var namebuf: [4096]u8 = undefined; + const name = if (row.len > 1 and row[0] == '"' and row[row.len - 1] == '"') look.unquoted(&namebuf, row[1 .. row.len - 1]) else row; + meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name }) catch row); + }, .recent => { const t = look.parsePathLine(row); meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); @@ -1030,7 +1035,8 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar const index = try File.lineIndex(p.gpa, f); const path = addressOf(p.scratch.allocator(), tp); var relbuf: [4096]u8 = undefined; - const rel = lookPath(&relbuf, path, dir); + var namebuf: [8192]u8 = undefined; + const rel = std.fmt.bufPrint(&namebuf, "{f}", .{look.quoted(lookPath(&relbuf, path, dir))}) catch lookPath(&relbuf, path, dir); const width = addressWidth(rel, index.len); var sh: Shades = .{}; defer sh.done(p); @@ -1194,10 +1200,11 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; + var namebuf: [8192]u8 = undefined; for (q.found.items[lo..hi], lo..) |fd, i| { const name = q.found_bytes.items[fd.path..][0..fd.path_len]; const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name }) catch continue; - const rel = lookPath(&relbuf, path, dir); + const rel = std.fmt.bufPrint(&namebuf, "{f}", .{look.quoted(lookPath(&relbuf, path, dir))}) catch lookPath(&relbuf, path, dir); if (!std.mem.eql(u8, name, last_path)) { last_path = name; try q.items.append(p.gpa, .{ .kind = .header }); @@ -1259,19 +1266,21 @@ pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void { const t = look.parsePathLine(ln); if (t.at.line == 0 or t.path.len == 0) continue; const code = if (t.end < ln.len) ln[t.end + 1 ..] else ""; - // A row is a line's text, a file's name in it unescaped (one - // named `a:5000000000:b` reads as `a` at line 5000000000): one - // whose numbers a Found cannot hold is passed over. + // The worker writes a name that needs it quoted (look.quoted: + // a newline in it was a row of its own); one whose numbers a + // Found cannot hold is passed over. + var namebuf: [4096]u8 = undefined; + const name = if (ln[0] == '"') look.unquoted(&namebuf, t.path) else t.path; const found: Found = .{ .path = std.math.cast(u32, q.found_bytes.items.len) orelse return, - .path_len = std.math.cast(u16, t.path.len) orelse continue, + .path_len = std.math.cast(u16, name.len) orelse continue, .line = std.math.cast(u32, t.at.line) orelse continue, .col = std.math.cast(u32, t.at.col -| 1) orelse continue, .end = std.math.cast(u32, if (t.at.end_col > 0) t.at.end_col else t.at.col) orelse continue, - .code = std.math.cast(u32, q.found_bytes.items.len + t.path.len) orelse return, + .code = std.math.cast(u32, q.found_bytes.items.len + name.len) orelse return, .code_len = std.math.cast(u32, code.len) orelse continue, }; - q.found_bytes.appendSlice(p.gpa, t.path) catch return; + q.found_bytes.appendSlice(p.gpa, name) catch return; q.found_bytes.appendSlice(p.gpa, code) catch return; q.found.append(p.gpa, found) catch return; }, @@ -1357,13 +1366,14 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; + var namebuf: [8192]u8 = undefined; for (sorted.items, 0..) |ln, li| { if (ln.len == 0) continue; if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; const t = look.parsePathLine(ln); if (t.at.line == 0) continue; const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; - const rel = lookPath(&relbuf, path, dir); + const rel = std.fmt.bufPrint(&namebuf, "{f}", .{look.quoted(lookPath(&relbuf, path, dir))}) catch lookPath(&relbuf, path, dir); if (!std.mem.eql(u8, t.path, last_path)) { last_path = t.path; try q.items.append(p.gpa, .{ .kind = .header }); diff --git a/core/Stream.zig b/core/Stream.zig index c231d413..2f700cb4 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -835,13 +835,13 @@ const Worker = struct { const ln = std.mem.trimEnd(u8, raw, " \t\r\n"); var cut = @min(ln.len, 400); while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; - try w.rows.print(w.gpa, "{s}:{d}:{d}{c}{d} {s}\n", .{ path, line, from + 1, config.range_sep, end, ln[0..cut] }); + try w.rows.print(w.gpa, "{f}:{d}:{d}{c}{d} {s}\n", .{ look.quoted(path), line, from + 1, config.range_sep, end, ln[0..cut] }); w.total += 1; } /// A listing's file: its name, relative to the base. fn file(w: *Worker, path: []const u8) !bool { - try w.rows.print(w.gpa, "{s}\n", .{path}); + try w.rows.print(w.gpa, "{f}\n", .{look.quoted(path)}); w.total += 1; try w.maybeSend(); return w.checkCap(); @@ -1278,6 +1278,53 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the try testing.expectEqual(State.done, p.stream.state); } +test "Stream: a file named `a\\nb:1:1` is one Grep row and one Find name, its own, for the walk and rg; a row is a line" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var root_buf: [4096]u8 = undefined; + // Up to 2026-11-23 its row, `a\nb:1:1:1:1-6 needle`, was two: `a` + // (no place) and a hit in a file `b`, line 1, that has none. + const odd = "a\nb:1:1"; + try tmp.dir.writeFile(testing.io, .{ .sub_path = odd, .data = "needle\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b", .data = "hay\n" }); + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + for ([_]Engine{ .walk, .rg }) |engine| { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("x\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ root, "main.txt" }); + p.advance(1); + p.stream.engine = engine; + // No host workers: the search runs on the loop at the next tick. + panes.Query.open(p, 0, .grep, "", false); + const qp = for (p.panes) |slot| { + if (slot) |qp| if (qp.query != null) break qp; + } else return error.NoQueryPane; + const q = qp.query.?; + try query(p, qp.serial, .grep, "needle", root, .now); + p.update(.tick); + p.update(.tick); + if (engine == .rg and p.stream.used != .rg) return; // no rg here + try testing.expectEqual(@as(usize, 1), q.found.items.len); + const fd = q.found.items[0]; + try testing.expectEqualStrings(odd, q.found_bytes.items[fd.path..][0..fd.path_len]); + try testing.expectEqual(@as(u32, 1), fd.line); + // The pane's rows: a line each, its name's newline written `\n`. + const f = &qp.file.?; + try testing.expectEqual(std.mem.count(u8, f.content, "\n"), f.location_rows.len); + try testing.expect(std.mem.indexOf(u8, f.content, "\"a\\nb:1:1\"") != null); + // Find: the same name, once, opening that file. + panes.Query.open(p, 0, .find, "", false); + p.update(.tick); + p.update(.tick); + const fq = for (p.panes) |slot| { + if (slot) |fp| if (fp.query) |got| if (got.source == .find) break got; + } else return error.NoFindPane; + try testing.expectEqual(@as(usize, 2), fq.names.cands.items.len); + } +} + test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" { if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); diff --git a/core/colors.zig b/core/colors.zig index 7e692fe5..5579ed05 100644 --- a/core/colors.zig +++ b/core/colors.zig @@ -687,6 +687,29 @@ fn revertThemeFile(p: *Pardes) void { p.emit(.{ .theme_file = .{ .generation = generation, .on = loaded.len > 0 } }); } +/// The deepest a theme file's brackets nest: its schema is three levels +/// deep, and std's ZON parser recurses a level a bracket with no bound of +/// its own (a file 5 000 deep overflowed a 16 MiB stack in a Debug build: +/// the session's end, at every start that loaded it). +const max_theme_nesting = 64; + +/// How deep `source`'s brackets nest, as std's tokenizer reads it (strings +/// and comments are tokens of their own). +fn nesting(source: [:0]const u8) usize { + var tokens: std.zig.Tokenizer = .init(source); + var depth: usize = 0; + var most: usize = 0; + while (true) switch (tokens.next().tag) { + .eof => return most, + .l_brace, .l_bracket, .l_paren => { + depth += 1; + most = @max(most, depth); + }, + .r_brace, .r_bracket, .r_paren => depth -|= 1, + else => {}, + }; +} + pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool { // ZON's generated field dispatch grows with the complete theme schema. @setEvalBranchQuota(10000); @@ -700,6 +723,10 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool { return false; }; defer p.gpa.free(source); + if (nesting(source) > max_theme_nesting) { + themeFileFailure(p, request, std.fmt.comptimePrint("nested past {d} levels", .{max_theme_nesting})); + return false; + } // The parse's results live in `arena`; the theme kept owns only its name. var arena: std.heap.ArenaAllocator = .init(p.gpa); defer arena.deinit(); @@ -931,6 +958,31 @@ test "a theme file that cannot be read is named in the failure" { try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "theme file /nowhere/mine.zon: ") != null); } +test "a theme file nested 10, 1 000 and 100 000 deep is refused in words, never a stack overflow" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .config_dir = "/tmp/pardes-config" }); + defer p.deinit(); + for ([_]usize{ 10, 1000, 100_000 }) |depth| { + requestThemeFile(p, 0, "themes/deep.zon"); + var source: std.ArrayList(u8) = .empty; + defer source.deinit(gpa); + try source.appendSlice(gpa, ".{ .name = \"deep\", .bg = "); + for (0..depth) |_| try source.appendSlice(gpa, ".{"); + try source.appendSlice(gpa, "1"); + for (0..depth) |_| try source.append(gpa, '}'); + try source.appendSlice(gpa, " }\n"); + p.panes[0].?.msg_len = 0; + // Up to 2026-11-23 std's parser took it: 5 000 deep overflowed the + // stack (a Debug build's 16 MiB). + try std.testing.expect(!loadThemeFile(p, p.theme_file_generation, source.items)); + const said = p.panes[0].?.msg[0..p.panes[0].?.msg_len]; + std.testing.expect(std.mem.indexOf(u8, said, "theme file /tmp/pardes-config/themes/deep.zon: ") != null) catch |err| { + std.debug.print("{d} deep: said {s}\n", .{ depth, said }); + return err; + }; + } +} + test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, diff --git a/core/diff.zig b/core/diff.zig index 659576d3..edf037fe 100644 --- a/core/diff.zig +++ b/core/diff.zig @@ -294,11 +294,14 @@ fn range(line: []const u8, at: *usize) ?[2]usize { return .{ start, 1 }; } +/// A header's number: a line of a file, or a count of them, so a u32 (no +/// file pardes opens has more lines); one past it makes the line no header, +/// where the walk's count would overflow (a crafted `+18446744073709551615`). fn number(line: []const u8, at: *usize) ?usize { const from = at.*; - var n: usize = 0; + var n: u32 = 0; while (at.* < line.len and std.ascii.isDigit(line[at.*])) : (at.* += 1) - n = std.math.add(usize, std.math.mul(usize, n, 10) catch return null, line[at.*] - '0') catch return null; + n = std.math.add(u32, std.math.mul(u32, n, 10) catch return null, line[at.*] - '0') catch return null; return if (at.* > from) n else null; } diff --git a/core/fuzz.zig b/core/fuzz.zig index 0fce6f9d..4f291d64 100644 --- a/core/fuzz.zig +++ b/core/fuzz.zig @@ -784,3 +784,101 @@ test "9P: a rows style past the syntax's kinds is refused, never drawn" { _ = try p.render(p.frame_arena.allocator()); } } + +// --------------------------------------------------------------------------- +// (v, vi) Numbers in a file's text and in another program's answer: a +// diff's hunk headers (a `.diff` drawn, the patch view, a look's target) +// and a language server's rows (each kind's answer landed, stepped, drawn; +// the same places typed to Look). + +const diff = @import("diff.zig"); +const hunks = @import("hunks.zig"); +const lsp = pardes.lsp; + +/// Around what an int of each width holds, and past it. +const numbers = [_][]const u8{ "0", "1", "2", "3", "5", "65535", "2147483647", "2147483648", "3000000000", "4294967295", "4294967296", "9223372036854775807", "9223372036854775808", "18446744073709551615", "18446744073709551616", "99999999999999999999999" }; + +fn draw(p: *Pardes) !void { + p.sync(); + _ = p.frame_arena.reset(.retain_capacity); + _ = try p.render(p.frame_arena.allocator()); +} + +fn diffSeed(gpa: std.mem.Allocator, seed: u64) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + try text.appendSlice(gpa, "diff --git a/x.zig b/x.zig\n--- a/x.zig\n+++ b/x.zig\n"); + for (0..1 + r.uintLessThan(usize, 3)) |_| { + try text.print(gpa, "@@ -{s}", .{pick(r, numbers)}); + if (chance(r, 0.7)) try text.print(gpa, ",{s}", .{pick(r, numbers)}); + try text.print(gpa, " +{s}", .{pick(r, numbers)}); + if (chance(r, 0.7)) try text.print(gpa, ",{s}", .{pick(r, numbers)}); + try text.appendSlice(gpa, " @@ fn x()\n"); + const lines = [_][]const u8{ " const a = 1;\n", "-const b = 2;\n", "+const b = 3;\n", "\\ No newline at end of file\n", "\n", "--- y\n", "+++ y\n", "text\n" }; + for (0..r.uintLessThan(usize, 9)) |_| try text.appendSlice(gpa, pick(r, lines)); + } + // A `.diff` drawn. + const p = try th.withFile(gpa, text.items); + defer p.deinit(); + const pane = p.panes[p.view().active].?; + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, "/change.diff"); + pane.file.?.syntax_dirty = true; + try draw(p); + // The patch view. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ctx: hunks.Ctx = .{ .arena = arena.allocator() }; + _ = hunks.format(&ctx, "", text.items) catch {}; + // A look's target, at every row. + var rows: std.ArrayList([]const u8) = .empty; + defer rows.deinit(gpa); + var it = std.mem.splitScalar(u8, text.items, '\n'); + while (it.next()) |row| try rows.append(gpa, row); + for (0..rows.items.len) |row| _ = diff.targetAt(rows.items, row, false); +} + +test "a diff's hunk headers with numbers past any file's: drawn, formatted and looked at, never a panic" { + for (seeds) |seed| for (0..4) |k| try diffSeed(testing.allocator, seed *% 31 +% k); +} + +fn lspSeed(gpa: std.mem.Allocator, seed: u64) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + const p = try th.withFile(gpa, "alpha one\n\tbeta\n\t\tgamma \xe6\x97\xa5\n\n"); + defer p.deinit(); + var rows: std.ArrayList(u8) = .empty; + defer rows.deinit(gpa); + for (0..1 + r.uintLessThan(usize, 4)) |_| { + // As lsp.sourceSpanRow writes them; the file's own name. + try rows.print(gpa, "/test.txt:{s}:{s}", .{ pick(r, numbers), pick(r, numbers) }); + if (chance(r, 0.5)) try rows.print(gpa, "-{s}", .{pick(r, numbers)}); + try rows.appendSlice(gpa, " alpha\n"); + } + const kinds = [_]lsp.Kind{ .definition, .declaration, .implementation, .references, .diagnostics, .document_symbols, .workspace_symbols }; + const kind = pick(r, kinds); + if (lsp.supports.contains(kind)) { + p.lspRequest(0, kind, ""); + while (p.nextEffect()) |_| {} + if (p.lsp_ask.wait) |wait| p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = rows.items } }); + try draw(p); + for ("nNjk\r") |key| { + p.update(.{ .key = .{ .cp = if (key == '\r') pardes.Key.enter else key } }); + try draw(p); + } + } + // The same places typed. + var look: [96]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}:{s}", .{ pick(r, numbers), pick(r, numbers) }) }); + try draw(p); + p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}:{s}-{s}:{s}", .{ pick(r, numbers), pick(r, numbers), pick(r, numbers), pick(r, numbers) }) }); + try draw(p); + p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}-{s}", .{ pick(r, numbers), pick(r, numbers) }) }); + try draw(p); +} + +test "a language server's rows and a typed Look with numbers past any file's: landed, stepped and drawn, never a panic" { + for (seeds) |seed| for (0..4) |k| try lspSeed(testing.allocator, seed *% 31 +% k); +} diff --git a/core/hunks.zig b/core/hunks.zig index 8f56f8f1..fdc040da 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -15,6 +15,7 @@ const std = @import("std"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); const locations = @import("locations.zig"); +const look = @import("look.zig"); const pardes = @import("root.zig"); const Pardes = pardes.Pardes; @@ -385,7 +386,7 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, scratch: *[ var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { if (row == declaration.start_line and ctx.tslocations) { - const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); + const label = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(shown), row + 1 }); try out.row(arena, label, .{ .kind = .declaration, .path = shown, .line = row + 1, .location_end = label.len, .code_start = label.len }); } // A blank where a hunk line has its marker: the code aligns. @@ -396,7 +397,8 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, scratch: *[ // The hunk's label: a step for n and N, and a look's place. const line_no = change_row + 1; var label: std.Io.Writer.Allocating = .init(arena); - try label.writer.print("{s}:{d}", .{ shown, line_no }); + // The name as a row writes it (look.quoted): a `:` in it never splits it. + try label.writer.print("{f}:{d}", .{ look.quoted(shown), line_no }); const location_end = label.written().len; if (depth > 0) { try label.writer.writeByte(' '); diff --git a/core/look.zig b/core/look.zig index b240b6e2..72bb42eb 100644 --- a/core/look.zig +++ b/core/look.zig @@ -67,13 +67,89 @@ fn num(tok: []const u8, i: usize) struct { v: usize, end: usize } { return .{ .v = v, .end = j }; } +/// A file's name in a row (a Grep's, Find's, a query pane's, the patch +/// view's), written as git writes an unusual one (quote_c_style): one with +/// a control byte, a `"`, a `\` or a `:` in double quotes, `\n \t \r \" \\` +/// and `\ooo` for any other control byte, so that a row is one line and its +/// name never splits at a `:`. Any other name as it is. +pub fn quoted(name: []const u8) Quoted { + return .{ .name = name }; +} + +pub const Quoted = struct { + name: []const u8, + + pub fn format(q: Quoted, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (q.name) |c| { + if (c < 0x20 or c == 0x7f or c == '"' or c == '\\' or c == config.line_col_sep) break; + } else return w.writeAll(q.name); + try w.writeByte('"'); + for (q.name) |c| switch (c) { + '\n' => try w.writeAll("\\n"), + '\t' => try w.writeAll("\\t"), + '\r' => try w.writeAll("\\r"), + '"', '\\' => try w.print("\\{c}", .{c}), + 0...0x08, 0x0b, 0x0c, 0x0e...0x1f, 0x7f => try w.print("\\{o:0>3}", .{c}), + else => try w.writeByte(c), + }; + try w.writeByte('"'); + } +}; + +/// A quoted name's inside (parsePathLine's path of a `"`-led word) read +/// back into `buf` (escapes only shrink it: `buf` as long as `inside` is +/// enough). +pub fn unquoted(buf: []u8, inside: []const u8) []const u8 { + var n: usize = 0; + var i: usize = 0; + while (i < inside.len and n < buf.len) : (n += 1) { + const c = inside[i]; + i += 1; + buf[n] = c; + if (c != '\\' or i == inside.len) continue; + const e = inside[i]; + i += 1; + buf[n] = switch (e) { + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + 'a' => 0x07, + 'b' => 0x08, + 'v' => 0x0b, + 'f' => 0x0c, + else => e, + }; + // `\ooo`: three octal digits. + if (i + 2 <= inside.len) if (std.fmt.parseInt(u8, inside[i - 1 .. i + 2], 8)) |v| { + buf[n] = v; + i += 2; + } else |_| {}; + } + return buf[0..n]; +} + +/// Where a `"`-led word's quoted name closes (`quoted`'s), past its +/// escapes; null when it is no quoted name. +fn quoteEnd(tok: []const u8) ?usize { + if (tok.len < 2 or tok[0] != '"') return null; + var i: usize = 1; + while (i < tok.len) : (i += 1) switch (tok[i]) { + '\\' => i += 1, + '"' => return i, + else => {}, + }; + return null; +} + pub fn parsePathLine(tok: []const u8) struct { path: []const u8, at: Spot, end: usize } { - var sep: usize = 0; + // A quoted name (a row's: `quoted`) is the path whole, its `:` its own. + const close = quoteEnd(tok); + var sep: usize = if (close) |c| c + 1 else 0; while (sep < tok.len) : (sep += 1) { if (tok[sep] != config.line_col_sep) continue; const l = num(tok, sep + 1); if (l.end == sep + 1) continue; // no digits after ':' - const path = tok[0..sep]; + const path = if (close) |c| tok[1..c] else tok[0..sep]; var i = l.end; if (i < tok.len and tok[i] == config.range_sep) { const e = num(tok, i + 1); @@ -753,20 +829,29 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at_in: Spot, landing: enum { center, } } } - pane.body.cur_row = @intCast(at.line - 1); - pane.body.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0; + pane.body.cur_row = std.math.cast(i32, at.line - 1) orelse return; + pane.body.cur_col = columnOn(pane, pane.body.cur_row, at.col); pane.body.cur_pinned = true; if (at.end_line != 0) return selectSpan(p, pane, at); pane.ensureCursorVisible(p.settings.tab); } +/// A place's column (from 1) as a cursor's on `row`: past the line's end (a +/// server's answer, a typed number: any) it is the end, as a search's +/// landing and clampCursor have it. A terminal's (a jump's) as it was. +fn columnOn(pane: *const Pane, row: i32, col: usize) i32 { + if (pane.file == null) return std.math.lossyCast(i32, col -| 1); + return @intCast(@min(col -| 1, panes.File.sourceLine(pane, row).len)); +} + fn selectSpan(p: *Pardes, pane: *Pane, at: Spot) void { const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(.at(p.view().active), "look", err); // saturating, not `- 1`: `f.zig:0-5` is a legal thing to type and a // 1-based zero is the same nothing an absent number is - const acol: i32 = @intCast(at.col -| 1); - const ecol: i32 = if (at.end_col > 0) @intCast(at.end_col - 1) else std.math.maxInt(i32); - const r = panes.Text.cellRange(text, @intCast(at.line -| 1), acol, @intCast(at.end_line -| 1), ecol); + // Any number a place has: cellRange clamps each to the text. + const acol = std.math.lossyCast(i32, at.col -| 1); + const ecol: i32 = if (at.end_col > 0) std.math.lossyCast(i32, at.end_col - 1) else std.math.maxInt(i32); + const r = panes.Text.cellRange(text, std.math.lossyCast(i32, at.line -| 1), acol, std.math.lossyCast(i32, at.end_line -| 1), ecol); pane.body.setRange(p.settings.tab, text, 0, r, true); } @@ -1605,7 +1690,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const free = p.freeSlot() orelse return p.reportError(.at(id), "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); - if (target.at.col > 0) nt.body.cur_col = @intCast(target.at.col - 1); + nt.body.cur_col = columnOn(nt, nt.body.cur_row, target.at.col); const failures = p.fs.failures; layout.placeNew(p, id, id, free, .doc); // Refused a place: that is the look's one failure, not a @@ -2025,6 +2110,39 @@ test "Look copies its operand before releasing pointer selection storage" { try std.testing.expectEqual(.none, p.view().drag); } +test "a Look whose column is past its line's end lands at the end, however big; a line past the file's is a miss" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha\n\tbeta\n"); + // Up to 2026-11-23 a column past i32 panicked the session (`@intCast` + // in focusPaneLine): any text a B3 or Look takes, a server's row. + for ([_][]const u8{ "/test.txt:2:9", "/test.txt:2:3000000000", "/test.txt:2:18446744073709551615" }) |place| { + lookAt(p, 0, place); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 5), pane.body.cur_col); + } + // A span past the text: selected to its end. + lookAt(p, 0, "/test.txt:1:2-3000000000:3000000000"); + try std.testing.expect(pane.body.vsel.active); + pane.body.cur_row = 0; + lookAt(p, 0, "/test.txt:3000000000:1"); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); +} + +test "a file's name written as a row writes it reads back whole: a newline, a `:5:`, a quote, a control byte; a plain name as it is" { + var row: [256]u8 = undefined; + var back: [256]u8 = undefined; + for ([_][]const u8{ "a\nb:1:1", "a:5:b.txt", "say \"hi\".txt", "bell\x07\x1b[31m", "back\\slash", "plain/name.zig" }) |name| { + const written = try std.fmt.bufPrint(&row, "{f}:12:3-5 code", .{quoted(name)}); + try std.testing.expect(std.mem.indexOfScalar(u8, written, '\n') == null); + const got = parsePathLine(written); + try std.testing.expectEqual(@as(usize, 12), got.at.line); + try std.testing.expectEqual(@as(usize, 3), got.at.col); + try std.testing.expectEqualStrings(name, if (written[0] == '"') unquoted(&back, got.path) else got.path); + } + try std.testing.expectEqualStrings("plain/name.zig:1", try std.fmt.bufPrint(&row, "{f}:1", .{quoted("plain/name.zig")})); +} + test "@p names a pane by its serial, as /index does" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); diff --git a/core/replica.zig b/core/replica.zig index 72662df6..829972c2 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3726,6 +3726,11 @@ fn endJoin(j: *Joined, have: ?*Have) void { /// as `Peers.join` sends it: its state, its blobs put back where they go. fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { const gpa = std.testing.allocator; + // What was recorded goes first, as a join sends it (Peers.dumped): + // left on the tape, the joiner's first unit replayed it over the dump + // it loaded (a session's `init` first: a core made afresh). + a.seq += 1; + _ = try a.unit(0, a.seq); const was = Stepping.begin(&a.t, null); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer blobs.deinit(a.core.gpa); @@ -3794,6 +3799,33 @@ fn shows(p: *Pardes, text: []const u8) !bool { return false; } +test "a client joined from a dump keeps the session's jump list through a step: two entries the same but for their place's undefined bytes are one entry on both" { + // The release soak's parting (the witness: `views[3].jumps`): a text's + // entry has `.place = .{}`, bytes undefined: a session's are its + // stack's (here 0x11 and 0x22, the two a release build left), a + // client's what its load left; the step drops the gone entry between + // the two and makes them one where they compare the same. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + const v = a.core.view(); + const serial = a.core.panes[v.active].?.serial; + var at: pardes.Jump.Loc = .{ .pane = @intCast(v.active), .serial = serial, .line = 1, .col = 1 }; + var again = at; + @memset(&at.place.bytes, 0x11); + @memset(&again.place.bytes, 0x22); + v.jumps.list[0] = at; + v.jumps.list[1] = .{ .pane = 5, .serial = 999, .line = 1, .col = 1 }; + v.jumps.list[2] = again; + v.jumps.list[3] = .{ .pane = @intCast(v.active), .serial = serial, .line = 150, .col = 1 }; + v.jumps.n, v.jumps.cur = .{ 4, 3 }; + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); + try agrees(a, r); + try std.testing.expectEqual(@as(usize, 2), r.core().view().jumps.n); +} + test "a message past the wire's bound is named, never read as the link's end" { var fds: [2]c_int = undefined; try std.testing.expectEqual(0, libc.pipe(&fds)); diff --git a/core/walk.zig b/core/walk.zig index 02e46454..91400bc1 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -89,6 +89,45 @@ pub fn digest(comptime T: type, v: *const T) u64 { return h.final(); } +/// Equal as the digest sees them, by the digest's rules: what the walk +/// leaves out (a field `replica` names, a Buf's bytes past its length) is +/// not compared; a type that walks itself, by its digest. std.meta.eql +/// compares every byte of an array, and those bytes are undefined: 0xAA on +/// every Debug process, each release process's own garbage; a decision of +/// the core taken on them agrees between a session and its clients in +/// Debug alone. +pub fn eql(comptime T: type, a: *const T, b: *const T) bool { + switch (@typeInfo(T)) { + .void => return true, + .bool, .int, .@"enum" => return a.* == b.*, + .optional => |o| return if (a.*) |*x| (if (b.*) |*y| eql(o.child, x, y) else false) else b.* == null, + .array => |arr| { + if (comptime flatHash(arr.child)) return std.mem.eql(arr.child, a, b); + for (a, b) |*x, *y| if (!eql(arr.child, x, y)) return false; + return true; + }, + .@"struct" => |s| { + if (comptime machinery(T)) return true; + if (comptime s.layout == .@"packed" or @hasDecl(T, "digest") or isList(T) or isAtomic(T) or isBitset(T) or @hasField(T, "any_future")) return digest(T, a) == digest(T, b); + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or comptime excluded(T, name)) continue; + if (comptime lengthOf(T, name)) |len| { + const x = @field(a, name)[0..lengthIn(a, len)]; + const y = @field(b, name)[0..lengthIn(b, len)]; + if (comptime flatHash(Element(F))) { + if (!std.mem.eql(Element(F), x, y)) return false; + } else { + if (x.len != y.len) return false; + for (x, y) |*p, *q| if (!eql(Element(F), p, q)) return false; + } + } else if (!eql(F, &@field(a, name), &@field(b, name))) return false; + } + return true; + }, + else => return digest(T, a) == digest(T, b), + } +} + /// A digest of each field `hash` would walk, in order (what a divergence /// is narrowed down by); `names` are theirs. pub fn fieldDigests(comptime T: type, v: *const T, out: []u64) []u64 { diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 9320e522..f0011273 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -119,6 +119,9 @@ const Msg = union(enum) { paste: []const u8, paste_start, paste_end, + /// A sequence past max_sequence was dropped (a clipboard's answer past + /// the paste limit): said on the notice line. + reply_dropped, fs_ready, /// A replica's reader posted: the step boundary takes it in. replica_mail, @@ -154,23 +157,61 @@ fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { loop.postEvent(.quit) catch {}; } +/// The longest sequence the terminal's input carries whole: a clipboard +/// read's answer (OSC 52) of the paste limit's text, in base64, with its +/// framing. One longer is dropped and said (`reply_dropped`). +const max_sequence: usize = std.base64.standard.Encoder.calcSize(max_paste_bytes) + 16; + +/// A string sequence's start (OSC, DCS, APC, PM, SOS): it ends at a BEL or +/// an ESC, however long it is. +fn isString(head: []const u8) bool { + return head[0] == 0x1b and std.mem.indexOfScalar(u8, "]P_^X", head[1]) != null; +} + fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { try loop.postEvent(.{ .winsize = try tty.getWinsize() }); var parser: vaxis.Parser = .{}; - var buf: [1024]u8 = undefined; + // Grown while one sequence is longer (a clipboard's answer: megabytes), + // up to max_sequence, and back to its first size after. + const gpa = vx.opts.system_clipboard_allocator orelse std.heap.c_allocator; + var buf = try gpa.alloc(u8, 1024); + defer gpa.free(buf); var carried: usize = 0; + // The sequence carried is past max_sequence, and said so. + var dropping = false; while (true) { // stopInput cancels the task; the read then fails with Canceled - if (carried == buf.len) return error.InputSequenceTooLong; + if (carried == buf.len and buf.len < max_sequence) { + if (gpa.realloc(buf, @min(2 * buf.len, max_sequence))) |grown| buf = grown else |_| {} + } + if (carried == buf.len) { + // Dropped, and said once. A string keeps its introducer and a + // byte after it that makes it no reply vaxis knows, so the parse + // still finds its end and passes it over; anything else (a CSI + // of megabytes) is let go where it stands. + if (!dropping) try loop.postEvent(.reply_dropped); + dropping = true; + carried = if (isString(buf)) 3 else 0; + buf[2] = 'x'; + } const received = try tty.read(buf[carried..]); if (received == 0) return; // The terminal's answers to frames (FrameAck) come out first, // wherever they sit: never events, and never glued to a key (an - // Escape pressed just before one would read as Alt on it). - const end = feed.ack.take(buf[0 .. carried + received], loop); + // Escape pressed just before one would read as Alt on it). What + // was carried is clear of them but for one cut across the read. + const from = carried -| (FrameAck.answer.len - 1); + const end = from + feed.ack.take(buf[from .. carried + received], loop); if (end == 0) { carried = 0; continue; } + // A string still arriving (a clipboard's answer in a pty's 4 KiB + // reads) has no end till a BEL or an ESC comes: it is read on, not + // parsed again from its start at every read. + if (carried > 2 and isString(buf) and std.mem.indexOfAny(u8, buf[carried - 1 .. end], "\x07\x1b") == null) { + carried = end; + continue; + } if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { feed.shm_probing.store(false, .release); feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); @@ -217,7 +258,7 @@ fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue; if (result.event) |event| vaxis.loop.handleEventGeneric(loop, vx, &feed.cache, Msg, event, vx.opts.system_clipboard_allocator) catch |err| { - if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); + if (event == .paste) if (vx.opts.system_clipboard_allocator) |clip| clip.free(@constCast(event.paste)); return err; }; // The last answer to the startup queries is no event of its @@ -229,7 +270,13 @@ fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { }; } carried = end - consumed; - std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); + if (consumed > 0) { + std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); + dropping = false; + } + if (buf.len > 1024 and carried <= 1024) if (gpa.realloc(buf, 1024)) |first| { + buf = first; + } else |_| {}; } } @@ -333,10 +380,13 @@ const TestInput = struct { }; /// A terminal that hands over `parts`, a read each (an empty one passed -/// over), and says more follows (within `gap_ms`) while some are left. +/// over; one longer than the reader's room in reads of that room, as a tty +/// does), and says more follows (within `gap_ms`) while some are left. const TestReader = struct { parts: []const []const u8, next: usize = 0, + /// How much of `parts[next]` was read. + at: usize = 0, gap_ms: u32 = 0, asked: bool = false, @@ -351,11 +401,15 @@ const TestReader = struct { fn read(r: *TestReader, buf: []u8) !usize { while (r.next < r.parts.len) { - const part = r.parts[r.next]; - r.next += 1; - if (part.len == 0) continue; - @memcpy(buf[0..part.len], part); - return part.len; + const part = r.parts[r.next][r.at..]; + const n = @min(part.len, buf.len); + @memcpy(buf[0..n], part[0..n]); + r.at += n; + if (n == part.len) { + r.next += 1; + r.at = 0; + } + if (n > 0) return n; } return 0; } @@ -1556,7 +1610,7 @@ const Shell = struct { if (!s.peers.recording) return false; switch (ev) { .key_press => if (s.in_paste) return false, - .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {}, + .mouse, .paste, .paste_end, .reply_dropped, .winsize, .focus_in, .focus_out => {}, else => return false, } if (s.took_output or s.took_input) { @@ -1583,14 +1637,14 @@ const Shell = struct { s.frames.input(pardes.FrameStats.nowNs()); s.input_seen = true; }, - .paste, .paste_start, .winsize => s.input_seen = true, + .paste, .paste_start, .reply_dropped, .winsize => s.input_seen = true, else => {}, } if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); if (event != .replica_mail) s.mail_only = false; // The terminal's input goes into its view. switch (event) { - .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { + .key_press, .mouse, .paste, .paste_start, .paste_end, .reply_dropped, .winsize, .focus_in, .focus_out, .quit => { if (s.local() and s.client == null) core.toView(.at(s.own)); }, else => {}, @@ -1659,7 +1713,8 @@ const Shell = struct { .winsize => |ws| if (!s.detached()) s.resized(s.screen, ws), .key_press => |key| if (s.in_paste) { const bytes = vaxis_input.pasteBytes(key); - const room = max_paste_bytes -| s.paste_buf.written().len; + // A byte past the limit kept: the core cuts there and says so. + const room = max_paste_bytes + 1 -| s.paste_buf.written().len; s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; } else s.feed(vaxis_input.keyEvent(key)), .mouse => |m| if (mouseEvent(m)) |ev| s.feed(ev), @@ -1677,6 +1732,7 @@ const Shell = struct { if (pasted.len > 0) s.feed(.{ .paste = pasted }); s.paste_buf.clearRetainingCapacity(); }, + .reply_dropped => if (s.client) |c| c.link.notify("{s}", .{reply_dropped_words}) else core.setMessage(.at(core.view().active), reply_dropped_words), .fs_ready => {}, } return false; @@ -2098,6 +2154,7 @@ fn wakeFs(ctx: ?*anyopaque) void { } const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; +const reply_dropped_words = std.fmt.comptimePrint("a terminal reply past {d} KiB dropped: a clipboard past {d} KiB is not pasted", .{ max_sequence / 1024, max_paste_bytes / 1024 }); fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { const button: pardes.Mouse.Button = switch (m.button) { @@ -2365,6 +2422,155 @@ test "terminal replies and malformed sequences never become typed text" { try std.testing.expect(alt_up and clicked); } +/// The terminal's answer to a clipboard read (OSC 52) of `text`, between a +/// typed `x` and `y`, ended by `end` (BEL or ST). +fn testClipboardReply(gpa: std.mem.Allocator, text: []const u8, end: []const u8) ![]u8 { + const enc = std.base64.standard.Encoder; + const head = "x\x1b]52;c;"; + const reply = try gpa.alloc(u8, head.len + enc.calcSize(text.len) + end.len + 1); + @memcpy(reply[0..head.len], head); + const b64 = enc.encode(reply[head.len..], text); + @memcpy(reply[head.len + b64.len ..][0..end.len], end); + reply[reply.len - 1] = 'y'; + return reply; +} + +/// The loop's events after a `testClipboardReply`, one word each. +fn testReplyEvents(gpa: std.mem.Allocator, loop: *Loop, text: []const u8) ![]u8 { + var got: std.ArrayList(u8) = .empty; + errdefer got.deinit(gpa); + while (try loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |key| try got.print(gpa, "{u} ", .{key.codepoint}), + .paste => |bytes| { + defer gpa.free(@constCast(bytes)); + try got.appendSlice(gpa, if (std.mem.eql(u8, bytes, text)) "clipboard " else "other "); + }, + else => |other| try got.print(gpa, "{t} ", .{other}), + }; + return got.toOwnedSlice(gpa); +} + +test "a clipboard reply of 4 KB or 1 MB is taken, whole, in a pty's reads and cut inside its end, and input goes on after it" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // 3 KiB and 768 KiB of clipboard: a 4 KiB and a 1 MiB reply. Up to + // 2026-11-23 a reply over 1 KiB of unread input ended it, and the + // session quit (InputSequenceTooLong). + for ([_]usize{ 3 << 10, 768 << 10 }) |len| { + const text = try gpa.alloc(u8, len); + defer gpa.free(text); + for (text, 0..) |*b, i| b.* = @truncate(i *% 131 +% i / 7); + for ([_][]const u8{ "\x07", "\x1b\\" }) |end| { + const reply = try testClipboardReply(gpa, text, end); + defer gpa.free(reply); + // A pty's reads: 4 KiB at most. + const pieces = try gpa.alloc([]const u8, (reply.len + 4095) / 4096); + defer gpa.free(pieces); + for (pieces, 0..) |*piece, i| piece.* = reply[i * 4096 .. @min(reply.len, (i + 1) * 4096)]; + // Cut just before the end's last byte (inside an ST). + const cut = reply.len - 2; + const ways = [_][]const []const u8{ &.{reply}, pieces, &.{ reply[0..cut], reply[cut..] } }; + for (ways, 0..) |parts, way| { + var reader: TestReader = .{ .parts = parts }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + const got = try testReplyEvents(gpa, &t.loop, text); + defer gpa.free(got); + std.testing.expectEqualStrings("x clipboard y ", got) catch |err| { + std.debug.print("clipboard of {d} bytes, end {f}, way {d}\n", .{ len, std.ascii.hexEscape(end, .lower), way }); + return err; + }; + } + } + } +} + +test "a clipboard reply past the cap is dropped and said once, and the input after it, another reply, is taken; a DCS and a kitty graphics answer the same" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + const big = try gpa.alloc(u8, max_paste_bytes + 12); + defer gpa.free(big); + @memset(big, 'b'); + for ([_][]const u8{ "\x07", "\x1b\\" }) |end| { + const too_long = try testClipboardReply(gpa, big, end); + defer gpa.free(too_long); + try std.testing.expect(too_long.len > max_sequence); + const reply = try testClipboardReply(gpa, "clip", end); + defer gpa.free(reply); + // In a pty's 4 KiB reads, the reply after them. + const pieces = try gpa.alloc([]const u8, (too_long.len + 4095) / 4096 + 1); + defer gpa.free(pieces); + for (pieces[0 .. pieces.len - 1], 0..) |*piece, i| piece.* = too_long[i * 4096 .. @min(too_long.len, (i + 1) * 4096)]; + pieces[pieces.len - 1] = reply; + const cut = too_long.len - 2; + const ways = [_][]const []const u8{ &.{ too_long, reply }, pieces, &.{ too_long[0..cut], too_long[cut..], reply } }; + for (ways, 0..) |parts, way| { + var reader: TestReader = .{ .parts = parts }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + const got = try testReplyEvents(gpa, &t.loop, "clip"); + defer gpa.free(got); + std.testing.expectEqualStrings("x reply_dropped y x clipboard y ", got) catch |err| { + std.debug.print("end {f}, way {d}\n", .{ std.ascii.hexEscape(end, .lower), way }); + return err; + }; + } + } + // A DCS and a kitty graphics answer (APC): 4 KiB taken (no event of + // pardes's), one past the cap dropped and said. + for ([_][]const u8{ "\x1bP", "\x1b_G" }) |intro| for ([_]usize{ 4096, max_sequence }) |len| { + const long = try gpa.alloc(u8, 1 + intro.len + len + 3); + defer gpa.free(long); + long[0] = 'x'; + @memcpy(long[1..][0..intro.len], intro); + @memset(long[1 + intro.len .. long.len - 3], 'a'); + @memcpy(long[long.len - 3 ..], "\x1b\\y"); + var reader: TestReader = .{ .parts = &.{long} }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + const got = try testReplyEvents(gpa, &t.loop, ""); + defer gpa.free(got); + try std.testing.expectEqualStrings(if (len == max_sequence) "x reply_dropped y " else "x y ", got); + }; +} + +test "a bracketed paste past the paste limit is cut and said, and a reply dropped is said, on the notice line" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile(""); + pane.body.mode = .insert; + var no_peers: replica.Peers = .{}; + var paste_buf: std.Io.Writer.Allocating = .init(gpa); + defer paste_buf.deinit(); + var shell: Shell = .{ + .io = std.testing.io, + .gpa = gpa, + .lsp_gpa = gpa, + .core = core, + .frames = core.frames, + .loop = undefined, + .frame = undefined, + .paste_buf = &paste_buf, + .watches = undefined, + .peers = &no_peers, + .ptys = undefined, + }; + const big = try gpa.alloc(u8, max_paste_bytes); + defer gpa.free(big); + @memset(big, 'x'); + // Up to 2026-11-23 the tty kept the limit's bytes and no more, so the + // core never saw the paste was longer: cut, and nothing said. + const paste = [_]Msg{ .paste_start, .{ .key_press = .{ .codepoint = 'x', .text = big } }, .{ .key_press = .{ .codepoint = 'y', .text = "y" } }, .paste_end }; + for (paste) |ev| _ = shell.apply(ev); + try std.testing.expectEqual(max_paste_bytes, pane.file.?.content.len); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "paste cut") != null); + _ = shell.apply(.reply_dropped); + try std.testing.expectEqualStrings(reply_dropped_words, pane.msg[0..pane.msg_len]); +} + test "terminal input split at every byte with a gap reads as it does whole" { const gpa = std.testing.allocator; var t: TestInput = undefined; diff --git a/runtime/main.zig b/runtime/main.zig index 8558e25f..7c2998f5 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -52,6 +52,9 @@ pub const debug = struct { pardes.replica.dying(); @import("vaxis").recover(); } + // A fault in C code (an addon's library, MuPDF, tree-sitter) leaves + // a record as a panic does. + @import("runtime").crash.record(name); return std.debug.defaultHandleSegfault(addr, name, opt_ctx); } }; diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig index b385556c..12163743 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -452,7 +452,7 @@ pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Op // keep its blocks for as long as this session runs. if (rec.old >= 0) _ = libc.close(rec.old); rec.old = -1; - p.setMessage(.at(p.view().active), if (rec.refused.len > 0) + tellEveryView(p, if (rec.refused.len > 0) std.fmt.bufPrint(&buf, "Upgrade: the new build could not load this session ({s}); it goes on as {s}", .{ rec.refused[0..@min(rec.refused.len, 200)], version_line }) catch "Upgrade: the new build could not load this session; it goes on as before" else "Upgrade: now " ++ version_line); @@ -479,6 +479,106 @@ pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Op } } +/// An Upgrade is the session's news, not the asking view's: said in every +/// view at the pane its keyboard is on (each client reads it on its own +/// screen), a pane two views are on once; the live view is only the one +/// whose input came last before the dump. +fn tellEveryView(p: *pardes.Pardes, text: []const u8) void { + var told: [pardes.MAX_PANES]bool = @splat(false); + for (p.views) |v| if (v) |view| if (!told[view.active]) { + told[view.active] = true; + p.setMessage(.at(view.active), text); + }; +} + +test "an upgrade's outcome is said in every view, at the pane its keyboard is on, whichever view's input came last" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("before the upgrade\n"); + const asked = p.view().active; + // A second client's view, its keyboard on a pane of its own, the input + // that came last its own (as a client's keys before an Upgrade over 9P). + const k = p.openView() orelse return error.NoView; + p.toView(k); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "New")); + try std.testing.expect(p.view().active != asked); + const q = try upgradedForTest(gpa, p); + defer q.deinit(); + var seen: usize = 0; + for (q.views, 0..) |v, i| if (v != null) { + try std.testing.expect(saysOutcome(q, i)); + seen += 1; + }; + try std.testing.expectEqual(@as(usize, 2), seen); + try std.testing.expect(q.views[0].?.active != q.views[k.index()].?.active); +} + +test "an upgrade's outcome waits in each view kept for its client until that client is back for it: no other view's key and no clock take it" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("before the upgrade\n"); + // Two clients' views, each its keyboard on a pane of its own, kept for + // their clients as an Upgrade keeps them (Peers.refuseAll: away). + var kept: [2]pardes.Pardes.View.Id = undefined; + for (&kept) |*k| { + k.* = p.openView() orelse return error.NoView; + p.toView(k.*); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "New")); + } + p.toView(.at(0)); + for (kept) |k| p.awayView(k); + const q = try upgradedForTest(gpa, p); + defer q.deinit(); + // As the daemon's tests run (MessageLinger 0): a dismissal is at once. + q.settings.message_linger_ms = 0; + const key: pardes.Event = .{ .key = .{ .cp = 'j', .text = "j" } }; + // A key in the session's own view: its outcome goes, not theirs. + q.update(key); + try std.testing.expect(!saysOutcome(q, q.live)); + for (kept) |k| try std.testing.expect(saysOutcome(q, k.index())); + // Nobody attached: the clock takes nothing a kept view waits for. + q.unattended = true; + q.update(.tick); + for (kept) |k| try std.testing.expect(saysOutcome(q, k.index())); + q.unattended = false; + // A client back for its view has it (its join's dump); the next key, + // anyone's, takes it. + try std.testing.expect(q.rejoinView(kept[0])); + try std.testing.expect(saysOutcome(q, kept[0].index())); + q.update(key); + try std.testing.expect(!saysOutcome(q, kept[0].index())); + try std.testing.expect(saysOutcome(q, kept[1].index())); + // One never back: once its view's kept time is up, as anyone's. + q.advance(q.views[kept[1].index()].?.away_ns + pardes.views.away_kept_ns); + q.update(key); + try std.testing.expect(!saysOutcome(q, kept[1].index())); +} + +/// Whether view `k`'s keyboard pane says the Upgrade's outcome. +fn saysOutcome(q: *const pardes.Pardes, k: usize) bool { + const pane = q.panes[q.views[k].?.active].?; + return std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "Upgrade: now pardes "); +} + +/// `p` dumped and loaded as an Upgrade's new process loads it (`load`). +fn upgradedForTest(gpa: std.mem.Allocator, p: *pardes.Pardes) !*pardes.Pardes { + const bytes = try pardes.dump.byteDump(p); + defer gpa.free(bytes); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-upgrade-1.dump", .data = bytes }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var text_buf: [4300]u8 = undefined; + var rec = try Record.decode(try std.fmt.bufPrint(&text_buf, "link -1\nstub -1\nold -1\nwindow 0\nexe /x/pardes\ndump {s}/pardes-upgrade-1.dump\n", .{dir})); + const q = try load(gpa, gpa, .{ .tty_only = true }, &rec); + errdefer q.deinit(); + try std.testing.expect(!rec.fresh); + return q; +} + test "an upgrade's record reads back as it was written, and refuses one cut short" { var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .size = "1402x1488", .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1", .state = .kept }; rec.addPty(3, 1234, 11); diff --git a/test/behaviour/addons.zig b/test/behaviour/addons.zig index abadd781..8b54de02 100644 --- a/test/behaviour/addons.zig +++ b/test/behaviour/addons.zig @@ -37,7 +37,7 @@ test "addons: Addon load takes a library in, /addons lists it with the kinds com defer unload(&s, "fake"); // `<kind> <version> <abi> <panes open> <path> <blake3> <state>`. const listed = try s.read("/addons"); - try std.testing.expect(std.mem.startsWith(u8, listed, "fake 1 3.2 0 /")); + try std.testing.expect(std.mem.startsWith(u8, listed, "fake 1 3.3 0 /")); var fields = std.mem.tokenizeScalar(u8, listed[0..std.mem.indexOfScalar(u8, listed, '\n').?], ' '); for (0..5) |_| _ = fields.next(); try std.testing.expectEqual(@as(usize, 64), fields.next().?.len); @@ -51,7 +51,7 @@ test "addons: Addon load takes a library in, /addons lists it with the kinds com // A pane of it open, it stays; closed, it goes. try s.write("/ctl", "Fake\n"); const pane = try paneOf(&s, "fake"); - try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "fake 1 3.2 1 /")); + try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "fake 1 3.3 1 /")); try std.testing.expect(try s.refused("/ctl", "Addon unload fake\n") != 0); try std.testing.expect(has(s.said, "1 fake pane is open")); try s.write(s.at("/pane/{d}/ctl", .{pane}), "Del\n"); @@ -68,7 +68,7 @@ test "addons: a library of another ABI, one with no pardes_addon, and one whose try std.testing.expect(std.mem.startsWith(u8, listed, "fakeabi 1 2.2 0 /")); try std.testing.expect(has(listed, " refused: wants abi 2, this pardes speaks 3\n")); try std.testing.expect(has(listed, " refused: it has no pardes_addon\n")); - try std.testing.expect(has(listed, "\nfakeword 1 3.2 0 /")); + try std.testing.expect(has(listed, "\nfakeword 1 3.3 0 /")); try std.testing.expect(has(listed, " refused: word Save is the core's\n")); // A file that is no library at all: listed with what the loader said. var tmp = std.testing.tmpDir(.{}); @@ -120,7 +120,7 @@ test "addons: the image addon opens the pictures a Look names, fitted, with the defer s.deinit(); try load(&s, Session.image_addon); const listed = try s.read("/addons"); - try std.testing.expect(std.mem.startsWith(u8, listed, "image 1 3.2 0 /") and has(listed, " loaded\n")); + try std.testing.expect(std.mem.startsWith(u8, listed, "image 1 3.3 0 /") and has(listed, " loaded\n")); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig index 18fa503c..0c7982d1 100644 --- a/test/behaviour/addons_pdf.zig +++ b/test/behaviour/addons_pdf.zig @@ -38,7 +38,7 @@ test "addons: a PDF is the pdf addon's pane, its pages pictures, its page in its s.graphics(); const n = try s.lookFile("docs/design.pdf"); try std.testing.expect(has(try s.read("/index"), " pdf ")); - try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "pdf 1 3.2 1 /")); + try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "pdf 1 3.3 1 /")); const pages = (try s.pdfPage(n))[1]; try std.testing.expectEqual(@as(u32, 16), pages); // Its first page, a picture over its body. diff --git a/test/daemon.py b/test/daemon.py index 90977ef4..c465b52f 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -3787,6 +3787,10 @@ def upgrades(old, new): raise TimeoutError(f'the client joined again: not {[c.stem for _, c in owners if c not in joined]} ' f'{time.monotonic() - t0:.1f} s after the Upgrade, the session back at {back:.1f} s') from None assert again.poll() is None and again5.poll() is None + # The session's news: each client's own screen says it (a long + # message shows its end), not only the view whose input came + # last before the Upgrade's step. + wait_for("each client's own screen saying the Upgrade's outcome", lambda: all(b'it goes on as' in t.text() for t, _ in owners), timeout=15) for (t, check), pane, theirs in zip(owners, mine, reversed(mine)): in_own_view('its own view again', lambda: made_live(t, check), client, pane, theirs) for c, t in ((again, term4), (again5, term5)): diff --git a/test/liar.zig b/test/liar.zig index f564614b..e7bc2763 100644 --- a/test/liar.zig +++ b/test/liar.zig @@ -32,6 +32,7 @@ pub const Liar = extern struct { }; pub const pardes_addon = addon.ops(Liar); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } diff --git a/test/pdf-fixtures/huge-pages.pdf b/test/pdf-fixtures/huge-pages.pdf new file mode 100644 index 00000000..f2d73a14 --- /dev/null +++ b/test/pdf-fixtures/huge-pages.pdf @@ -0,0 +1,61 @@ +%PDF-1.4 +1 0 obj +<< /Type /Catalog /Pages 2 0 R >> +endobj +2 0 obj +<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >> +endobj +3 0 obj +<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1000000000 792] /Contents 4 0 R >> +endobj +4 0 obj +<< /Length 17 >> +stream +0 0 m 100 100 l S +endstream +endobj +5 0 obj +<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1000000000000000000000000000000000000000000000 1000000000000000000000000000000000000000000000] /Contents 6 0 R >> +endobj +6 0 obj +<< /Length 17 >> +stream +0 0 m 100 100 l S +endstream +endobj +7 0 obj +<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /UserUnit 1000000000000000000000000000000000000 /Contents 8 0 R >> +endobj +8 0 obj +<< /Length 17 >> +stream +0 0 m 100 100 l S +endstream +endobj +9 0 obj +<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 10 0 R >> +endobj +10 0 obj +<< /Length 17 >> +stream +0 0 m 100 100 l S +endstream +endobj +xref +0 11 +0000000000 65535 f +0000000009 00000 n +0000000058 00000 n +0000000133 00000 n +0000000227 00000 n +0000000294 00000 n +0000000467 00000 n +0000000534 00000 n +0000000669 00000 n +0000000736 00000 n +0000000824 00000 n +trailer +<< /Size 11 /Root 1 0 R >> +startxref +892 +%%EOF diff --git a/test/veil.zig b/test/veil.zig index 0be5d218..ac51de1c 100644 --- a/test/veil.zig +++ b/test/veil.zig @@ -32,6 +32,7 @@ pub const Veil = extern struct { }; pub const pardes_addon = addon.ops(Veil); +pub const panic = addon.panic; comptime { addon.exportLib(&pardes_addon); } |
