From 5157579ff7f9ae0cfc3c7629e953da05bce340fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 9 Nov 2026 00:52:52 -0300 Subject: 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 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/tui/tui.zig | 2005 +++++++++++++++++++++++++++---------------------------- 1 file changed, 1002 insertions(+), 1003 deletions(-) (limited to 'src/tui/tui.zig') 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 { @@ -848,179 +510,61 @@ fn kittyPlacement( const aspect_pixel_h: u32 = @intCast( (@as(u64, safe_src_h) * declared_pixel_w + geometry.src.w - 1) / geometry.src.w, - ); - declared_rows = @intCast( - (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h, - ); - }, - .height => { - declared_rows = safe_rows_u32; - safe_src_h = @max(@as(u32, 1), @as(u32, @intCast( - @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h, - ))); - safe_src_h = @min(safe_src_h, geometry.src.h); - const aspect_pixel_w: u32 = @intCast( - (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) / - safe_src_h, - ); - declared_cols = @intCast( - (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w, - ); - }, - } - if (declared_rows == 0 or declared_rows > safe_rows_u32) return null; - - const src_x = std.math.cast(u16, geometry.src.x) orelse return null; - const src_y = std.math.cast(u16, geometry.src.y) orelse return null; - const src_w = std.math.cast(u16, geometry.src.w) orelse return null; - const src_h = std.math.cast(u16, safe_src_h) orelse return null; - const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null; - const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null; - if (cell_x >= place.dst.w or cell_y >= place.dst.h) return null; - const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null; - const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null; - const cell_cols = std.math.cast(u16, @min( - @as(u32, place.dst.w - cell_x), - (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w, - )) orelse return null; - const cell_rows = std.math.cast(u16, @min( - @as(u32, place.dst.h - cell_y), - (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h, - )) orelse return null; - if (cell_cols == 0 or cell_rows == 0) return null; - - return .{ - .cell_x = cell_x, - .cell_y = cell_y, - .cell_cols = cell_cols, - .cell_rows = cell_rows, - .options = .{ - .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h }, - .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null, - .size = switch (fit) { - .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, - .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, - }, - }, - }; -} - -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); + ); + declared_rows = @intCast( + (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h, + ); + }, + .height => { + declared_rows = safe_rows_u32; + safe_src_h = @max(@as(u32, 1), @as(u32, @intCast( + @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h, + ))); + safe_src_h = @min(safe_src_h, geometry.src.h); + const aspect_pixel_w: u32 = @intCast( + (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) / + safe_src_h, + ); + declared_cols = @intCast( + (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w, + ); + }, + } + if (declared_rows == 0 or declared_rows > safe_rows_u32) return null; - height.at.?.h = 13; - try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); -} + const src_x = std.math.cast(u16, geometry.src.x) orelse return null; + const src_y = std.math.cast(u16, geometry.src.y) orelse return null; + const src_w = std.math.cast(u16, geometry.src.w) orelse return null; + const src_h = std.math.cast(u16, safe_src_h) orelse return null; + const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null; + const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null; + if (cell_x >= place.dst.w or cell_y >= place.dst.h) return null; + const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null; + const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null; + const cell_cols = std.math.cast(u16, @min( + @as(u32, place.dst.w - cell_x), + (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w, + )) orelse return null; + const cell_rows = std.math.cast(u16, @min( + @as(u32, place.dst.h - cell_y), + (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h, + )) orelse return null; + if (cell_cols == 0 or cell_rows == 0) return 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; - } + return .{ + .cell_x = cell_x, + .cell_y = cell_y, + .cell_cols = cell_cols, + .cell_rows = cell_rows, + .options = .{ + .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h }, + .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null, + .size = switch (fit) { + .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, + .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, + }, + }, }; - try std.testing.expectEqual(@as(usize, 32), painted); } fn kittyImageRepresentable(place: pardes.Placement) bool { @@ -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 @@ -2458,220 +2001,958 @@ const Shell = struct { tz_render.end(); } - fn postPresent(ctx: ?*anyopaque) void { + fn postPresent(ctx: ?*anyopaque) void { + const s = of(ctx); + if (s.term() != null) s.core.presented(); + tracy.frameMark(); + } + + fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + const s = of(ctx); + if (s.adoptions.take(pane)) |a| return s.takeShell(pane, a); + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = s.ptys[pane] != null; + const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { + if (running) return s.core.restartFailed(pane, err); + return s.core.shellFailed(pane, err); + }; + closePty(ctx, pane); // a shell still in the slot goes, reaped + s.gens[pane] +%= 1; + const command = if (s.core.panes[pane]) |pn| pn.command != null else false; + s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and asked now, before + // its chdir, it would answer this process's, a rename to undo. + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + if (s.threads_ok) { + if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + } + } + } + + /// An adopted shell, running already, as pane `pane`'s: told the size + /// twice (a size it never had, then the pane's), which makes it redraw. + fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { + closePty(s, pane); + s.gens[pane] +%= 1; + const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; + s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); + if (s.threads_ok) if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + }; + } + + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const s = of(ctx); + if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + } + + fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + const s = of(ctx); + if (s.ptys[pane]) |pt| { + const ws = host_io.ptyWinsize(s.core, cols, rows); + _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); + } + } + + fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + const s = of(ctx); + // A command whose exit is recorded is reaped: its group may be + // another's by now. + if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); + } + + /// The pane is gone: hang its pty up, which the kernel passes on to the + /// shell as SIGHUP, and retire the shell. Output still in flight + /// carries the old generation and is dropped. + fn closePty(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + var pt = s.ptys[pane] orelse return; + s.ptys[pane] = null; + s.gens[pane] +%= 1; + pt.reader.cancel(s.io) catch {}; + _ = libc.close(pt.file.handle); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); + } + + fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.ttyTaken(pt.pid, pt.file.handle); + } + + fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { + const s = of(ctx); + const pt = s.ptys[pane] orelse return null; + return host_io.foregroundName(pt.pid, pt.file.handle, buf); + } + + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *@This()) void { + host_io.takeExits(s.core, &s.ptys, s, closeWatched); + } + + fn closeWatched(s: *@This(), id: usize) void { + const pt = &(s.ptys[id] orelse return); + _ = libc.close(pt.file.handle); + s.ptys[id] = null; + } + + fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.killJob(pt.pid, pt.file.handle); + } + + fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { + const s = of(ctx); + host_io.writeFile(s.core, &s.watches, pane, path, bytes); + } + + fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { + host_io.writeDump(of(ctx).core, bytes); + } + + fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { + const s = of(ctx); + if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) + s.loop.postEvent(.files_changed) catch {}; + } + + fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { + const s = of(ctx); + if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on)) + s.loop.postEvent(.files_changed) catch {}; + } + + fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + host_io.dumpThemes(s.core, s.io, s.gpa, pane); + } + + fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { + const s = of(ctx); + // Detached, the session keeps it (a 9P read, a paste here). + const sc = s.term() orelse return s.core.fallback.setClipboard(text); + if (!sc.on) return s.core.fallback.setClipboard(text); + if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {}; + } + + fn readClipboard(ctx: ?*anyopaque) void { + const s = of(ctx); + const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + sc.vx.requestSystemClipboard(sc.tty.writer()) catch {}; + } + + fn openLink(_: ?*anyopaque, url: []const u8) void { + look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly + } + + fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { + const s = of(ctx); + if (!s.threads_ok) { + s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); + } + host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); + } + + fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { const s = of(ctx); - if (s.term() != null) s.core.presented(); - tracy.frameMark(); + s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); } - fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + fn pipe(ctx: ?*anyopaque, id: u32) void { const s = of(ctx); - if (s.adoptions.take(pane)) |a| return s.takeShell(pane, a); - // The new shell starts before a running one goes: one that cannot - // start leaves the running one be (pty/ctl's exec). - const running = s.ptys[pane] != null; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(pane, err); - return s.core.shellFailed(pane, err); - }; - closePty(ctx, pane); // a shell still in the slot goes, reaped - s.gens[pane] +%= 1; - const command = if (s.core.panes[pane]) |pn| pn.command != null else false; - s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - // Only a shell given no directory is asked where it is: one given a - // directory is named by it already (newShell), and asked now, before - // its chdir, it would answer this process's, a rename to undo. - if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - if (s.threads_ok) { - if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - } + if (!s.threads_ok) { + s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); + return s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); } + selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); } - /// An adopted shell, running already, as pane `pane`'s: told the size - /// twice (a size it never had, then the pane's), which makes it redraw. - fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { - closePty(s, pane); - s.gens[pane] +%= 1; - const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; - s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; - var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; - _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); - if (s.threads_ok) if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - }; + fn search(ctx: ?*anyopaque, gen: u32) void { + const s = of(ctx); + if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); + pardes.Stream.runHere(s.core, gen); } - fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { const s = of(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); + host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { + fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { + of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); + } + }.deliver); } - fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + /// The loop's queue waits for room (a wait the worker's cancel ends). + fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { const s = of(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); - } + s.loop.postEvent(.{ .search_rows = batch }) catch { + batch.deinit(s.gpa); + return false; + }; + return true; } - fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { const s = of(ctx); - // A command whose exit is recorded is reaped: its group may be - // another's by now. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); + var owned = response; + s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); } +}; - /// The pane is gone: hang its pty up, which the kernel passes on to the - /// shell as SIGHUP, and retire the shell. Output still in flight - /// carries the old generation and is dropped. - fn closePty(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - var pt = s.ptys[pane] orelse return; - s.ptys[pane] = null; - s.gens[pane] +%= 1; - pt.reader.cancel(s.io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); +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; + const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; + if (!posted) s.lsp_gpa.free(copy); +} + +fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { + if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { + while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; + return; + } + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [4096]u8 = undefined; + while (true) { + const n = file.readStreaming(io, &.{&buf}) catch break; + if (n == 0) break; + loop.postEvent(.files_changed) catch break; + } +} + +fn keepSignal(_: posix.SIG) callconv(.c) void {} + +/// A replica client's (`remote`): a hangup is its end, whoever sent it. +var hangup_quits = false; + +fn winchWatch(loop: *Loop) void { + var set = posix.sigemptyset(); + posix.sigaddset(&set, posix.SIG.WINCH); + if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); + while (true) { + var sig: c_int = 0; + if (libc.sigwait(&set, &sig) != 0) continue; + // The terminals are the loop's: it asks each its size, and takes a + // hangup as the end of the one that hung up. + const ev: Msg = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; + loop.postEvent(ev) catch {}; + } +} + +/// A wait with a timeout: post one `.wake` when it runs out. The wake joins +/// the input queue, so a key or a click that lands first is handled at once +/// instead of after a blind sleep; vaxis's queue has no timed wait. Each +/// request bumps `wake_gen`, which cuts short a sleep still timing an +/// earlier, longer request (an 800 ms linger interrupted by a key that +/// starts a 16 ms fall) and times the new one instead. +var wake_gen: std.atomic.Value(u32) = .init(0); +var wake_ms: std.atomic.Value(u32) = .init(0); + +fn requestWake(io: std.Io, ms: u32) void { + wake_ms.store(ms, .release); + _ = wake_gen.fetchAdd(1, .acq_rel); + io.futexWake(u32, &wake_gen.raw, 1); +} + +fn wakeWatch(io: std.Io, loop: *Loop) void { + var seen = wake_gen.load(.acquire); + while (true) { + // Asleep until a request. + while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen); + seen = wake_gen.load(.acquire); + if (timeWake(io, &seen)) loop.postEvent(.wake) catch {}; + } +} + +/// Sleep out the latest request; true when it ran its course, false when +/// none is pending. A newer request met on the way restarts the timing. +fn timeWake(io: std.Io, seen: *u32) bool { + while (true) { + const ms = wake_ms.load(.acquire); + const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms; + while (true) { + const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); + if (now >= deadline) return true; + io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{ + .raw = .fromNanoseconds(@intCast(deadline - now)), + .clock = .awake, + } }) catch {}; + const gen = wake_gen.load(.acquire); + if (gen != seen.*) { + seen.* = gen; + break; + } + } + } +} + +fn wakeFs(ctx: ?*anyopaque) void { + const loop: *Loop = @ptrCast(@alignCast(ctx.?)); + _ = loop.tryPostEvent(.fs_ready) catch {}; +} + +/// Each pane's reads posted and not yet taken in. Two at most: a flood the +/// loop cannot keep up with waits in its pty, not in the queue ahead of a +/// key and its echo (hundreds of 4 KB reads queued were half a second). +var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); + +/// A read of pane `id` taken in (or dropped): its reader may read on. Never +/// below zero, for an event no reader posted (a test's). +fn tookRead(io: std.Io, id: usize) void { + var queued = reads_queued[id].load(.acquire); + while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { + if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); + return; + }; +} + +fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; + read: while (true) { + while (true) { + const queued = reads_queued[id].load(.acquire); + if (queued < 2) break; + io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; + } + const n = pty.readStreaming(io, &.{&buf}) catch break; + if (n == 0) break; + const bytes = try gpa.dupe(u8, buf[0..n]); + _ = reads_queued[id].fetchAdd(1, .acq_rel); + loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { + tookRead(io, id); + gpa.free(bytes); + break; + }; } + _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; +} + +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, + } }; +} - fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.file.handle); - } +/// 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)); +} - fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { - const s = of(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.file.handle, buf); - } +/// 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 }, + }); +} - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *@This()) void { - host_io.takeExits(s.core, &s.ptys, s, closeWatched); +/// 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; +} - fn closeWatched(s: *@This(), id: usize) void { - const pt = &(s.ptys[id] orelse return); - _ = libc.close(pt.file.handle); - s.ptys[id] = null; - } +/// 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"); +} - fn killJob(ctx: ?*anyopaque, pane: u8) bool { - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.file.handle); +/// 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 writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { - const s = of(ctx); - host_io.writeFile(s.core, &s.watches, pane, path, bytes); +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), + }); + } } +} - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - host_io.writeDump(of(ctx).core, bytes); - } +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); +} - fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const s = of(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) - s.loop.postEvent(.files_changed) catch {}; +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; +} - fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = of(ctx); - if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on)) - s.loop.postEvent(.files_changed) catch {}; +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; +} - fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - host_io.dumpThemes(s.core, s.io, s.gpa, pane); +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); +} - fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { - const s = of(ctx); - // Detached, the session keeps it (a 9P read, a paste here). - const sc = s.term() orelse return s.core.fallback.setClipboard(text); - if (!sc.on) return s.core.fallback.setClipboard(text); - if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {}; - } +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)); +} - fn readClipboard(ctx: ?*anyopaque) void { - const s = of(ctx); - const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - sc.vx.requestSystemClipboard(sc.tty.writer()) catch {}; +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); } +} - fn openLink(_: ?*anyopaque, url: []const u8) void { - look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly - } +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); - fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { - const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); - } - host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); - } + // 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); - fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const s = of(ctx); - s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); - } + // 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); +} - fn pipe(ctx: ?*anyopaque, id: u32) void { - const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); - } - selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); - } +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); - fn search(ctx: ?*anyopaque, gen: u32) void { - const s = of(ctx); - if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); - pardes.Stream.runHere(s.core, gen); - } + // 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); - fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { - const s = of(ctx); - if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); - host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { - fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { - of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); - } - }.deliver); - } + height.at.?.h = 13; + try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); +} - /// The loop's queue waits for room (a wait the worker's cancel ends). - fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { - const s = of(ctx); - s.loop.postEvent(.{ .search_rows = batch }) catch { - batch.deinit(s.gpa); - return false; +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, }; - return true; - } - - fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { - const s = of(ctx); - var owned = response; - s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); - } -}; + 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; @@ -2712,140 +2993,51 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { 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; - const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; - if (!posted) s.lsp_gpa.free(copy); -} - -fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { - if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { - while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; - return; - } - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [4096]u8 = undefined; - while (true) { - const n = file.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - loop.postEvent(.files_changed) catch break; - } -} - -fn keepSignal(_: posix.SIG) callconv(.c) void {} - -/// A replica client's (`remote`): a hangup is its end, whoever sent it. -var hangup_quits = false; - -fn winchWatch(loop: *Loop) void { - var set = posix.sigemptyset(); - posix.sigaddset(&set, posix.SIG.WINCH); - if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); - while (true) { - var sig: c_int = 0; - if (libc.sigwait(&set, &sig) != 0) continue; - // The terminals are the loop's: it asks each its size, and takes a - // hangup as the end of the one that hung up. - const ev: Msg = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; - loop.postEvent(ev) catch {}; - } -} - -/// A wait with a timeout: post one `.wake` when it runs out. The wake joins -/// the input queue, so a key or a click that lands first is handled at once -/// instead of after a blind sleep; vaxis's queue has no timed wait. Each -/// request bumps `wake_gen`, which cuts short a sleep still timing an -/// earlier, longer request (an 800 ms linger interrupted by a key that -/// starts a 16 ms fall) and times the new one instead. -var wake_gen: std.atomic.Value(u32) = .init(0); -var wake_ms: std.atomic.Value(u32) = .init(0); - -fn requestWake(io: std.Io, ms: u32) void { - wake_ms.store(ms, .release); - _ = wake_gen.fetchAdd(1, .acq_rel); - io.futexWake(u32, &wake_gen.raw, 1); -} - -fn wakeWatch(io: std.Io, loop: *Loop) void { - var seen = wake_gen.load(.acquire); - while (true) { - // Asleep until a request. - while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen); - seen = wake_gen.load(.acquire); - if (timeWake(io, &seen)) loop.postEvent(.wake) catch {}; - } -} + 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); -/// Sleep out the latest request; true when it ran its course, false when -/// none is pending. A newer request met on the way restarts the timing. -fn timeWake(io: std.Io, seen: *u32) bool { - while (true) { - const ms = wake_ms.load(.acquire); - const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms; - while (true) { - const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - if (now >= deadline) return true; - io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{ - .raw = .fromNanoseconds(@intCast(deadline - now)), - .clock = .awake, - } }) catch {}; - const gen = wake_gen.load(.acquire); - if (gen != seen.*) { - seen.* = gen; - break; - } - } + 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); } } @@ -2872,51 +3064,6 @@ test "a short wake request cuts short a long one still sleeping" { 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 {}; -} - -/// Each pane's reads posted and not yet taken in. Two at most: a flood the -/// loop cannot keep up with waits in its pty, not in the queue ahead of a -/// key and its echo (hundreds of 4 KB reads queued were half a second). -var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); - -/// A read of pane `id` taken in (or dropped): its reader may read on. Never -/// below zero, for an event no reader posted (a test's). -fn tookRead(io: std.Io, id: usize) void { - var queued = reads_queued[id].load(.acquire); - while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { - if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); - return; - }; -} - -fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [0x10000]u8 = undefined; - read: while (true) { - while (true) { - const queued = reads_queued[id].load(.acquire); - if (queued < 2) break; - io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; - } - const n = pty.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - const bytes = try gpa.dupe(u8, buf[0..n]); - _ = reads_queued[id].fetchAdd(1, .acq_rel); - loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { - tookRead(io, id); - gpa.free(bytes); - break; - }; - } - _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; -} - -const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; - 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; -- cgit v1.3