diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-09 00:52:52 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-09 01:28:28 -0300 |
| commit | 5157579ff7f9ae0cfc3c7629e953da05bce340fc (patch) | |
| tree | 02147789efdcea998981efcfe05d4bcb3e9bb7b0 /src/tui/tui.zig | |
| parent | 4c4b9bf54d77dbc0f9f4e2619746908e501c6001 (diff) | |
| download | pardes-5157579ff7f9ae0cfc3c7629e953da05bce340fc.tar.gz pardes-5157579ff7f9ae0cfc3c7629e953da05bce340fc.zip | |
tests: at the end of their files: every top-level test block of the 46 files that had one mid-file (the locality analysis's 45 and test/hxdiff.zig; gui.zig, macos.zig, look, host_io, 9p_io, terminal, tui, mouse, fs, replica, layout among them, 11,429 test lines), with the functions only tests call, moved after the file's code in their order, a mechanical move (.scratch/suites/tests_to_end.py), zig fmt'd; the unit suites pass as before (tui 1486/1487, gui 1536/1537, core 956/956 on both), macos.zig only parse-checked here
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
Diffstat (limited to 'src/tui/tui.zig')
| -rw-r--r-- | src/tui/tui.zig | 1429 |
1 files changed, 714 insertions, 715 deletions
diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 5532fdb3..d5d3a782 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -375,344 +375,6 @@ const TestReader = struct { } }; -test "terminal input preserves fragmented keys queries paste and text after EOF" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ .parts = &.{ - "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", - "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", - } }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(t.vx.queries_done.load(.unordered)); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var resized = false; - var up = false; - var in_paste = false; - var pasted = false; - var clipboard = false; - var escape = false; - while (try t.loop.tryEvent()) |event| switch (event) { - .winsize => |size| { - try std.testing.expect(!resized); - resized = true; - try std.testing.expectEqual(@as(u16, 80), size.cols); - }, - .key_press => |key| { - try std.testing.expect(resized); - if (key.codepoint == vaxis.Key.up) { - up = true; - } else if (key.codepoint == vaxis.Key.escape) { - escape = true; - } else if (key.text) |bytes| { - if (in_paste) try std.testing.expect(up); - try text.appendSlice(gpa, bytes); - } else return error.UnexpectedInputKey; - }, - .paste_start => { - try std.testing.expect(up and !in_paste); - in_paste = true; - }, - .paste_end => { - try std.testing.expect(in_paste); - in_paste = false; - pasted = true; - }, - .paste => |bytes| { - defer gpa.free(@constCast(bytes)); - try std.testing.expect(pasted and !in_paste); - try std.testing.expectEqualStrings("clip", bytes); - clipboard = true; - }, - // The device attributes' wake (a capability answer). - .nop => try std.testing.expect(t.vx.queries_done.load(.unordered)), - else => return error.UnexpectedInputEvent, - }; - try std.testing.expectEqualStrings("plain café 界 😀tail", text.items); - try std.testing.expect(resized and up and pasted and clipboard and escape); -} - -test "terminal replies and malformed sequences never become typed text" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ - .parts = &.{ - // The startup width queries' answers where the terminal has no - // explicit width: both used to arrive as a bare F3, typed as text. - "a\x1b[1;1R\x1b[1;1R", - // A late report somewhere else on the screen, and DECXCPR. - "\x1b[12;40R\x1b[?3;7;1R", - // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`. - "b\x1b\x1b[A", - // A kitty graphics reply cut inside its ST sliced past its input. - "\x1b_Gi=1;OK\x1b", - "\\", - // An X10 mouse report cut after `CSI M` left three bytes as text. - "\x1b[M", - " !!", - // Malformed color and clipboard replies failed the parse, which - // ended input altogether; and a reply ended by BEL ran on to the - // next sequence's ESC, leaving what lay between as text. - "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07", - // Device reports whose fields end early. - "\x1b[?1;y\x1b[?997;n\x1b[c", - "\x1b[?62;c", - "c", - }, - }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(t.vx.queries_done.load(.unordered)); - try std.testing.expect(t.vx.caps.kitty_graphics); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var alt_up = false; - var clicked = false; - while (try t.loop.tryEvent()) |event| switch (event) { - .winsize => {}, - .key_press => |key| { - if (key.codepoint == vaxis.Key.up and key.mods.alt) { - alt_up = true; - } else if (key.text) |bytes| { - try text.appendSlice(gpa, bytes); - } else return error.UnexpectedInputKey; - }, - .mouse => |mouse| { - try std.testing.expectEqual(@as(i16, 0), mouse.col); - clicked = true; - }, - .nop => {}, // the device attributes' wake - else => return error.UnexpectedInputEvent, - }; - try std.testing.expectEqualStrings("abc", text.items); - try std.testing.expect(alt_up and clicked); -} - -test "terminal input split at every byte with a gap reads as it does whole" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - // Two reads with `gap_ms` between them, as an ssh link delivers a - // sequence cut across two packets (TestReader). - const Events = struct { - /// What the loop was handed, one line per event. - fn of(l: *Loop, out: *std.ArrayList(u8)) !void { - out.clearRetainingCapacity(); - while (try l.tryEvent()) |event| switch (event) { - .winsize => {}, - .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }), - .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }), - .paste => |bytes| { - try out.print(std.testing.allocator, "paste {s}\n", .{bytes}); - std.testing.allocator.free(@constCast(bytes)); - }, - else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}), - }; - } - }; - const Case = struct { bytes: []const u8, kitty: bool = false }; - const cases = [_]Case{ - .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V - .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text - .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own - .{ .bytes = "\x1b[27u", .kitty = true }, // Escape - .{ .bytes = "\x1b[A" }, - .{ .bytes = "\x1bOA" }, - .{ .bytes = "\x1b[3;5~" }, - .{ .bytes = "\x1b\x1b[A" }, - // Four wheel notches: cut at a `;` with 60 ms between the halves, - // ssh's framing lost all four. - .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" }, - .{ .bytes = "\x1b[200~pasted\x1b[201~" }, - .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" }, - .{ .bytes = "\x1b_Gi=1;OK\x1b\\" }, - .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" }, - }; - var whole: std.ArrayList(u8) = .empty; - defer whole.deinit(gpa); - var split: std.ArrayList(u8) = .empty; - defer split.deinit(gpa); - for (cases) |case| { - t.vx.caps.kitty_keyboard = case.kitty; - const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); - defer gpa.free(all); - const whole_parts = [_][]const u8{ all, "" }; - var one: TestReader = .{ .parts = &whole_parts }; - try readInput(&t.loop, &one, &t.vx, &t.feed); - try Events.of(&t.loop, &whole); - for (1..all.len) |cut| { - // A cut just after an ESC is the one that has to wait, and a - // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut - // anywhere else is carried however long the gap. - const after_esc = all[cut - 1] == 0x1b; - const halves = [_][]const u8{ all[0..cut], all[cut..] }; - var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&t.loop, &two, &t.vx, &t.feed); - try Events.of(&t.loop, &split); - std.testing.expectEqualStrings(whole.items, split.items) catch |err| { - std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); - return err; - }; - } - } - t.vx.caps.kitty_keyboard = false; -} - -test "an ESC read by itself is the Escape key at once" { - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - // More always follows at once: a reader that waited on the ESC would - // take `j` for the rest of its sequence (Alt-j). - for ([_]bool{ false, true }) |kitty| { - t.vx.caps.kitty_keyboard = kitty; - var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(!reader.asked); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); - const escape = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - const j = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(@as(u21, 'j'), j.codepoint); - try std.testing.expect(!j.mods.alt); - try std.testing.expect(try t.loop.tryEvent() == null); - } - t.vx.caps.kitty_keyboard = false; -} - -test "a frame's answer is taken wherever the reads cut it, and never typed" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - const all = "x" ++ FrameAck.answer ++ "y"; - defer t.feed.ack.waiting.store(false, .release); - for (0..all.len) |cut| { - t.feed.ack.waiting.store(true, .release); - const halves = [_][]const u8{ all[0..cut], all[cut..] }; - var reader: TestReader = .{ .parts = &halves }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(!t.feed.ack.waiting.load(.acquire)); - var typed: std.ArrayList(u8) = .empty; - defer typed.deinit(gpa); - var woke = false; - while (try t.loop.tryEvent()) |event| switch (event) { - .winsize => {}, - .nop => woke = true, - .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey), - else => return error.UnexpectedInputEvent, - }; - std.testing.expectEqualStrings("xy", typed.items) catch |err| { - std.debug.print("cut at {d}\n", .{cut}); - return err; - }; - try std.testing.expect(woke); - } - // An Escape pressed just before an answer, in the same read, is the - // Escape key, not Alt on the answer. - t.feed.ack.waiting.store(true, .release); - var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&t.loop, &glued, &t.vx, &t.feed); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); - try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?)); - const escape = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - try std.testing.expectEqual(@as(u21, 'j'), (try t.loop.tryEvent()).?.key_press.codepoint); - try std.testing.expect(try t.loop.tryEvent() == null); -} - -test "a terminal that never answers a frame stops being asked after one timeout" { - const io = std.testing.io; - var ack: FrameAck = .{}; - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - const t0: u64 = 5 * std.time.ns_per_s; - ack.ask(&out.writer, t0); - try std.testing.expectEqualStrings(FrameAck.request, out.written()); - // Unanswered: the next frame waits, until the timeout. - try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); - try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); - try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); - // Then never again: no request, no wait. - out.clearRetainingCapacity(); - ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); - try std.testing.expectEqual(@as(usize, 0), out.written().len); - try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); -} - -test "terminal input cancellation joins blocked reads and queued EOF" { - const io = std.testing.io; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - const Reader = struct { - file: std.Io.File, - eof: bool, - entered: std.Io.Event = .unset, - release: std.Io.Event = .unset, - returned: std.Io.Event = .unset, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(_: *@This(), _: u32) bool { - return false; - } - fn read(self: *@This(), buf: []u8) !usize { - self.entered.set(std.testing.io); - if (self.eof) { - try self.release.wait(std.testing.io); - self.returned.set(std.testing.io); - return 0; - } - return self.file.readStreaming(std.testing.io, &.{buf}); - } - fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { - inputReader(loop, reader, vx_, feed); - } - }; - const Case = enum { blocked_read, cancel_eof, deliver_eof }; - for (std.enums.values(Case)) |case| { - const eof = case != .blocked_read; - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return error.PipeFailed; - defer _ = libc.close(fds[0]); - defer _ = libc.close(fds[1]); - var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; - var loop: Loop = .init(io, undefined, &t.vx); - var feed: Feed = .{}; - var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.vx, &feed }); - defer stopInput(io, &thread); - try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); - try reader.entered.wait(io); - if (eof) { - for (0..512) |_| try loop.postEvent(.nop); - reader.release.set(io); - try reader.returned.wait(io); - } - if (case == .deliver_eof) { - try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); - thread.?.await(io); - } - stopInput(io, &thread); - try std.testing.expect(thread == null); - var count: usize = 0; - while (try loop.tryEvent()) |event| { - const expected: std.meta.Tag(Msg) = if (case == .deliver_eof and count == 511) .quit else .nop; - try std.testing.expectEqual(expected, std.meta.activeTag(event)); - count += 1; - } - try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count); - } -} - const PipeTasks = selection_pipe.Tasks; const Pty = struct { @@ -905,124 +567,6 @@ fn kittyPlacement( }; } -test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { - var place = pardes.Placement{ - .pane = 0, - .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 }, - .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, - .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 }, - .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, - .key = pardes.Placement.keyOf(3, 7, 0), - }; - // 10x20 pixel cells: a whole row, one to one. - const full = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(u16, 0), full.cell_x); - try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows); - try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y); - try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width); - try std.testing.expect(full.options.pixel_offset == null); - - // The top of a letterboxed picture: 7 pixels down into the row, 13 - // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns - // only, its source no taller than the 13 pixels left in the row at - // that scale. - place.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }; - place.at = .{ .x = 35, .y = 7, .w = 205, .h = 13 }; - const top = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(u16, 3), top.cell_x); - try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x); - try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y); - try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows); - const w = top.options.clip_region.?.width.?; - const h = top.options.clip_region.?.height.?; - try std.testing.expectEqual(@as(u16, 205), w); - try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13); - - // Narrower than its cells round to: the source is cut to their scale. - place.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }; - place.at = .{ .x = 0, .y = 0, .w = 204, .h = 20 }; - const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width); -} - -test "Kitty PDF fragments never declare pixels beyond their clipped bottom" { - // As wide as the body: fit to width. - const base = pardes.Placement{ - .pane = 0, - .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 }, - .src = .{ .w = 96, .h = 10 }, - .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 }, - .at = .{ .y = 195, .w = 304, .h = 29 }, - .key = pardes.Placement.keyOf(1, 0, 1), - }; - const width = kittyPlacement(base, 80, 16, 640, 256) orelse - return error.MissingSafeKittyWidthFragment; - const width_clip = width.options.clip_region.?; - const width_size = width.options.size.?; - try std.testing.expectEqual(@as(u16, 5), width_clip.height.?); - try std.testing.expectEqual(@as(u16, 38), width_size.cols.?); - try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y); - const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? + - width_clip.width.? - 1) / width_clip.width.?; - const inferred_rows = (aspect_pixels + 15) / 16; - try std.testing.expect(inferred_rows * 16 <= base.at.?.h); - - // Narrower than the body: fit to height. - var height = base; - height.at.?.w = 300; - height.src.h = 9; - const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse - return error.MissingSafeKittyHeightFragment; - try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?); - try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <= - height.at.?.h); - - height.at.?.h = 13; - try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); -} - -test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } }); - const pane = core.panes[0].?; - pane.body.mode = .tty; - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const a = frame.allocator(); - const px = try a.alloc(u8, 64 * 64 * 3); - for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 }; - const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len)); - _ = std.base64.standard.Encoder.encode(enc, px); - core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } }); - while (core.nextEffect()) |_| {} - const s = try core.render(a); - try std.testing.expectEqual(@as(usize, 4), s.placements.items.len); - var art: Art = .{}; - defer art.deinit(gpa); - try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16)); - const shown = try art.frame(gpa, a, s, false, 16); - const r = core.view().rects[0]; - const x0 = r.x + pardes.config.GUTTER + 7; - const y0 = core.bodyTop(pane, r) + 1; - var painted: usize = 0; - for (0..4) |dy| for (0..8) |dx| { - const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy))); - const bg = switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => continue, - }; - for (Art.commodore) |c| { - if (std.mem.eql(u8, &c, &bg)) painted += 1; - } - }; - try std.testing.expectEqual(@as(usize, 32), painted); -} - fn kittyImageRepresentable(place: pardes.Placement) bool { return place.raster.w > 0 and place.raster.h > 0 and place.raster.w <= std.math.maxInt(u16) and place.raster.h <= std.math.maxInt(u16); @@ -1284,7 +828,6 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se } } - /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, /// the terminal closed) at the session's start and end, and at a detach and @@ -2673,93 +2216,6 @@ const Shell = struct { } }; -test "TTY queued results reject old PTY generations and LSP request IDs" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer core.deinit(); - var shell: Shell = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_gpa = gpa, - .core = core, - .prompt_rcs = undefined, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .inotify_fd = -1, - }; - shell.gens[0] = 2; - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); - try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); - - core.lspRequest(0, .status, ""); - const old_id = core.lsp_ask.wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_ask.wait.?.id; - shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); - try std.testing.expect(shell.lsp_task != null); - try std.testing.expectEqual(current_id, shell.lsp_task.?.id); - try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); - _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expect(core.lsp_ask.wait == null); -} - -test "TTY worker setup failures finish matching LSP and pipe requests" { - const gpa = std.testing.allocator; - var failing_vtable = std.testing.io.vtable.*; - failing_vtable.concurrent = std.Io.failingConcurrent; - const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; - for (0..2) |failure| { - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - var failing = std.testing.FailingAllocator.init(gpa, .{ - .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), - }); - var shell: Shell = .{ - .io = failing_io, - .gpa = failing.allocator(), - .lsp_gpa = failing.allocator(), - .core = core, - .prompt_rcs = undefined, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .inotify_fd = -1, - .threads_ok = true, - }; - core.lspRequest(core.view().active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_ask.wait.?.id, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = "", - }; - Shell.lsp(&shell, req); - try std.testing.expect(core.lsp_ask.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - - pane.body.cur_col = 2; - pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - core.update(.{ .key = .{ .cp = '|' } }); - core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe.wait.?.id; - Shell.pipe(&shell, pipe_id); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); - } -} - fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); const copy = s.lsp_gpa.dupe(u8, text) catch return; @@ -2849,29 +2305,6 @@ fn timeWake(io: std.Io, seen: *u32) bool { } } -test "a short wake request cuts short a long one still sleeping" { - const io = std.testing.io; - var seen = wake_gen.load(.acquire); - requestWake(io, 800); - seen = wake_gen.load(.acquire); - const Timer = struct { - fn run(timer_io: std.Io, start_seen: u32, done: *std.atomic.Value(u64)) void { - var local = start_seen; - _ = timeWake(timer_io, &local); - done.store(@intCast(std.Io.Clock.awake.now(timer_io).nanoseconds), .release); - } - }; - var done: std.atomic.Value(u64) = .init(0); - const start: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - const thread = try std.Thread.spawn(.{}, Timer.run, .{ io, seen, &done }); - try io.sleep(.fromMilliseconds(50), .awake); - requestWake(io, 16); - thread.join(); - // The 16 ms request lands about 66 ms in: well before the 800 ms one - // would have, however loaded the machine. - try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms); -} - fn wakeFs(ctx: ?*anyopaque) void { const loop: *Loop = @ptrCast(@alignCast(ctx.?)); _ = loop.tryPostEvent(.fs_ready) catch {}; @@ -2917,6 +2350,720 @@ fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; +fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { + const button: pardes.Mouse.Button = switch (m.button) { + .left => .left, + .middle => .middle, + .right => .right, + .wheel_up => .wheel_up, + .wheel_down => .wheel_down, + .wheel_left => .wheel_left, + .wheel_right => .wheel_right, + // A mouse's side buttons, as xterm reports them: Back and Forward. + .button_8 => .back, + .button_9 => .forward, + .none => .none, // button-less motion: hover tracking + else => return null, + }; + return .{ .mouse = .{ + .button = button, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + .col = cellOf(m.col), + .row = cellOf(m.row), + .ctrl = m.mods.ctrl, + .shift = m.mods.shift, + .alt = m.mods.alt, + } }; +} + +/// A report's cell, 0-based: one before the first (SGR's 0, a drag past +/// the window's top or left edge, in cells or in 1016's pixels) is the +/// first, never a panic; past the far edge the core clamps it. +pub fn cellOf(v: i16) u16 { + return @intCast(@max(0, v)); +} + +/// A replica client's own line over its frame's last row (`Remote.notify`), +/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps +/// the slices). +fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { + if (rows == 0) return; + for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ + .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, + .style = .{ .reverse = true }, + }); +} + +/// A blank whose ink alone changed is not sent: vaxis's render skips it +/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows +/// nowhere. Deciding that here cost every cell of every frame a look at the +/// frame before; vaxis already makes that comparison. +/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind +/// the cursor in its body, on the page's own ground, that ground drawn +/// toward the text's colour; a copy of `shown` while it fades. +fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface { + var at: [5]JumpTrail.Cell = undefined; + const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); + if (lit.len == 0) return shown; + const cursor = shown.cursor.?; + const body = for (shown.regionList()) |region| { + if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and + cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; + } else return shown; + const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; + const page = shown.chrome.page orelse pardes.colors.null_page; + const out = try arena.create(pardes.Surface); + out.* = shown.*; + out.cells = try arena.dupe(pardes.Cell, shown.cells); + for (lit) |cell| { + if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; + const c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))]; + // On the page's own ground alone: never a selection or a match. + const ground: [3]u8 = if (c.default) page else switch (c.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (!std.mem.eql(u8, &ground, &page)) continue; + if (c.default) c.style = .{}; + c.default = false; + c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) }; + } + return out; +} + +/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does +/// not answer vaxis's query. +fn colortermTruecolor() bool { + const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false); + return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit"); +} + +/// The tty's picture of the glide (glide.zig, anim 12): the body's rows +/// moved by the offset rounded to whole rows (the position rounded, never +/// the step, so a slowing glide's steps come further apart), the rows that +/// left in the gap it opens, and a caret whose line rode the scroll carried +/// with it; `canonical` itself while the picture is where the core is, else +/// a copy of it in `arena`. The rows are walked from the side they move +/// toward, so each is read before a move writes over it. +fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface { + const k: i32 = @intFromFloat(@round(glide.follow.offset)); + const w = glide.bw(); + const h = glide.body_h; + const x0 = glide.rect.x + pardes.config.GUTTER; + const y0 = glide.body_y; + if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical; + const out = try arena.create(pardes.Surface); + out.* = canonical.*; + out.cells = try arena.dupe(pardes.Cell, canonical.cells); + const cols: usize = out.cols; + for (0..h) |i| { + const r = if (k > 0) i else h - 1 - i; + const from = @as(i32, @intCast(r)) + k; + const to = out.cells[(y0 + r) * cols + x0 ..][0..w]; + const kept: ?[]const pardes.Cell = if (from >= 0 and from < h) + out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w] + else if (from < 0 and -from - 1 < glide.nabove) + glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w] + else if (from >= h and from - h < glide.nbelow) + glide.below[@as(usize, @intCast(from - h)) * w ..][0..w] + else + null; + if (kept) |cells| @memcpy(to, cells) else @memset(to, .{}); + } + if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) { + const y = @as(i32, c.y) - k; + if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null; + }; + return out; +} + +fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void { + win.clear(); + var y: u16 = 0; + while (y < rows) : (y += 1) { + var x: u16 = 0; + while (x < cols) : (x += 1) { + const cell = &cells[@as(usize, y) * cols + x]; + if (cell.default) continue; + win.writeCell(x, y, .{ + .char = .{ .grapheme = cell.grapheme() }, + .style = vaxis_input.style(cell.style), + }); + } + } +} + +test "terminal input preserves fragmented keys queries paste and text after EOF" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ .parts = &.{ + "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", + "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", + } }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(t.vx.queries_done.load(.unordered)); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var resized = false; + var up = false; + var in_paste = false; + var pasted = false; + var clipboard = false; + var escape = false; + while (try t.loop.tryEvent()) |event| switch (event) { + .winsize => |size| { + try std.testing.expect(!resized); + resized = true; + try std.testing.expectEqual(@as(u16, 80), size.cols); + }, + .key_press => |key| { + try std.testing.expect(resized); + if (key.codepoint == vaxis.Key.up) { + up = true; + } else if (key.codepoint == vaxis.Key.escape) { + escape = true; + } else if (key.text) |bytes| { + if (in_paste) try std.testing.expect(up); + try text.appendSlice(gpa, bytes); + } else return error.UnexpectedInputKey; + }, + .paste_start => { + try std.testing.expect(up and !in_paste); + in_paste = true; + }, + .paste_end => { + try std.testing.expect(in_paste); + in_paste = false; + pasted = true; + }, + .paste => |bytes| { + defer gpa.free(@constCast(bytes)); + try std.testing.expect(pasted and !in_paste); + try std.testing.expectEqualStrings("clip", bytes); + clipboard = true; + }, + // The device attributes' wake (a capability answer). + .nop => try std.testing.expect(t.vx.queries_done.load(.unordered)), + else => return error.UnexpectedInputEvent, + }; + try std.testing.expectEqualStrings("plain café 界 😀tail", text.items); + try std.testing.expect(resized and up and pasted and clipboard and escape); +} + +test "terminal replies and malformed sequences never become typed text" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ + .parts = &.{ + // The startup width queries' answers where the terminal has no + // explicit width: both used to arrive as a bare F3, typed as text. + "a\x1b[1;1R\x1b[1;1R", + // A late report somewhere else on the screen, and DECXCPR. + "\x1b[12;40R\x1b[?3;7;1R", + // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`. + "b\x1b\x1b[A", + // A kitty graphics reply cut inside its ST sliced past its input. + "\x1b_Gi=1;OK\x1b", + "\\", + // An X10 mouse report cut after `CSI M` left three bytes as text. + "\x1b[M", + " !!", + // Malformed color and clipboard replies failed the parse, which + // ended input altogether; and a reply ended by BEL ran on to the + // next sequence's ESC, leaving what lay between as text. + "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07", + // Device reports whose fields end early. + "\x1b[?1;y\x1b[?997;n\x1b[c", + "\x1b[?62;c", + "c", + }, + }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(t.vx.queries_done.load(.unordered)); + try std.testing.expect(t.vx.caps.kitty_graphics); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var alt_up = false; + var clicked = false; + while (try t.loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |key| { + if (key.codepoint == vaxis.Key.up and key.mods.alt) { + alt_up = true; + } else if (key.text) |bytes| { + try text.appendSlice(gpa, bytes); + } else return error.UnexpectedInputKey; + }, + .mouse => |mouse| { + try std.testing.expectEqual(@as(i16, 0), mouse.col); + clicked = true; + }, + .nop => {}, // the device attributes' wake + else => return error.UnexpectedInputEvent, + }; + try std.testing.expectEqualStrings("abc", text.items); + try std.testing.expect(alt_up and clicked); +} + +test "terminal input split at every byte with a gap reads as it does whole" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // Two reads with `gap_ms` between them, as an ssh link delivers a + // sequence cut across two packets (TestReader). + const Events = struct { + /// What the loop was handed, one line per event. + fn of(l: *Loop, out: *std.ArrayList(u8)) !void { + out.clearRetainingCapacity(); + while (try l.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }), + .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }), + .paste => |bytes| { + try out.print(std.testing.allocator, "paste {s}\n", .{bytes}); + std.testing.allocator.free(@constCast(bytes)); + }, + else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}), + }; + } + }; + const Case = struct { bytes: []const u8, kitty: bool = false }; + const cases = [_]Case{ + .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V + .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text + .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own + .{ .bytes = "\x1b[27u", .kitty = true }, // Escape + .{ .bytes = "\x1b[A" }, + .{ .bytes = "\x1bOA" }, + .{ .bytes = "\x1b[3;5~" }, + .{ .bytes = "\x1b\x1b[A" }, + // Four wheel notches: cut at a `;` with 60 ms between the halves, + // ssh's framing lost all four. + .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" }, + .{ .bytes = "\x1b[200~pasted\x1b[201~" }, + .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" }, + .{ .bytes = "\x1b_Gi=1;OK\x1b\\" }, + .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" }, + }; + var whole: std.ArrayList(u8) = .empty; + defer whole.deinit(gpa); + var split: std.ArrayList(u8) = .empty; + defer split.deinit(gpa); + for (cases) |case| { + t.vx.caps.kitty_keyboard = case.kitty; + const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); + defer gpa.free(all); + const whole_parts = [_][]const u8{ all, "" }; + var one: TestReader = .{ .parts = &whole_parts }; + try readInput(&t.loop, &one, &t.vx, &t.feed); + try Events.of(&t.loop, &whole); + for (1..all.len) |cut| { + // A cut just after an ESC is the one that has to wait, and a + // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut + // anywhere else is carried however long the gap. + const after_esc = all[cut - 1] == 0x1b; + const halves = [_][]const u8{ all[0..cut], all[cut..] }; + var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; + try readInput(&t.loop, &two, &t.vx, &t.feed); + try Events.of(&t.loop, &split); + std.testing.expectEqualStrings(whole.items, split.items) catch |err| { + std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); + return err; + }; + } + } + t.vx.caps.kitty_keyboard = false; +} + +test "an ESC read by itself is the Escape key at once" { + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // More always follows at once: a reader that waited on the ESC would + // take `j` for the rest of its sequence (Alt-j). + for ([_]bool{ false, true }) |kitty| { + t.vx.caps.kitty_keyboard = kitty; + var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(!reader.asked); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); + const escape = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + const j = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(@as(u21, 'j'), j.codepoint); + try std.testing.expect(!j.mods.alt); + try std.testing.expect(try t.loop.tryEvent() == null); + } + t.vx.caps.kitty_keyboard = false; +} + +test "a frame's answer is taken wherever the reads cut it, and never typed" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + const all = "x" ++ FrameAck.answer ++ "y"; + defer t.feed.ack.waiting.store(false, .release); + for (0..all.len) |cut| { + t.feed.ack.waiting.store(true, .release); + const halves = [_][]const u8{ all[0..cut], all[cut..] }; + var reader: TestReader = .{ .parts = &halves }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(!t.feed.ack.waiting.load(.acquire)); + var typed: std.ArrayList(u8) = .empty; + defer typed.deinit(gpa); + var woke = false; + while (try t.loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .nop => woke = true, + .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey), + else => return error.UnexpectedInputEvent, + }; + std.testing.expectEqualStrings("xy", typed.items) catch |err| { + std.debug.print("cut at {d}\n", .{cut}); + return err; + }; + try std.testing.expect(woke); + } + // An Escape pressed just before an answer, in the same read, is the + // Escape key, not Alt on the answer. + t.feed.ack.waiting.store(true, .release); + var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } }; + try readInput(&t.loop, &glued, &t.vx, &t.feed); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); + try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?)); + const escape = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + try std.testing.expectEqual(@as(u21, 'j'), (try t.loop.tryEvent()).?.key_press.codepoint); + try std.testing.expect(try t.loop.tryEvent() == null); +} + +test "a terminal that never answers a frame stops being asked after one timeout" { + const io = std.testing.io; + var ack: FrameAck = .{}; + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + const t0: u64 = 5 * std.time.ns_per_s; + ack.ask(&out.writer, t0); + try std.testing.expectEqualStrings(FrameAck.request, out.written()); + // Unanswered: the next frame waits, until the timeout. + try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); + try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); + try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); + // Then never again: no request, no wait. + out.clearRetainingCapacity(); + ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); + try std.testing.expectEqual(@as(usize, 0), out.written().len); + try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); +} + +test "terminal input cancellation joins blocked reads and queued EOF" { + const io = std.testing.io; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + const Reader = struct { + file: std.Io.File, + eof: bool, + entered: std.Io.Event = .unset, + release: std.Io.Event = .unset, + returned: std.Io.Event = .unset, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(_: *@This(), _: u32) bool { + return false; + } + fn read(self: *@This(), buf: []u8) !usize { + self.entered.set(std.testing.io); + if (self.eof) { + try self.release.wait(std.testing.io); + self.returned.set(std.testing.io); + return 0; + } + return self.file.readStreaming(std.testing.io, &.{buf}); + } + fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { + inputReader(loop, reader, vx_, feed); + } + }; + const Case = enum { blocked_read, cancel_eof, deliver_eof }; + for (std.enums.values(Case)) |case| { + const eof = case != .blocked_read; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + defer _ = libc.close(fds[0]); + defer _ = libc.close(fds[1]); + var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; + var loop: Loop = .init(io, undefined, &t.vx); + var feed: Feed = .{}; + var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.vx, &feed }); + defer stopInput(io, &thread); + try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); + try reader.entered.wait(io); + if (eof) { + for (0..512) |_| try loop.postEvent(.nop); + reader.release.set(io); + try reader.returned.wait(io); + } + if (case == .deliver_eof) { + try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); + thread.?.await(io); + } + stopInput(io, &thread); + try std.testing.expect(thread == null); + var count: usize = 0; + while (try loop.tryEvent()) |event| { + const expected: std.meta.Tag(Msg) = if (case == .deliver_eof and count == 511) .quit else .nop; + try std.testing.expectEqual(expected, std.meta.activeTag(event)); + count += 1; + } + try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count); + } +} + +test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { + var place = pardes.Placement{ + .pane = 0, + .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 }, + .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, + .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 }, + .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, + .key = pardes.Placement.keyOf(3, 7, 0), + }; + // 10x20 pixel cells: a whole row, one to one. + const full = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(u16, 0), full.cell_x); + try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows); + try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y); + try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width); + try std.testing.expect(full.options.pixel_offset == null); + + // The top of a letterboxed picture: 7 pixels down into the row, 13 + // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns + // only, its source no taller than the 13 pixels left in the row at + // that scale. + place.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }; + place.at = .{ .x = 35, .y = 7, .w = 205, .h = 13 }; + const top = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(u16, 3), top.cell_x); + try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x); + try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y); + try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows); + const w = top.options.clip_region.?.width.?; + const h = top.options.clip_region.?.height.?; + try std.testing.expectEqual(@as(u16, 205), w); + try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13); + + // Narrower than its cells round to: the source is cut to their scale. + place.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }; + place.at = .{ .x = 0, .y = 0, .w = 204, .h = 20 }; + const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width); +} + +test "Kitty PDF fragments never declare pixels beyond their clipped bottom" { + // As wide as the body: fit to width. + const base = pardes.Placement{ + .pane = 0, + .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 }, + .src = .{ .w = 96, .h = 10 }, + .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 }, + .at = .{ .y = 195, .w = 304, .h = 29 }, + .key = pardes.Placement.keyOf(1, 0, 1), + }; + const width = kittyPlacement(base, 80, 16, 640, 256) orelse + return error.MissingSafeKittyWidthFragment; + const width_clip = width.options.clip_region.?; + const width_size = width.options.size.?; + try std.testing.expectEqual(@as(u16, 5), width_clip.height.?); + try std.testing.expectEqual(@as(u16, 38), width_size.cols.?); + try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y); + const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? + + width_clip.width.? - 1) / width_clip.width.?; + const inferred_rows = (aspect_pixels + 15) / 16; + try std.testing.expect(inferred_rows * 16 <= base.at.?.h); + + // Narrower than the body: fit to height. + var height = base; + height.at.?.w = 300; + height.src.h = 9; + const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse + return error.MissingSafeKittyHeightFragment; + try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?); + try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <= + height.at.?.h); + + height.at.?.h = 13; + try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); +} + +test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } }); + const pane = core.panes[0].?; + pane.body.mode = .tty; + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const a = frame.allocator(); + const px = try a.alloc(u8, 64 * 64 * 3); + for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 }; + const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len)); + _ = std.base64.standard.Encoder.encode(enc, px); + core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } }); + while (core.nextEffect()) |_| {} + const s = try core.render(a); + try std.testing.expectEqual(@as(usize, 4), s.placements.items.len); + var art: Art = .{}; + defer art.deinit(gpa); + try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16)); + const shown = try art.frame(gpa, a, s, false, 16); + const r = core.view().rects[0]; + const x0 = r.x + pardes.config.GUTTER + 7; + const y0 = core.bodyTop(pane, r) + 1; + var painted: usize = 0; + for (0..4) |dy| for (0..8) |dx| { + const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy))); + const bg = switch (cell.style.bg) { + .rgb => |rgb| rgb, + else => continue, + }; + for (Art.commodore) |c| { + if (std.mem.eql(u8, &c, &bg)) painted += 1; + } + }; + try std.testing.expectEqual(@as(usize, 32), painted); +} + +test "TTY queued results reject old PTY generations and LSP request IDs" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer core.deinit(); + var shell: Shell = .{ + .io = std.testing.io, + .gpa = gpa, + .lsp_gpa = gpa, + .core = core, + .prompt_rcs = undefined, + .loop = undefined, + .frame = undefined, + .paste_buf = undefined, + .inotify_fd = -1, + }; + shell.gens[0] = 2; + _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); + _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); + const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); + try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); + + core.lspRequest(0, .status, ""); + const old_id = core.lsp_ask.wait.?.id; + core.lspRequest(0, .status, ""); + const current_id = core.lsp_ask.wait.?.id; + shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; + _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); + try std.testing.expect(shell.lsp_task != null); + try std.testing.expectEqual(current_id, shell.lsp_task.?.id); + try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); + _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); + try std.testing.expect(shell.lsp_task == null); + try std.testing.expect(core.lsp_ask.wait == null); +} + +test "TTY worker setup failures finish matching LSP and pipe requests" { + const gpa = std.testing.allocator; + var failing_vtable = std.testing.io.vtable.*; + failing_vtable.concurrent = std.Io.failingConcurrent; + const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; + for (0..2) |failure| { + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("abc"); + var failing = std.testing.FailingAllocator.init(gpa, .{ + .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), + }); + var shell: Shell = .{ + .io = failing_io, + .gpa = failing.allocator(), + .lsp_gpa = failing.allocator(), + .core = core, + .prompt_rcs = undefined, + .loop = undefined, + .frame = undefined, + .paste_buf = undefined, + .inotify_fd = -1, + .threads_ok = true, + }; + core.lspRequest(core.view().active, .status, ""); + const req: host_io.Lsp.Request = .{ + .id = core.lsp_ask.wait.?.id, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }; + Shell.lsp(&shell, req); + try std.testing.expect(core.lsp_ask.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + core.update(.{ .key = .{ .cp = '|' } }); + core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + core.update(.{ .key = .{ .cp = pardes.Key.enter } }); + const pipe_id = core.pipe.wait.?.id; + Shell.pipe(&shell, pipe_id); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(shell.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); + } +} + +test "a short wake request cuts short a long one still sleeping" { + const io = std.testing.io; + var seen = wake_gen.load(.acquire); + requestWake(io, 800); + seen = wake_gen.load(.acquire); + const Timer = struct { + fn run(timer_io: std.Io, start_seen: u32, done: *std.atomic.Value(u64)) void { + var local = start_seen; + _ = timeWake(timer_io, &local); + done.store(@intCast(std.Io.Clock.awake.now(timer_io).nanoseconds), .release); + } + }; + var done: std.atomic.Value(u64) = .init(0); + const start: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); + const thread = try std.Thread.spawn(.{}, Timer.run, .{ io, seen, &done }); + try io.sleep(.fromMilliseconds(50), .awake); + requestWake(io, 16); + thread.join(); + // The 16 ms request lands about 66 ms in: well before the 800 ms one + // would have, however loaded the machine. + try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms); +} + test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { const gpa = std.testing.allocator; var t: TestInput = undefined; @@ -3023,44 +3170,6 @@ test "keypad Enter matches Return for editor input terminal writes and paste" { } } -fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { - const button: pardes.Mouse.Button = switch (m.button) { - .left => .left, - .middle => .middle, - .right => .right, - .wheel_up => .wheel_up, - .wheel_down => .wheel_down, - .wheel_left => .wheel_left, - .wheel_right => .wheel_right, - // A mouse's side buttons, as xterm reports them: Back and Forward. - .button_8 => .back, - .button_9 => .forward, - .none => .none, // button-less motion: hover tracking - else => return null, - }; - return .{ .mouse = .{ - .button = button, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, - }, - .col = cellOf(m.col), - .row = cellOf(m.row), - .ctrl = m.mods.ctrl, - .shift = m.mods.shift, - .alt = m.mods.alt, - } }; -} - -/// A report's cell, 0-based: one before the first (SGR's 0, a drag past -/// the window's top or left edge, in cells or in 1016's pixels) is the -/// first, never a panic; past the far edge the core clamps it. -pub fn cellOf(v: i16) u16 { - return @intCast(@max(0, v)); -} - test "a mouse report at row or column 0, or before it, is the window's edge, never a panic" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -3081,54 +3190,6 @@ test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 } } -/// A replica client's own line over its frame's last row (`Remote.notify`), -/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps -/// the slices). -fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { - if (rows == 0) return; - for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ - .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, - .style = .{ .reverse = true }, - }); -} - -/// A blank whose ink alone changed is not sent: vaxis's render skips it -/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows -/// nowhere. Deciding that here cost every cell of every frame a look at the -/// frame before; vaxis already makes that comparison. -/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind -/// the cursor in its body, on the page's own ground, that ground drawn -/// toward the text's colour; a copy of `shown` while it fades. -fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface { - var at: [5]JumpTrail.Cell = undefined; - const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); - if (lit.len == 0) return shown; - const cursor = shown.cursor.?; - const body = for (shown.regionList()) |region| { - if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and - cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; - } else return shown; - const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; - const page = shown.chrome.page orelse pardes.colors.null_page; - const out = try arena.create(pardes.Surface); - out.* = shown.*; - out.cells = try arena.dupe(pardes.Cell, shown.cells); - for (lit) |cell| { - if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; - const c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))]; - // On the page's own ground alone: never a selection or a match. - const ground: [3]u8 = if (c.default) page else switch (c.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (!std.mem.eql(u8, &ground, &page)) continue; - if (c.default) c.style = .{}; - c.default = false; - c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) }; - } - return out; -} - test "a jump's trail tints the ground behind the cursor in its body, and is gone by 120 ms" { std.testing.refAllDecls(JumpTrail); const gpa = std.testing.allocator; @@ -3164,68 +3225,6 @@ test "a jump's trail tints the ground behind the cursor in its body, and is gone try std.testing.expect(!trail.active); } -/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does -/// not answer vaxis's query. -fn colortermTruecolor() bool { - const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false); - return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit"); -} - -/// The tty's picture of the glide (glide.zig, anim 12): the body's rows -/// moved by the offset rounded to whole rows (the position rounded, never -/// the step, so a slowing glide's steps come further apart), the rows that -/// left in the gap it opens, and a caret whose line rode the scroll carried -/// with it; `canonical` itself while the picture is where the core is, else -/// a copy of it in `arena`. The rows are walked from the side they move -/// toward, so each is read before a move writes over it. -fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface { - const k: i32 = @intFromFloat(@round(glide.follow.offset)); - const w = glide.bw(); - const h = glide.body_h; - const x0 = glide.rect.x + pardes.config.GUTTER; - const y0 = glide.body_y; - if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical; - const out = try arena.create(pardes.Surface); - out.* = canonical.*; - out.cells = try arena.dupe(pardes.Cell, canonical.cells); - const cols: usize = out.cols; - for (0..h) |i| { - const r = if (k > 0) i else h - 1 - i; - const from = @as(i32, @intCast(r)) + k; - const to = out.cells[(y0 + r) * cols + x0 ..][0..w]; - const kept: ?[]const pardes.Cell = if (from >= 0 and from < h) - out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w] - else if (from < 0 and -from - 1 < glide.nabove) - glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w] - else if (from >= h and from - h < glide.nbelow) - glide.below[@as(usize, @intCast(from - h)) * w ..][0..w] - else - null; - if (kept) |cells| @memcpy(to, cells) else @memset(to, .{}); - } - if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) { - const y = @as(i32, c.y) - k; - if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null; - }; - return out; -} - -fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void { - win.clear(); - var y: u16 = 0; - while (y < rows) : (y += 1) { - var x: u16 = 0; - while (x < cols) : (x += 1) { - const cell = &cells[@as(usize, y) * cols + x]; - if (cell.default) continue; - win.writeCell(x, y, .{ - .char = .{ .grapheme = cell.grapheme() }, - .style = vaxis_input.style(cell.style), - }); - } - } -} - test "a fade sends the text it dims, not the blanks beside it" { const gpa = std.testing.allocator; var t: TestInput = undefined; |
