diff options
Diffstat (limited to 'src/tty')
| -rw-r--r-- | src/tty/panel_compositor.zig | 706 | ||||
| -rw-r--r-- | src/tty/tty.zig | 4017 |
2 files changed, 0 insertions, 4723 deletions
diff --git a/src/tty/panel_compositor.zig b/src/tty/panel_compositor.zig deleted file mode 100644 index 67d3a6e6..00000000 --- a/src/tty/panel_compositor.zig +++ /dev/null @@ -1,706 +0,0 @@ -//! TTY implementation of panel transitions. -//! -//! The core publishes presentation cells plus POD tracks. It has already -//! composed PanelAscii because byte stepping is semantic, while this backend -//! copies the grid for geometry and dissolve operations. No terminal escape -//! trick or pixel assumption leaks into the core. - -const std = @import("std"); -const pardes = @import("../pardes.zig"); -const layout = @import("../layout.zig"); -const animation = @import("../animation.zig"); - -const Box = animation.Box; -const Track = animation.Track; - -/// Kitty placements cannot be resampled through the character-grid transform. -/// Keep their transmitted pixels cached, but omit the placement while its pane -/// geometry moves. Data effects animate changed grid cells in place and have -/// no honest old Kitty bitmap, so leaving an unchanged attachment canonical is -/// better than making it disappear for the whole reveal and pop back. -pub fn hidesAttachment(tracks: []const Track, serial: u32) bool { - for (tracks) |track| { - if (track.serial != serial or !track.active()) continue; - if (track.effect != .slide and track.effect != .zoom and track.effect != .vertical) continue; - // The last active sample is already the exact canonical frame. Place - // the image there too, rather than making it pop in one tick later. - if (track.frame + 1 < track.frames()) return true; - } - return false; -} - -/// Return `source` unchanged when idle, otherwise an arena-owned Surface whose -/// cells contain this frame's TTY presentation. Geometry exposed by a moving -/// panel uses the theme's page background when it has one; null deliberately -/// leaves the host terminal's default background showing. -pub fn compose( - arena: std.mem.Allocator, - source: *pardes.Surface, - tracks: []const Track, - theme_bg: ?[3]u8, -) !*pardes.Surface { - var active = false; - var noncanonical = false; - for (tracks) |track| { - if (!drawable(source, track)) continue; - active = true; - noncanonical = noncanonical or track.amount() < 1.0; - } - if (!active) return source; - // Every effect's last active sample is its exact canonical endpoint. Keep - // the real cursor and attachments in that sample instead of suppressing - // them for one extra frame that is otherwise pixel-identical. - if (!noncanonical) return source; - - const out = try arena.create(pardes.Surface); - out.* = source.*; - out.cells = try arena.dupe(pardes.Cell, source.cells); - // A cursor has no pane/phase record of its own. All native backends hide - // it for the short transition rather than disagreeing about whether it - // should move, stay static, or cover an overlapping opening pane. - out.cursor = null; - - // Clear every final geometry before drawing any presented geometry. If - // clear and draw are interleaved, a new panel can erase the old full-width - // panel that was deliberately drawn underneath it at frame zero. - for (tracks) |track| - if (drawable(source, track) and (track.effect == .slide or track.effect == .zoom)) - clearBox(out, track.to, theme_bg); - - // A vertical opener starts over the exact old pixels in its fixed target - // clip. Its new content then rises into that clip from below. Restore all - // bases before painting anything so an opener cannot erase an earlier - // moving panel merely because its pane slot sorts later. - for (tracks) |track| - if (drawable(source, track) and track.effect == .vertical and track.phase == .opening) - restorePrevious(out, source, track.contentBox()); - - // Stable layout motion first, newly opening panels above it, and closing - // tombstones last. A closing pane no longer owns input or canonical cells, - // but its frozen old content remains the top visual until it slides out. - for ([_]animation.Phase{ .moving, .opening, .closing }) |phase| { - for (tracks) |track| { - if (!drawable(source, track) or track.phase != phase) continue; - switch (track.effect) { - .off => {}, - .slide, .zoom => transform(out, source, track), - .dissolve => dissolve(out, source, track), - // Pardes core has already composed every character effect - // into source.cells — byte walks, glyph motion, and per-cell - // locks are semantic. TTY only owns cursor suppression here. - .ascii, .edges, .fall, .wave, .curtain, .scramble, .typewriter => {}, - .vertical => vertical(out, source, track), - } - } - } - return out; -} - -/// Content effects have no honest frame without the frozen old grid. In -/// production the core drops such tracks before publishing Surface; retain -/// this guard at the backend boundary so a partial/custom caller also snaps -/// to canonical content instead of manufacturing blanks. -fn drawable(source: *const pardes.Surface, track: Track) bool { - return track.active() and - (!track.effect.needsPreviousGrid() or source.hasPanelDiff()); -} - -fn transform(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { - const shown = track.presented(); - if (shown.w <= 0 or shown.h <= 0) return; - const dst = clipped(shown, out.cols, out.rows) orelse return; - var y = dst.y0; - while (y < dst.y1) : (y += 1) { - var x = dst.x0; - while (x < dst.x1) : (x += 1) { - // The core hit-tests cell CENTRES against this same half-open box. - // floor/ceil clipping includes boundary cells for iteration, but - // they are not visible unless their centre is actually inside. - // Test that containment before division: at large u16 grids f32 - // can round an inside right-edge ratio to exactly 1.0. - const cx = @as(f32, @floatFromInt(x)) + 0.5; - const cy = @as(f32, @floatFromInt(y)) + 0.5; - if (cx < shown.x or cx >= shown.x + shown.w or - cy < shown.y or cy >= shown.y + shown.h) continue; - const u = std.math.clamp((cx - shown.x) / shown.w, 0, 0.999_999); - const v = std.math.clamp((cy - shown.y) / shown.h, 0, 0.999_999); - const sx: i32 = @intFromFloat(@floor(track.to.x + u * track.to.w)); - const sy: i32 = @intFromFloat(@floor(track.to.y + v * track.to.h)); - if (sx < 0 or sy < 0 or sx >= source.cols or sy >= source.rows) continue; - out.at(x, y).* = source.cells[@as(usize, @intCast(sy)) * source.cols + @as(usize, @intCast(sx))]; - } - } -} - -fn dissolve(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { - const area = clipped(track.to, out.cols, out.rows) orelse return; - const amount = track.amount(); - var y = area.y0; - while (y < area.y1) : (y += 1) { - var x = area.x0; - while (x < area.x1) : (x += 1) { - if (!source.panelCellChanged(x, y)) continue; - if (animation.dissolveRevealed( - track.serial, - x - area.x0, - y - area.y0, - amount, - )) continue; - out.at(x, y).* = previousCell(source, x, y).*; - } - } -} - -fn previousCell(source: *const pardes.Surface, x: u16, y: u16) *const pardes.Cell { - std.debug.assert(source.hasPanelDiff()); - return &source.previous_cells[@as(usize, y) * source.cols + x]; -} - -fn restorePrevious(out: *pardes.Surface, source: *const pardes.Surface, box: Box) void { - const area = clipped(box, out.cols, out.rows) orelse return; - var y = area.y0; - while (y < area.y1) : (y += 1) { - var x = area.x0; - while (x < area.x1) : (x += 1) - out.at(x, y).* = previousCell(source, x, y).*; - } -} - -fn vertical(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { - const cells = if (track.phase == .closing) source.previous_cells else source.cells; - transformClipped(out, source.cols, source.rows, cells, track, track.contentBox()); -} - -/// Translate one old/new canonical panel through its fixed lifecycle clip. -/// Sampling is always relative to contentBox: an opener reads its new target, -/// while a closer reads the old box retained after that pane was destroyed. -fn transformClipped( - out: *pardes.Surface, - source_cols: u16, - source_rows: u16, - cells: []const pardes.Cell, - track: Track, - clip: Box, -) void { - const shown = track.presented(); - if (shown.w <= 0 or shown.h <= 0) return; - const dst = clipped(shown, out.cols, out.rows) orelse return; - const content = track.contentBox(); - var y = dst.y0; - while (y < dst.y1) : (y += 1) { - var x = dst.x0; - while (x < dst.x1) : (x += 1) { - const cx = @as(f32, @floatFromInt(x)) + 0.5; - const cy = @as(f32, @floatFromInt(y)) + 0.5; - if (cx < shown.x or cx >= shown.x + shown.w or - cy < shown.y or cy >= shown.y + shown.h or - cx < clip.x or cx >= clip.x + clip.w or - cy < clip.y or cy >= clip.y + clip.h) continue; - const u = std.math.clamp((cx - shown.x) / shown.w, 0, 0.999_999); - const v = std.math.clamp((cy - shown.y) / shown.h, 0, 0.999_999); - const sx: i32 = @intFromFloat(@floor(content.x + u * content.w)); - const sy: i32 = @intFromFloat(@floor(content.y + v * content.h)); - if (sx < 0 or sy < 0 or sx >= source_cols or sy >= source_rows) continue; - out.at(x, y).* = cells[@as(usize, @intCast(sy)) * source_cols + @as(usize, @intCast(sx))]; - } - } -} - -fn clearBox(surface: *pardes.Surface, box: Box, theme_bg: ?[3]u8) void { - const area = clipped(box, surface.cols, surface.rows) orelse return; - var blank: pardes.Cell = .{}; - if (theme_bg) |rgb| { - blank.default = false; - blank.style.bg = .{ .rgb = rgb }; - } - var y = area.y0; - while (y < area.y1) : (y += 1) { - var x = area.x0; - while (x < area.x1) : (x += 1) surface.at(x, y).* = blank; - } -} - -const GridBox = struct { x0: u16, y0: u16, x1: u16, y1: u16 }; - -fn clipped(box: Box, cols: u16, rows: u16) ?GridBox { - const x0: i32 = @intFromFloat(@floor(box.x)); - const y0: i32 = @intFromFloat(@floor(box.y)); - const x1: i32 = @intFromFloat(@ceil(box.x + box.w)); - const y1: i32 = @intFromFloat(@ceil(box.y + box.h)); - const area: GridBox = .{ - .x0 = @intCast(std.math.clamp(x0, 0, @as(i32, cols))), - .y0 = @intCast(std.math.clamp(y0, 0, @as(i32, rows))), - .x1 = @intCast(std.math.clamp(x1, 0, @as(i32, cols))), - .y1 = @intCast(std.math.clamp(y1, 0, @as(i32, rows))), - }; - return if (area.x0 < area.x1 and area.y0 < area.y1) area else null; -} - -test "TTY consumes core-composed ASCII cells without reinterpreting glyphs" { - var cells: [8]pardes.Cell = @splat(.{}); - var previous: [8]pardes.Cell = @splat(.{}); - const diffs: [8]pardes.PanelCellDiff = @splat(.visual); - for (&cells) |*cell| { - cell.text[0] = 'X'; - cell.len = 1; - cell.default = false; - } - for (&previous) |*cell| { - cell.text[0] = 'O'; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ - .cols = 4, - .rows = 2, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 9, - .effect = .ascii, - .frame = 0, - .from = .{ .w = 4, .h = 2 }, - .to = .{ .w = 4, .h = 2 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expect(animated != &surface); - try std.testing.expectEqualStrings("X", surface.at(0, 0).grapheme()); - for (animated.cells) |cell| try std.testing.expectEqualStrings("X", cell.grapheme()); -} - -test "dissolve changes only diff cells from old to new" { - var cells: [2]pardes.Cell = @splat(.{}); - var previous: [2]pardes.Cell = @splat(.{}); - for (&cells, "NU") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - for (&previous, "OU") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs = [_]pardes.PanelCellDiff{ .{ .ascii = .{ .from = 'O', .to = 'N' } }, .unchanged }; - var surface: pardes.Surface = .{ - .cols = 2, - .rows = 1, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var track: Track = .{ - .serial = 1, - .effect = .dissolve, - .from = .{ .w = 2, .h = 1 }, - .to = .{ .w = 2, .h = 1 }, - }; - - const first = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("O", first.at(0, 0).grapheme()); - try std.testing.expectEqual(cells[1], first.at(1, 0).*); - - _ = arena.reset(.retain_capacity); - track.frame = track.effect.frames() - 1; - const final = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(cells[0], final.at(0, 0).*); - try std.testing.expectEqual(cells[1], final.at(1, 0).*); -} - -test "TTY content effects never touch cells outside the published diff" { - var cells: [4]pardes.Cell = @splat(.{}); - var previous: [4]pardes.Cell = @splat(.{}); - for (&cells, "NUQV") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - // Deliberately disagree even where the mask says unchanged. This makes - // the test prove that the compositor obeys the core cell diff rather than - // merely appearing correct because old and new happened to match there. - for (&previous, "OXRY") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs = [_]pardes.PanelCellDiff{ .visual, .unchanged, .visual, .unchanged }; - var surface: pardes.Surface = .{ - .cols = 4, - .rows = 1, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - - for ([_]animation.Transition{ .ascii, .dissolve }) |effect| { - const track: Track = .{ - .serial = 17, - .effect = effect, - .from = .{ .w = 4, .h = 1 }, - .to = .{ .w = 4, .h = 1 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(cells[1], animated.at(1, 0).*); - try std.testing.expectEqual(cells[3], animated.at(3, 0).*); - _ = arena.reset(.retain_capacity); - } -} - -test "content transition without a diff snaps to canonical surface" { - var cells = [_]pardes.Cell{.{}}; - cells[0].text[0] = 'N'; - cells[0].default = false; - var surface: pardes.Surface = .{ - .cols = 1, - .rows = 1, - .cells = &cells, - .cursor = .{ .x = 0, .y = 0 }, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - - for ([_]animation.Transition{ .dissolve, .ascii, .vertical }) |effect| { - const track: Track = .{ - .effect = effect, - .phase = .opening, - .from = .{ .y = 1, .w = 1, .h = 1 }, - .to = .{ .w = 1, .h = 1 }, - }; - try std.testing.expectEqual(&surface, try compose(arena.allocator(), &surface, &.{track}, null)); - } -} - -test "exact transition endpoint preserves the canonical cursor" { - var cells = [_]pardes.Cell{.{}}; - var previous = cells; - const diffs = [_]pardes.PanelCellDiff{.visual}; - var surface: pardes.Surface = .{ - .cols = 1, - .rows = 1, - .cells = &cells, - .cursor = .{ .x = 0, .y = 0 }, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - const track: Track = .{ - .effect = .ascii, - .frame = animation.Transition.ascii.frames() - 1, - .from = .{ .w = 1, .h = 1 }, - .to = .{ .w = 1, .h = 1 }, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - - const result = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(&surface, result); - try std.testing.expect(result.cursor != null); -} - -test "vertical opening rises through a fixed old-grid clip" { - var cells: [12]pardes.Cell = @splat(.{}); - var previous: [12]pardes.Cell = @splat(.{}); - for (&cells, "aaabbbcccddd") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - for (&previous, "000111222333") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs: [12]pardes.PanelCellDiff = @splat(.visual); - var surface: pardes.Surface = .{ - .cols = 3, - .rows = 4, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const target: Box = .{ .y = 1, .w = 3, .h = 2 }; - var track: Track = .{ - .serial = 5, - .phase = .opening, - .effect = .vertical, - .from = animation.openingBox(.vertical, target, 3), - .to = target, - }; - - const first = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("1", first.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("2", first.at(0, 2).grapheme()); - try std.testing.expectEqualStrings("a", first.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("d", first.at(0, 3).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = 2; - const entering = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("1", entering.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("b", entering.at(0, 2).grapheme()); - try std.testing.expectEqualStrings("a", entering.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("d", entering.at(0, 3).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = track.effect.frames() - 1; - const final = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("b", final.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("c", final.at(0, 2).grapheme()); -} - -test "vertical closing drops frozen content over canonical cells" { - var cells: [12]pardes.Cell = @splat(.{}); - var previous: [12]pardes.Cell = @splat(.{}); - for (&cells, "aaabbbcccddd") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - for (&previous, "000111222333") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs: [12]pardes.PanelCellDiff = @splat(.visual); - var surface: pardes.Surface = .{ - .cols = 3, - .rows = 4, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const old_box: Box = .{ .y = 1, .w = 3, .h = 2 }; - var track: Track = .{ - .serial = 5, - .phase = .closing, - .effect = .vertical, - .from = old_box, - .to = animation.closingBox(.vertical, old_box), - }; - - const first = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("1", first.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("2", first.at(0, 2).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = 8; - const leaving = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("b", leaving.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("1", leaving.at(0, 2).grapheme()); - try std.testing.expectEqualStrings("a", leaving.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("d", leaving.at(0, 3).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = track.effect.frames() - 1; - const final = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(cells[3], final.at(0, 1).*); - try std.testing.expectEqual(cells[6], final.at(0, 2).*); -} - -test "closing content paints after opening content regardless of track order" { - var cells = [_]pardes.Cell{.{}}; - var previous = [_]pardes.Cell{.{}}; - cells[0].text[0] = 'N'; - cells[0].default = false; - previous[0].text[0] = 'O'; - previous[0].default = false; - const diffs = [_]pardes.PanelCellDiff{.visual}; - var surface: pardes.Surface = .{ - .cols = 1, - .rows = 1, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const box: Box = .{ .w = 1, .h = 1 }; - const closing: Track = .{ - .serial = 1, - .phase = .closing, - .effect = .vertical, - .from = box, - .to = animation.closingBox(.vertical, box), - }; - const opening: Track = .{ - .serial = 2, - .phase = .opening, - .effect = .ascii, - .frame = animation.Transition.ascii.frames() - 1, - .from = box, - .to = box, - }; - - const animated = try compose(arena.allocator(), &surface, &.{ closing, opening }, null); - try std.testing.expectEqualStrings("O", animated.at(0, 0).grapheme()); -} - -test "opening panel cannot erase an existing panel drawn underneath" { - var cells: [8]pardes.Cell = @splat(.{}); - for (&cells, 0..) |*cell, x| { - cell.text[0] = if (x < 4) 'A' else 'B'; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ .cols = 8, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const tracks = [_]Track{ - .{ - .serial = 1, - .phase = .moving, - .effect = .slide, - .from = .{ .w = 8, .h = 1 }, - .to = .{ .w = 4, .h = 1 }, - }, - .{ - .serial = 2, - .phase = .opening, - .effect = .slide, - .from = .{ .x = 8, .w = 4, .h = 1 }, - .to = .{ .x = 4, .w = 4, .h = 1 }, - }, - }; - const animated = try compose(arena.allocator(), &surface, &tracks, null); - try std.testing.expectEqualStrings("A", animated.at(7, 0).grapheme()); -} - -test "geometry gap is a blank painted in an explicit theme background" { - var cells: [4]pardes.Cell = @splat(.{}); - for (&cells, "ABCD") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - cell.style = .{ - .fg = .{ .rgb = .{ 220, 210, 200 } }, - .bg = .{ .rgb = .{ 30, 20, 10 } }, - .bold = true, - .font_role = .tagline, - }; - } - var surface: pardes.Surface = .{ .cols = 4, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 1, - .effect = .slide, - .from = .{ .x = 2, .w = 2, .h = 1 }, - .to = .{ .w = 4, .h = 1 }, - }; - const page_bg = [3]u8{ 248, 244, 232 }; - const animated = try compose(arena.allocator(), &surface, &.{track}, page_bg); - - const gap = animated.at(0, 0); - try std.testing.expect(!gap.default); - try std.testing.expectEqualStrings(" ", gap.grapheme()); - try std.testing.expectEqual(pardes.Color{ .rgb = page_bg }, gap.style.bg); - try std.testing.expectEqual(pardes.Color.default, gap.style.fg); - try std.testing.expect(!gap.style.bold); - try std.testing.expectEqual(pardes.FontRole.body, gap.style.font_role); - // The clear supplies only exposed geometry. Cells sampled from the moving - // panel retain all canonical content and style fields byte-for-byte. - try std.testing.expectEqual(cells[1], animated.at(2, 0).*); -} - -test "geometry gap stays terminal-default for a transparent theme" { - var cells: [2]pardes.Cell = @splat(.{}); - for (&cells, "AB") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ .cols = 2, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 1, - .effect = .slide, - .from = .{ .x = 1, .w = 1, .h = 1 }, - .to = .{ .w = 2, .h = 1 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - - const gap = animated.at(0, 0); - try std.testing.expect(gap.default); - try std.testing.expectEqualStrings(" ", gap.grapheme()); - try std.testing.expectEqual(pardes.Color.default, gap.style.bg); -} - -test "fractional geometry draws exactly the cell centres core can hit" { - var cells: [3]pardes.Cell = @splat(.{}); - for (&cells, "ABC") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ .cols = 3, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 1, - .effect = .slide, - .from = .{ .x = 0.9, .w = 1, .h = 1 }, - .to = .{ .x = 0, .w = 1, .h = 1 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - // Cell 0 lies in floor/ceil iteration bounds, but its centre (0.5) is - // outside [0.9, 1.9); cell 1 is the only presented/hit-testable cell. - try std.testing.expectEqualStrings(" ", animated.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("A", animated.at(1, 0).grapheme()); -} - -test "large-grid right edge uses containment before rounded ratio" { - const cols = std.math.maxInt(u16); - const source_cells = try std.testing.allocator.alloc(pardes.Cell, cols); - defer std.testing.allocator.free(source_cells); - const output_cells = try std.testing.allocator.alloc(pardes.Cell, cols); - defer std.testing.allocator.free(output_cells); - @memset(source_cells, .{}); - @memset(output_cells, .{}); - for (source_cells) |*cell| { - cell.text[0] = 'X'; - cell.len = 1; - cell.default = false; - } - var source: pardes.Surface = .{ .cols = cols, .rows = 1, .cells = source_cells }; - var output: pardes.Surface = .{ .cols = cols, .rows = 1, .cells = output_cells }; - const track: Track = .{ - .serial = 1, - .effect = .zoom, - .frame = 8, - .from = .{ .x = 56_796, .w = 8_299, .h = 1 }, - .to = .{ .x = 556, .w = 63_483, .h = 1 }, - }; - const shown = track.presented(); - try std.testing.expect(@as(f32, 63_935.5) < shown.x + shown.w); - transform(&output, &source, track); - try std.testing.expectEqualStrings("X", output.at(63_935, 0).grapheme()); -} - -test "active panel transition hides only its own native attachment" { - const tracks = [_]Track{ - .{ .serial = 41, .effect = .slide, .frame = 0 }, - .{ .serial = 42, .effect = .ascii, .frame = 0 }, - .{ .serial = 43, .effect = .zoom, .frame = animation.Transition.zoom.frames() - 1 }, - .{ .serial = 44, .effect = .zoom, .frame = animation.Transition.zoom.frames() }, - .{ .serial = 45, .phase = .opening, .effect = .vertical, .frame = 0 }, - }; - - try std.testing.expect(hidesAttachment(&tracks, 41)); - try std.testing.expect(!hidesAttachment(&tracks, 42)); - try std.testing.expect(!hidesAttachment(&tracks, 43)); - try std.testing.expect(!hidesAttachment(&tracks, 44)); - try std.testing.expect(hidesAttachment(&tracks, 45)); - try std.testing.expect(!hidesAttachment(&tracks, 46)); -} diff --git a/src/tty/tty.zig b/src/tty/tty.zig deleted file mode 100644 index 4c054021..00000000 --- a/src/tty/tty.zig +++ /dev/null @@ -1,4017 +0,0 @@ -const filesystem = @import("../fs.zig"); -const std = @import("std"); -const builtin = @import("builtin"); -const posix = std.posix; -const libc = std.c; -const vaxis = @import("vaxis"); -const pardes = @import("../pardes.zig"); -const vaxis_input = @import("../vaxis_input.zig"); -const dump = @import("../dump.zig"); -const tracy = @import("../tracy.zig"); -const look = @import("../look.zig"); -const message = pardes.Messages.Message; -const file_watch = @import("../file_watch.zig"); -const selection_pipe = @import("../selection_pipe.zig"); -const ninep_io = @import("../9p_io.zig"); -const panel_compositor = @import("panel_compositor.zig"); -const daemon = @import("../daemon.zig"); -const host_io = @import("../host_io.zig"); -const upgrade = @import("../upgrade.zig"); -const replica = @import("../replica.zig"); -const wire = @import("../detached/wire.zig"); - -extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; - -const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); - -/// What a terminal's input reader keeps, one a terminal (views.zig): its -/// graphemes, the frame it waits on the answer to, the shm probe, and the -/// view its input is. -const Feed = struct { - view: u8 = 0, - cache: vaxis.GraphemeCache = .{}, - ack: FrameAck = .{}, - /// The terminal answered the shared-memory probe (`kittyShmProbe`): it - /// can read a raster from a POSIX shm object, so a page costs a name on - /// the wire instead of its whole base64 body. Set by the input reader, - /// which sees the reply before vaxis' parser swallows every graphics APC - /// alike. - shm: std.atomic.Value(bool) = .init(false), - /// Only a reply that arrives while the probe is out counts. The id is - /// one vaxis' own image numbering (1, 2, ...) never reaches, because a - /// terminal answers every transmission `i=<id>;OK` and one of those must - /// not pass. - shm_probing: std.atomic.Value(bool) = .init(false), -}; - -/// A terminal's input onto the loop's queue, as its view's: a `from` goes -/// ahead of it whenever another terminal posted last. With one terminal -/// none ever does. -const Poster = struct { - loop: *Loop, - view: u8, - var lock: std.Io.Mutex = .init; - var last: u8 = 0; - - pub fn postEvent(p: Poster, ev: @TypeOf(Command.value)) !void { - lock.lockUncancelable(p.loop.io); - defer lock.unlock(p.loop.io); - if (last != p.view) { - try p.loop.postEvent(.{ .from = p.view }); - last = p.view; - } - try p.loop.postEvent(ev); - } -}; -const kitty_shm_probe_id = 0x7fff_fff1; -var kitty_shm_serial: u32 = 0; -/// Transmissions an unread shm segment outlives before it is removed. -const kitty_shm_window = 64; - -fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { - return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); -} - -/// A terminal unlinks what it reads; whatever it never read (the probe -/// unanswered, a transmission lost with the terminal) is ours to remove. -fn unlinkKittyShm() void { - var name_buf: [64]u8 = undefined; - var n: u32 = 0; - while (n <= kitty_shm_serial) : (n += 1) { - if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} - } -} - -/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading. -fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { - const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600)); - if (fd < 0) return false; - defer _ = libc.close(fd); - if (libc.ftruncate(fd, @intCast(bytes.len)) != 0) { - _ = libc.shm_unlink(name); - return false; - } - var off: usize = 0; - while (off < bytes.len) { - const n = libc.write(fd, bytes[off..].ptr, bytes.len - off); - if (n <= 0) { - _ = libc.shm_unlink(name); - return false; - } - off += @intCast(n); - } - return true; -} - -/// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A -/// remote terminal cannot see our shm and answers an error (or nothing). -fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { - var buf: [64]u8 = undefined; - const name = kittyShmName(&buf, 0) catch return; - if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; - var b64: [64]u8 = undefined; - const enc = std.base64.standard.Encoder.encode(&b64, name); - feed.shm_probing.store(true, .release); - w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; - w.flush() catch {}; -} - -pub const Command = struct { - pub var value: union(enum) { - nop, - /// The terminal's input ended: its end of file, a hangup. A session - /// a daemon keeps carries on detached; any other ends. - quit, - /// A terminal for this detached session, and its stub's pipe - /// (daemon.Note.attach). - attach: struct { tty: posix.fd_t, stub: posix.fd_t }, - /// A shell a dead session left, its pty's master (daemon.Note.adopted). - adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, - /// A timed wait ran out: the core's next wake has come. - wake, - /// The input after this is the terminal of this view's (Poster). - from: u8, - /// A SIGWINCH: a terminal changed size (Shell.winched). - winched, - /// A SIGHUP: the session's own terminal hung up. - hangup, - key_press: vaxis.Key, - pty_read: struct { id: usize, gen: u32, bytes: []u8 }, - pty_eof: struct { id: usize, gen: u32 }, - winsize: vaxis.Winsize, - mouse: vaxis.Mouse, - focus_in, - focus_out, - paste: []const u8, - paste_start, - paste_end, - lsp_done: struct { id: u32, rows: ?[]u8 }, - lsp_status: []u8, - pipe_done: selection_pipe.Response, - /// A streaming search's rows (pardes.Stream). - search_rows: pardes.Stream.Batch, - files_changed, - fs_ready, - /// A replica's connection, handed over by the daemon (Peers). - replica: daemon.Joining, - /// A replica's reader posted: the step boundary takes it in. - replica_mail, - /// A replica client's: what the session streamed (replica.Link). - said: replica.Said, - link_gone, - } = .nop; -}; -const Loop = vaxis.Loop(@TypeOf(Command.value)); - -fn startInput(loop: *Loop, sc: *Screen) !void { - if (comptime builtin.os.tag == .windows) return loop.start(); - if (sc.thread != null) return; - sc.thread = try loop.io.concurrent(inputThread, .{ loop, sc }); -} - -fn stopInput(io: std.Io, thread: *?std.Io.Future(void)) void { - if (thread.*) |*t| { - t.cancel(io); - thread.* = null; - } -} - -fn inputThread(loop: *Loop, sc: *Screen) void { - // vaxis's test terminal reads nothing off Linux: it has no read at all. - if (comptime !@hasDecl(vaxis.Tty, "read")) return; - inputReader(loop, &sc.tty, &sc.vx, &sc.feed); -} - -fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { - readInput(loop, tty, vx, feed) catch |err| { - if (err == error.Canceled) return; - std.log.err("terminal input: {s}", .{@errorName(err)}); - }; - (Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {}; -} - -fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { - const post: Poster = .{ .loop = loop, .view = feed.view }; - try post.postEvent(.{ .winsize = try tty.getWinsize() }); - var parser: vaxis.Parser = .{}; - var buf: [1024]u8 = undefined; - var carried: usize = 0; - while (true) { // stopInput cancels the task; the read then fails with Canceled - if (carried == buf.len) return error.InputSequenceTooLong; - const received = try tty.read(buf[carried..]); - if (received == 0) return; - // The terminal's answers to frames (FrameAck) come out first, - // wherever they sit: never events, and never glued to a key (an - // Escape pressed just before one would read as Alt on it). - const end = feed.ack.take(buf[0 .. carried + received], loop); - if (end == 0) { - carried = 0; - continue; - } - if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { - feed.shm_probing.store(false, .release); - feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); - // Answered either way: a terminal that could not read it left it. - var name_buf: [64]u8 = undefined; - if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} - }; - var parse_end = end; - var lead = end; - while (lead > 0 and buf[lead - 1] & 0xc0 == 0x80) lead -= 1; - if (lead > 0) { - const scalar_len = std.unicode.utf8ByteSequenceLength(buf[lead - 1]) catch 1; - if (scalar_len > end - (lead - 1)) parse_end = lead - 1; - } - var consumed: usize = 0; - // A read that is one ESC and nothing else is the Escape key: a - // terminal writes each key's sequence whole and ssh carries each of - // its writes whole, so no sequence arrives cut right after its ESC. - // Waiting on it cost every Escape press 50 ms on a legacy terminal - // (tmux, most ssh sessions), and 1 s before kitty's flags were on. - // (A terminal's answer to a frame is one write too: FrameAck.) - var waited = carried == 0 and end == 1; - while (consumed < parse_end) { - // A lone ESC that ends a longer read is the Escape key, or the - // first byte of a sequence whose rest the read boundary held - // back (an ssh packet, a busy link), which parsed now left the - // rest to be typed as text. Wait a moment for more. Under the - // kitty keyboard protocol Escape is `CSI 27 u`, so there the ESC - // can only start a sequence and the wait can be long. - const rest = buf[consumed..parse_end]; - // A frame's answer cut short by the read waits for its rest. - if (parse_end == end and rest.len > 1 and rest.len < FrameAck.answer.len and - std.mem.startsWith(u8, FrameAck.answer, rest)) break; - if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) { - waited = true; - if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break; - } - const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator); - if (result.n == 0) break; - consumed += result.n; - // A modifier pressed on its own, which the kitty keyboard - // protocol reports: pardes binds none, it would break a pending - // chord, and a shell pane was typed its private-use code. - if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue; - if (result.event) |event| - vaxis.loop.handleEventGeneric(post, vx, &feed.cache, @TypeOf(Command.value), event, vx.opts.system_clipboard_allocator) catch |err| { - if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); - return err; - }; - // The last answer to the startup queries is no event of its - // own: wake the loop so it takes the capabilities up (pollFrame) - // now. Left to the first key, that key paid for the full redraw - // they cost, and kitty's keys came in the legacy way till then. - if (result.event) |event| if (event == .cap_da1) { - _ = loop.tryPostEvent(.nop) catch {}; - }; - } - carried = end - consumed; - std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); - } -} - -/// One frame in flight at most. Each frame the tty draws ends with a device -/// status request (`CSI 5 n`), and no other frame is drawn until the -/// terminal's `CSI 0 n` comes back: over ssh the frames a burst of scrolling -/// or typing would queue behind each other (sshd's window holds megabytes) -/// are never drawn, and the burst ends one frame and one round trip after -/// its last input. On a local terminal the answer is back in well under a -/// millisecond. A terminal that never answers turns this off for good after -/// `timeout_ns`. -const FrameAck = struct { - const request = "\x1b[5n"; - const answer = "\x1b[0n"; - const timeout_ns: u64 = std.time.ns_per_s; - waiting: std.atomic.Value(bool) = .init(false), - off: std.atomic.Value(bool) = .init(false), - /// When the request went out (the loop's thread only). - sent_ns: u64 = 0, - - /// Take every answer out of `bytes`, closing up the rest; the new - /// length. The loop is woken for the frame that waited on one. - fn take(a: *FrameAck, bytes: []u8, loop: *Loop) usize { - var len = bytes.len; - var found = false; - while (std.mem.indexOf(u8, bytes[0..len], answer)) |at| { - std.mem.copyForwards(u8, bytes[at..], bytes[at + answer.len .. len]); - len -= answer.len; - found = true; - } - if (found and a.waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; - return len; - } - - /// Whether a new frame must wait (and the loop has a wake at the - /// timeout); past the timeout the terminal is taken to never answer. - fn holds(a: *FrameAck, now_ns: u64, io: std.Io) bool { - if (a.off.load(.acquire) or !a.waiting.load(.acquire)) return false; - const waited_ns = now_ns -| a.sent_ns; - if (waited_ns >= timeout_ns) { - a.off.store(true, .release); - a.waiting.store(false, .release); - return false; - } - requestWake(io, @intCast((timeout_ns - waited_ns + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); - return true; - } - - /// After a frame that wrote something: ask for the answer. - fn ask(a: *FrameAck, w: *std.Io.Writer, now_ns: u64) void { - if (a.off.load(.acquire)) return; - // Waiting before the request goes: a local terminal can answer - // before the write returns, and an answer nobody waited for is lost. - a.sent_ns = now_ns; - a.waiting.store(true, .release); - w.writeAll(request) catch return a.waiting.store(false, .release); - w.flush() catch return a.waiting.store(false, .release); - } -}; - -/// Whether more input is readable within `ms`, polled in short slices so -/// that a cancel of the input thread is still seen. A test reader answers -/// for itself. -fn inputFollows(tty: anytype, io: std.Io, ms: u32) !bool { - if (@hasDecl(@TypeOf(tty.*), "inputFollows")) return tty.inputFollows(ms); - const handle = if (@TypeOf(tty.fd) == std.Io.File) tty.fd.handle else tty.fd; - var fds = [_]posix.pollfd{.{ .fd = handle, .events = posix.POLL.IN, .revents = 0 }}; - var left = ms; - while (left > 0) : (left -|= 10) { - try io.checkCancel(); - if (try posix.poll(&fds, @intCast(@min(left, 10))) > 0) return true; - } - return false; -} - -test "terminal input preserves fragmented keys queries paste and text after EOF" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - vx.queries_done.store(false, .unordered); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - var reader: Reader = .{ .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(&loop, &reader, &vx, &feed); - try std.testing.expect(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 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(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" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - vx.queries_done.store(false, .unordered); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - var reader: Reader = .{ - .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(&loop, &reader, &vx, &feed); - try std.testing.expect(vx.queries_done.load(.unordered)); - try std.testing.expect(vx.caps.kitty_graphics); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var alt_up = false; - var clicked = false; - while (try 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" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - // Two reads with `gap_ms` between them, as an ssh link delivers a - // sequence cut across two packets. - const Reader = struct { - parts: [2][]const u8, - gap_ms: u32, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), ms: u32) bool { - return self.next < self.parts.len and self.gap_ms <= ms; - } - fn read(self: *@This(), buf: []u8) !usize { - while (self.next < self.parts.len) { - const part = self.parts[self.next]; - self.next += 1; - if (part.len == 0) continue; - @memcpy(buf[0..part.len], part); - return part.len; - } - return 0; - } - /// What the loop was handed, one line per event. - fn events(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| { - vx.caps.kitty_keyboard = case.kitty; - const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); - defer gpa.free(all); - var one: Reader = .{ .parts = .{ all, "" }, .gap_ms = 0 }; - try readInput(&loop, &one, &vx, &feed); - try Reader.events(&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; - var two: Reader = .{ .parts = .{ all[0..cut], all[cut..] }, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&loop, &two, &vx, &feed); - try Reader.events(&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; - }; - } - } - vx.caps.kitty_keyboard = false; -} - -test "an ESC read by itself is the Escape key at once" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - // More always follows at once: a reader that waited on the ESC would - // take `j` for the rest of its sequence (Alt-j). - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - asked: bool = false, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - self.asked = true; - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - for ([_]bool{ false, true }) |kitty| { - vx.caps.kitty_keyboard = kitty; - var reader: Reader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&loop, &reader, &vx, &feed); - try std.testing.expect(!reader.asked); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); - const escape = (try loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - const j = (try 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 loop.tryEvent() == null); - } - vx.caps.kitty_keyboard = false; -} - -test "a frame's answer is taken wherever the reads cut it, and never typed" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: [2][]const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - while (self.next < self.parts.len) { - const part = self.parts[self.next]; - self.next += 1; - if (part.len == 0) continue; - @memcpy(buf[0..part.len], part); - return part.len; - } - return 0; - } - }; - const all = "x" ++ FrameAck.answer ++ "y"; - defer feed.ack.waiting.store(false, .release); - for (0..all.len) |cut| { - feed.ack.waiting.store(true, .release); - var reader: Reader = .{ .parts = .{ all[0..cut], all[cut..] } }; - try readInput(&loop, &reader, &vx, &feed); - try std.testing.expect(!feed.ack.waiting.load(.acquire)); - var typed: std.ArrayList(u8) = .empty; - defer typed.deinit(gpa); - var woke = false; - while (try 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. - feed.ack.waiting.store(true, .release); - var glued: Reader = .{ .parts = .{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&loop, &glued, &vx, &feed); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); - try std.testing.expectEqual(.nop, std.meta.activeTag((try loop.tryEvent()).?)); - const escape = (try 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 loop.tryEvent()).?.key_press.codepoint); - try std.testing.expect(try 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" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - 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 tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &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(@TypeOf(Command.value)) = 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 { - file: std.Io.File, - pid: posix.pid_t, - reader: std.Io.Future(anyerror!void), - /// A command pane's child, watched to its exit (host_io.watchExit); - /// the pty stays open until both its end of file and its exit. - cmd: host_io.CommandWatch = .{}, -}; - -/// A watched child exited: wake the loop, which takes it (`takeExits`). -fn wakeForExit(ctx: ?*anyopaque) void { - const loop: *Loop = @ptrCast(@alignCast(ctx.?)); - _ = loop.tryPostEvent(.nop) catch {}; -} - -const KittyPlacement = struct { - cell_x: u16, - cell_y: u16, - cell_cols: u16, - cell_rows: u16, - options: vaxis.Image.DrawOptions, -}; - -fn terminalCellPixels(total_pixels: u16, cells: u16, fallback: u32) u32 { - if (total_pixels == 0 or cells == 0) return fallback; - return @max(1, @as(u32, total_pixels) / cells); -} - -fn updateCoreTerminalSize(core: *pardes.Pardes, cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) void { - core.update(.{ .resize = terminalSize(cols, rows, pixel_w, pixel_h) }); -} - -fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(pardes.Event, "resize") { - return .{ - .cols = cols, - .rows = rows, - .cell_pixels = .{ - .w = @intCast(terminalCellPixels(pixel_w, cols, 8)), - .h = @intCast(terminalCellPixels(pixel_h, rows, 16)), - }, - }; -} - -/// A terminal pane's image fragment (`native.exact`): its `src` into its -/// `dst`, inside one cell row. Kitty scales a source rectangle to whole -/// cells, so the source is trimmed to the cells' scale rather than the -/// picture stretched: a fragment loses under a cell at its right edge. -/// A full row is declared one row high; a part of one (an image's top or -/// bottom edge) only its columns, its height then following the source. -fn exactKittyPlacement( - place: pardes.ImagePlace, - screen_cols: u16, - screen_rows: u16, - screen_pixel_w: u16, - screen_pixel_h: u16, -) ?KittyPlacement { - if (comptime !pardes.pdf_enabled) return null; - const g = place.native.geometry orelse return null; - const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); - const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); - if (g.dst.w == 0 or g.dst.h == 0 or g.src.w == 0 or g.src.h == 0) return null; - const cell_x = g.dst.x / cell_w; - const pixel_x = g.dst.x % cell_w; - const pixel_y = @min(g.dst.y, cell_h - 1); - const cols: u32 = @max(1, (g.dst.w + cell_w / 2) / cell_w); - if (cell_x >= place.w) return null; - const declared_w = cols * cell_w; - // At the cells' scale, the source that fills `cols` cells. - var src_w = g.src.w; - if (declared_w < g.dst.w) src_w = @max(1, @as(u32, @intCast(@as(u64, g.src.w) * declared_w / g.dst.w))); - var src_h = g.src.h; - const full = g.dst.y == 0 and g.dst.h >= cell_h; - if (!full) { - // As tall as it is at that scale, and no taller than the row. - const room = cell_h - pixel_y; - const fits: u32 = @intCast(@as(u64, room) * src_w / declared_w); - if (fits == 0) return null; - src_h = @min(src_h, fits); - } - return .{ - .cell_x = std.math.cast(u16, cell_x) orelse return null, - .cell_y = 0, - .cell_cols = std.math.cast(u16, @min(@as(u32, place.w) - cell_x, (pixel_x + declared_w + cell_w - 1) / cell_w)) orelse return null, - .cell_rows = 1, - .options = .{ - .clip_region = .{ - .x = std.math.cast(u16, g.src.x) orelse return null, - .y = std.math.cast(u16, g.src.y) orelse return null, - .width = std.math.cast(u16, src_w) orelse return null, - .height = std.math.cast(u16, src_h) orelse return null, - }, - .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = @intCast(pixel_x), .y = @intCast(pixel_y) } else null, - // The outer terminal stacks them, under the text below 0. - .z_index = if (place.z != 0) place.z else null, - .size = if (full) - .{ .cols = std.math.cast(u16, cols) orelse return null, .rows = 1 } - else - .{ .cols = std.math.cast(u16, cols) orelse return null }, - }, - }; -} - -fn kittyPlacement( - place: pardes.ImagePlace, - screen_cols: u16, - screen_rows: u16, - screen_pixel_w: u16, - screen_pixel_h: u16, -) ?KittyPlacement { - if (comptime pardes.pdf_enabled) { - if (place.native.fit == .contain) return null; - const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); - const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); - const body_w = std.math.mul(u32, place.w, cell_w) catch return null; - const body_h = std.math.mul(u32, place.h, cell_h) catch return null; - const geometry = place.native.geometry orelse pardes.image.nativeGeometry( - place.iw, - place.ih, - body_w, - body_h, - place.native.fit, - place.native.pan_x, - place.native.pan_y, - ) orelse return null; - - const safe_rows_u32 = geometry.dst.h / cell_h; - if (safe_rows_u32 == 0) return null; - const safe_pixel_h = safe_rows_u32 * cell_h; - var safe_src_h: u32 = geometry.src.h; - var declared_cols: u32 = 0; - var declared_rows: u32 = 0; - switch (place.native.fit) { - .width => { - declared_cols = @intCast(@max( - @as(u64, 1), - (@as(u64, geometry.dst.w) + cell_w - 1) / cell_w, - )); - const declared_pixel_w = @as(u64, declared_cols) * cell_w; - const max_src_h: u32 = @intCast( - @as(u64, safe_pixel_h) * geometry.src.w / declared_pixel_w, - ); - if (max_src_h == 0) return null; - safe_src_h = @min(safe_src_h, max_src_h); - 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, - ); - }, - .contain => unreachable, - } - 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.w or cell_y >= place.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.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.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 (place.native.fit) { - .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, - .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, - .contain => unreachable, - }, - }, - }; - } else { - return null; - } -} - -test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { - if (comptime !pardes.pdf_enabled) return; - var place = pardes.ImagePlace{ - .pane = 0, - .serial = 3, - .native = .{ .page = 7, .exact = true, .geometry = .{ - .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, - .dst = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, - } }, - .x = 99, - .y = 4, - .w = 24, - .h = 1, - .rgba = &.{}, - .iw = 240, - .ih = 160, - }; - // 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.native.geometry = .{ - .src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }, - .dst = .{ .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.native.geometry = .{ - .src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }, - .dst = .{ .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" { - if (comptime !pardes.pdf_enabled) return; - - const base = pardes.ImagePlace{ - .pane = 0, - .serial = 1, - .native = .{ - .revision = 1, - .page = 0, - .fit = .width, - .geometry = .{ - .src = .{ .w = 96, .h = 10 }, - .dst = .{ .y = 195, .w = 304, .h = 29 }, - }, - }, - .x = 0, - .y = 0, - .w = 38, - .h = 14, - .rgba = &.{}, - .iw = 96, - .ih = 64, - }; - 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.native.geometry.?.dst.h); - - var height = base; - height.native.fit = .height; - height.native.geometry.?.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.native.geometry.?.dst.h); - - height.native.geometry.?.dst.h = 13; - try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); -} - -test "host watch closes initial race and reloads rename-over PDF while idle" { - if (comptime !file_watch.supported or !pardes.pdf_enabled) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const original = try pardes.pdf.makeOutlineTestPdf(gpa); - defer gpa.free(original); - const replacement = try pardes.pdf.makeNoOutlineTestPdf(gpa); - defer gpa.free(replacement); - try tmp.dir.writeFile(io, .{ .sub_path = "live.pdf", .data = original }); - try tmp.dir.writeFile(io, .{ .sub_path = "initial.pdf", .data = replacement }); - try tmp.dir.writeFile(io, .{ .sub_path = "live-replacement.pdf", .data = original }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/live.pdf", .{tmp.sub_path}); - - const fd = file_watch.init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - var watches: file_watch.Table = @splat(null); - defer for (0..pardes.MAX_PANES) |id| file_watch.watchPane( - fd, - &watches, - @intCast(id), - null, - 0, - .{ .text = 0 }, - ); - - const core = try pardes.Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 }); - defer core.deinit(); - try std.testing.expectEqual(@as(usize, 3), core.panes[0].?.pdf.?.page_count); - - try tmp.dir.rename("initial.pdf", tmp.dir, "live.pdf", io); - var armed = false; - while (core.nextEffect()) |effect| switch (effect) { - .watch => |watch| if (watch.pane == 0 and watch.on) { - armed = true; - try std.testing.expect(!file_watch.applyEffect(core, io, fd, &watches, 0, true, watch.mode)); - }, - else => {}, - }; - try std.testing.expect(armed and watches[0] != null); - try std.testing.expectEqual(@as(usize, 1), core.panes[0].?.pdf.?.page_count); - - try tmp.dir.rename("live-replacement.pdf", tmp.dir, "live.pdf", io); - try std.testing.expect(file_watch.drain(fd)); - - try std.testing.expect(!file_watch.reloadChanged(core, io, gpa, &watches)); - const pane = core.panes[0].?; - try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count); - const disk_identity = try file_watch.identify(io, path); - switch (watches[0].?.generation) { - .pdf => |accepted| try std.testing.expect(accepted != null and accepted.?.eql(disk_identity)), - .text => return error.PdfWatchStoredTextGeneration, - } - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "reloaded") != null); - - core.native_images = true; - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const surface = try core.render(frame.allocator()); - try std.testing.expect(surface.nimages > 0); - try std.testing.expectEqual(@as(u32, 0), surface.images[0].?.native.page); -} - -fn kittyImageRepresentable(place: pardes.ImagePlace) bool { - return place.iw > 0 and place.ih > 0 and - place.iw <= std.math.maxInt(u16) and place.ih <= std.math.maxInt(u16); -} - -fn surfaceHasKittyKey(surface: *const pardes.Surface, key: pardes.ImageCacheKey) bool { - for (surface.images[0..surface.nimages]) |maybe| { - const place = maybe orelse continue; - if (comptime pardes.pdf_enabled) if (!kittyImageRepresentable(place)) continue; - if (place.cacheKey().eql(key)) return true; - } - return false; -} - -const PdfWheelTarget = struct { pane: usize, page: usize }; - -fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWheelTarget { - if (comptime !pardes.pdf_enabled) return null; - if (!core.native_images or mouse.type != .press or - (mouse.button != .wheel_up and mouse.button != .wheel_down) or - mouse.col < 0 or mouse.row < 0) return null; - const col: u16 = @intCast(mouse.col); - const row: u16 = @intCast(mouse.row); - for (core.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const rect = core.rects[id]; - if (col < rect.x or col >= rect.x + rect.w or - row < rect.y or row >= rect.y + rect.h) continue; - const page = pane.pdfPage() orelse return null; - return .{ .pane = id, .page = page }; - } - return null; -} - -/// Where a session's terminal comes from: /dev/tty, as a plain `pardes` -/// opens it; one open already (a session forked off its stub, -/// daemon.forkSession); or none, until one is attached (`--detach`). -/// The terminal a session starts on: /dev/tty, one its stub opened (an -/// upgraded session's is raw already, `termios` the cooked one), or none. -pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, none }; - -pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { - const io = init.io; - const gpa = init.gpa; - - var winch_set = posix.sigemptyset(); - posix.sigaddset(&winch_set, posix.SIG.WINCH); - // Kept by a daemon, a hangup is the terminal's end, not the session's: - // winchWatch takes it, and the session carries on detached. - if (daemon.link >= 0) posix.sigaddset(&winch_set, posix.SIG.HUP); - // FreeBSD drops a signal whose action is to be ignored (WINCH's - // default) as it is sent, sigwait or not: a handler keeps it. - if (comptime builtin.os.tag == .freebsd) - posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); - posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); - - var tty_buf: [0x10000]u8 = undefined; - var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; - defer screen.kitty.deinit(); - switch (term) { - .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), - .fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)), - .none => {}, - } - defer screen.leave(); - - var paste_buf: std.Io.Writer.Allocating = .init(gpa); - defer paste_buf.deinit(); - var loop: Loop = .init(io, &screen.tty, &screen.vx); - - try localSession(init, opts, &screen, &loop, &paste_buf); -} - -/// A replica client's link to its session (`remote`), drawn here. -const Remote = struct { - link: replica.Link, - - /// The client's own view drawn on its terminal, outside any step: the - /// replica's digest stays the session's (views.drawOne). What the host - /// writes in the core as it presents (a frame skipped, one owed) is put - /// back, as the frame statistics are this process's. - fn draw(c: *Remote, s: *Shell) void { - const r = c.link.r; - const core = r.core(); - const skipped = core.present_skipped; - const needs = core.needs_frame; - core.frames.mark_start = pardes.FrameStats.nowNs(); - core.frames.mark_update = core.frames.mark_start; - r.draw(.{ .ctx = s, .f = Shell.present }); - core.frames.mark_render = core.frames.mark_update; - const drew = core.frames.bytes > 0; - c.link.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), false, c.link.owed); - core.present_skipped = skipped; - core.needs_frame = needs; - c.link.drawn(drew); - } -}; - -/// The session's stream, onto the loop: its units, and its end. -fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void { - defer done.store(true, .release); - const Post = struct { - fn post(l: *Loop, said: replica.Said) bool { - l.postEvent(.{ .said = said }) catch return false; - return true; - } - }; - replica.readLink(gpa, fd, rest, loop, Post.post); - loop.postEvent(.link_gone) catch {}; -} - -/// `pardes --attach=<socket>:<session>` (and `<host>:<session>`, through -/// ssh, main.zig): this terminal a replica client of a session elsewhere -/// (docs/next-daemon.md, "Phase 5 part B notes"). Its own core, loaded -/// from the session's dump, applies its keys at once (src/replica.zig); -/// the session's units are the truth it rolls back to. Its own view of the -/// session is drawn here, as the session draws its terminals'. -pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far_link: bool) !void { - const io = init.io; - const gpa = init.gpa; - const Said = struct { - fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { - var said: [800]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&said, "pardes: --attach: " ++ fmt ++ "\n", args) catch "pardes: --attach failed\n") catch {}; - std.process.exit(1); - } - }; - var why: [600]u8 = @splat(0); - // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash, - // those it holds kept from the link, and its stream in zstd. A client - // on this machine's own socket is sent the dump whole, as before: a - // hash and a compression there cost more than the bytes. - const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else far_link; - var have_store: replica.Have = if (far) .init(io) else .{ .io = io }; - defer have_store.deinit(); - const have: ?*replica.Have = if (far) &have_store else null; - var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - var joined = replica.dial(gpa, path, session, &why, have, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words}); - - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.image.start(io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.stop(); - } - var o = opts; - o.image_allocator = allocs.image; - o.pdf_allocator = allocs.pdf; - var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - // Its join's time, the dial and the load (PARDES_REPLICA_STATS). - var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); - - var winch_set = posix.sigemptyset(); - posix.sigaddset(&winch_set, posix.SIG.WINCH); - // A hangup ends it the normal way (`quit`), what it made kept on disk - // (`Have.keep`) and its ssh forward's socket unlinked (main.zig). - posix.sigaddset(&winch_set, posix.SIG.HUP); - hangup_quits = true; - if (comptime builtin.os.tag == .freebsd) - posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); - posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); - var tty_buf: [0x10000]u8 = undefined; - var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; - defer screen.kitty.deinit(); - try screen.enter(try vaxis.Tty.init(io, &tty_buf)); - defer screen.leave(); - defer screen.glide.deinit(gpa); - var paste_buf: std.Io.Writer.Allocating = .init(gpa); - defer paste_buf.deinit(); - var loop: Loop = .init(io, &screen.tty, &screen.vx); - var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); - defer frame_arena.deinit(); - var remote_link: Remote = .{ .link = .{ .r = r, .fd = joined.fd } }; - const link = &remote_link.link; - try link.fromEnv(gpa, init.environ_map); - defer link.deinit(gpa); - var sh: Shell = .{ - .io = io, - .gpa = gpa, - .lsp_gpa = allocs.lsp, - .core = r.core(), - .prompt_rcs = undefined, - .loop = &loop, - .frame = &frame_arena, - .paste_buf = &paste_buf, - .inotify_fd = -1, - .from = joined.view, - .remote = &remote_link, - }; - - try startInput(&loop, &screen); - defer stopInput(io, &screen.thread); - (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); - (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach(); - try screen.vx.queryTerminalSend(screen.tty.writer()); - // A join a pass: the first, and one after the replica diverged or the - // session let it go to upgrade. The terminal stays as it is. - while (true) { - r.gmtoff = joined.gmtoff; - sh.core = r.core(); - sh.from = joined.view; - sh.terms = @splat(null); - sh.terms[joined.view] = &screen; - screen.feed.view = joined.view; - link.reset(r, joined.fd); - link.joinedAs(&joined, dial_ms); - var reader_done: std.atomic.Value(bool) = .init(false); - const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); - // What it is, then its size, are its view's first inputs. - link.input(.{ .frontend = .{ .windowed = false } }); - screen.size = null; - sh.winched(); - screen.vx.queueRefresh(); - while (!link.quit) { - // Its predicted echo judged and caught up, once a frame. - if (r.echoFrame()) link.dirty = true; - if (link.dirty) remote_link.draw(&sh); - const first = (loop.tryEvent() catch null) orelse idle: { - // Idle, its frame drawn: the next key needs no copy taken. - r.ready(); - break :idle loop.nextEvent() catch break; - }; - var ev = first; - var batch: usize = 1; - while (true) { - _ = sh.apply(ev); - if (link.quit or (!sh.in_paste and batch >= 64)) break; - ev = (loop.tryEvent() catch null) orelse break; - batch += 1; - } - r.settle(); - if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { - screen.caps_pending = false; - screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; - screen.vx.queueRefresh(); - link.dirty = true; - } - if (link.owed or r.echo.changed) link.dirty = true; - // Predictions out: judged a frame at a time while they are. - if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms)); - if (link.quietCheck()) |ms| requestWake(io, ms); - if (r.diverged != null) link.quit = true; - } - if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(joined.fd, r.diverged != null); - // The link's reader ends with the link, posting as it goes: what it - // and the terminal posted is let go until it has. Its end is read - // before the drain, not after: its last post (`link_gone`) comes - // just before it, and left queued it ended the next link at once. - _ = libc.shutdown(joined.fd, 2); - while (true) { - const ended = reader_done.load(.acquire); - while (loop.tryEvent() catch null) |ev| switch (ev) { - .said => |said| switch (said) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), - .checked => {}, - }, - .paste => |b| gpa.free(@constCast(b)), - else => {}, - }; - if (ended) break; - std.Thread.yield() catch {}; - } - reader.join(); - _ = libc.close(joined.fd); - joined.rest.deinit(gpa); - // Why it joins again, in a line over its frame until a key. - if (!link.rejoins()) { - // What it made since it joined, kept for its next start. - if (have) |h| h.keep(r.core()); - r.deinit(); - if (link.gone) { - screen.leave(); - Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session}); - } - return; - } - // The session again, the core it leaves held meanwhile: its blobs - // are not sent again. - if (have) |h| h.leaving(r.core()); - dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - joined = replica.Link.redial(gpa, path, session, &why, have, r.diverged == null, joined.view) orelse { - screen.leave(); - Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)}); - }; - if (have) |h| h.left(); - r.deinit(); - r = replica.Link.load(gpa, &joined, o, &why, have) orelse { - screen.leave(); - Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - }; - dial_ms = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); - } -} - - -/// 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 -/// a reattach in between (daemon.zig). One a view (views.zig): the session's -/// own (`primary`, its stub `daemon.stub`), and one more for each terminal -/// `pardes --attach`ed while it is attached, which keeps its own. -const Screen = struct { - io: std.Io, - gpa: std.mem.Allocator, - env: *std.process.Environ.Map, - buf: []u8, - tty: vaxis.Tty = undefined, - vx: vaxis.Vaxis = undefined, - on: bool = false, - primary: bool = false, - /// The pipe to its stub, an attached one's (the primary's is daemon.stub). - stub: posix.fd_t = -1, - /// Its slot in Killed. - killed: ?usize = null, - feed: Feed = .{}, - thread: ?std.Io.Future(void) = null, - kitty: std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), - caps_pending: bool = true, - /// Its size as last taken (`Shell.resized`). - size: ?vaxis.Winsize = null, - tracks: []const pardes.animation.Track = &.{}, - /// T2: the cursor's jump trail (JumpTrail). - trail: JumpTrail = .{}, - /// The view's glide, the GUI's motion drawn at whole rows (anim 12). - glide: pardes.glide.Glide = .{}, - /// T7: when each pane's view last moved (ThumbFlash). - flash: ThumbFlash = .{}, - - /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a - /// forked session is no controlling terminal of its, which /dev/tty is. - /// An upgraded session's is raw already, `cooked` what it goes back to. - fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t, cooked: ?posix.termios) !vaxis.Tty { - if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty - const termios = cooked orelse try vaxis.Tty.makeRaw(fd); - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) }; - } - - fn enter(sc: *Screen, tty: vaxis.Tty) !void { - sc.tty = tty; - errdefer sc.tty.deinit(); - sc.vx = try vaxis.init(sc.io, sc.gpa, sc.env, .{ .system_clipboard_allocator = sc.gpa }); - errdefer sc.vx.deinit(sc.gpa, sc.tty.writer()); - try sc.vx.enterAltScreen(sc.tty.writer()); - try sc.vx.setMouseMode(sc.tty.writer(), true); - try sc.vx.setBracketedPaste(sc.tty.writer(), true); - if (comptime !builtin.is_test) { - sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios); - // What a panic puts back (vaxis.recover). - if (sc.primary) vaxis.tty.global_tty = sc.tty; - } - const view = sc.feed.view; - sc.feed = .{ .view = view }; - sc.caps_pending = true; - sc.size = null; - sc.on = true; - } - - fn leave(sc: *Screen) void { - if (!sc.on) return; - sc.on = false; - if (sc.killed) |slot| Killed.disarm(slot); - sc.killed = null; - clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); - sc.vx.exitAltScreen(sc.tty.writer()) catch {}; - sc.vx.deinit(sc.gpa, sc.tty.writer()); - if (comptime !builtin.is_test) if (sc.primary) { - vaxis.tty.global_tty = null; - }; - sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets - } - - /// Its stub told the terminal is detached (it ends, and its shell has - /// the terminal back). - fn sayDetached(sc: *Screen) void { - if (sc.primary) return daemon.tellStubDetached(); - daemon.tellDetached(sc.stub); - sc.stub = -1; - } - - /// Its terminal hung up, or the stub that waits on it is gone. - fn hungUp(sc: *const Screen) bool { - const stub = if (sc.primary) daemon.stub else sc.stub; - const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd; - var fds = [_]posix.pollfd{ - .{ .fd = handle, .events = 0, .revents = 0 }, - .{ .fd = stub, .events = 0, .revents = 0 }, - }; - _ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false; - const gone = posix.POLL.HUP | posix.POLL.ERR; - return fds[0].revents & gone != 0 or (stub >= 0 and fds[1].revents & gone != 0); - } - - fn setStub(sc: *Screen, fd: posix.fd_t) void { - if (sc.primary) daemon.stub = fd else sc.stub = fd; - } -}; - -/// SIGTERM or SIGHUP: each terminal put back as a clean exit leaves it -- -/// the main screen, no mouse, paste or keyboard modes, the cursor shown, -/// cooked termios -- and then the signal's own death. A nested editor -/// killed in a pane must not leave that pane's terminal wedged. -/// Async-signal-safe: write, tcsetattr, sigaction, raise. -const Killed = struct { - var fds: [pardes.views.max]posix.fd_t = @splat(-1); - var cooked: [pardes.views.max]posix.termios = undefined; - const reset = "\x1b[<u\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?2004l\x1b[0m\x1b[?25h\x1b[?1049l"; - fn arm(tty_fd: posix.fd_t, termios: posix.termios) ?usize { - const slot = std.mem.findScalar(posix.fd_t, &fds, -1) orelse return null; - cooked[slot] = termios; - fds[slot] = tty_fd; - const on: posix.Sigaction = .{ .handler = .{ .handler = handle }, .mask = posix.sigemptyset(), .flags = posix.SA.RESETHAND }; - posix.sigaction(.TERM, &on, null); - // A hangup a daemon keeps the session through is winchWatch's. - if (daemon.link < 0) posix.sigaction(.HUP, &on, null); - return slot; - } - - /// The terminal gone (put back, or detached): a TERM still takes the - /// socket, the prompt files and the shells with it, and leaves the - /// terminal alone. - fn disarm(slot: usize) void { - fds[slot] = -1; - } - - fn handle(sig: posix.SIG) callconv(.c) void { - for (fds, &cooked) |fd, *termios| if (fd >= 0) { - _ = std.c.write(fd, reset, reset.len); - _ = std.c.tcsetattr(fd, .FLUSH, termios); - }; - // The 9P socket and private prompt files go too: a killed editor - // leaves none behind. Its shells too, the daemon's dups let go. - ninep_io.unlinkOwnSocket(); - host_io.Shell.unlinkOwnedRcs(); - daemon.hangUp(); - // SA_RESETHAND put the default back: the same signal, now fatal. - _ = std.c.raise(sig); - } -}; - -fn localSession( - init: std.process.Init, - opts: pardes.Options, - screen: *Screen, - loop: *Loop, - paste_buf: *std.Io.Writer.Allocating, -) !void { - const io = init.io; - const gpa = init.gpa; - - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - var options = opts; - options.image_allocator = allocs.image; - options.pdf_allocator = allocs.pdf; - options.tree_sitter_allocator = allocs.tree_sitter; - options.frame_allocator = allocs.frame; - - pardes.image.start(io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - // Pages render on lanes off the loop (pdf_view.workers). - if (comptime pardes.pdf_enabled) pardes.panes.Pdf.workers = io; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.panes.Pdf.dropKept(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.stop(); - } - - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, options, rec) - else if (options.load_path) |lp| blk: { - const bytes = try filesystem.readFile(gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); - } else try pardes.Pardes.init(allocs.pardes, options); - defer core.deinit(); - - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); - - var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); - defer frame_arena.deinit(); - - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); - - var sh: Shell = .{ - .io = io, - .gpa = gpa, - .lsp_gpa = allocs.lsp, - .core = core, - .prompt_rcs = &prompt_rcs, - .loop = loop, - .frame = &frame_arena, - .paste_buf = paste_buf, - .inotify_fd = file_watch.init(false), - .fs = fs, - .test_clock = host_io.testClock(), - }; - sh.terms[0] = screen; - sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica }; - defer sh.peers.deinit(); - // Before the core goes: each client sees its link end. - defer sh.peers.dropAll(sh.core); - pardes.lsp.setStatusSink(&sh, lspStatusSink); - host_io.setExitWake(loop, wakeForExit); - defer screen.glide.deinit(gpa); - // The terminals of the other views end with the session: each put back, - // its stub told. - defer for (&sh.terms) |*slot| if (slot.*) |sc| if (!sc.primary) { - stopInput(io, &sc.thread); - sh.dropScreen(sc, .exit); - slot.* = null; - }; - defer { - host_io.setExitWake(null, null); - pardes.lsp.setStatusSink(null, null); - for (&sh.ptys) |*slot| if (slot.*) |*pt| { - pt.reader.cancel(io) catch {}; - _ = libc.close(pt.file.handle); - slot.* = null; - }; - for (sh.adoptions[0..sh.adoptions_len]) |a| _ = libc.close(a.fd); - if (sh.lsp_task) |*t| { - t.future.cancel(io); - sh.lsp_task = null; - } - sh.pipe_tasks.cancelAll(io); - // Its worker may be waiting on the loop's queue for room. - core.stream.cancelTask(); - file_watch.stop(sh.inotify_fd); - if (sh.watch_task) |*t| { - t.cancel(io) catch {}; - sh.watch_task = null; - } - if (sh.inotify_fd >= 0) { - _ = libc.close(sh.inotify_fd); - sh.inotify_fd = -1; - } - while (loop.tryEvent() catch null) |ev| switch (ev) { - .pty_read => |pr| { - tookRead(io, pr.id); - gpa.free(pr.bytes); - }, - .paste => |b| gpa.free(@constCast(b)), - .lsp_done => |d| if (d.rows) |rows| allocs.lsp.free(rows), - .lsp_status => |text| allocs.lsp.free(text), - .pipe_done => |response_value| { - var response = response_value; - response.deinit(gpa); - }, - .search_rows => |b| b.deinit(gpa), - .attach => |a| { - _ = libc.close(a.tty); - if (a.stub >= 0) _ = libc.close(a.stub); - }, - .adopted => |a| _ = libc.close(a.fd), - else => {}, - }; - } - const host = sh.host(); - - core.host = host; - // An upgraded session's terminals, its own again. - if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen); - // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). - sh.setAttended(sh.attached()); - while (core.nextEffect()) |effect| core.perform(effect); - // ...and its shells, once a fresh session's own has a directory to - // adopt them in. - if (upgrade.resumed) |*rec| { - sh.resumePtys(rec); - while (core.nextEffect()) |effect| core.perform(effect); - } - - if (screen.on) try startInput(loop, screen); - defer stopInput(io, &screen.thread); - (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); - (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); - if (fs) |f| try f.watch(loop, wakeFs); - if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); - // Detached from the start, nothing else may wake the first wait. - if (!screen.on) daemon.watch(loop, deliverNote); - // PARDES_TEST_VIEWS: the terminals at these paths are views of the - // session too, from its start, as `pardes --attach`ed ones are (the - // snapshot harness's `start ... views=N`). - if (upgrade.resumed == null) if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { - var it = std.mem.tokenizeScalar(u8, paths, ' '); - while (it.next()) |path| { - var path_buf: [256]u8 = undefined; - const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue; - const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0)); - if (fd >= 0) sh.attachTerminal(fd, -1, null); - } - }; - - sh.threads_ok = true; - for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try io.concurrent(readPty, .{ io, gpa, pt.file, id, sh.gens[id], loop }); - }; - if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; - - defer unlinkKittyShm(); - while (!core.quit) { - pardes.turn.bump(&pardes.turn.restores); - try core.pump(host); - // Its unit to each replica client, and theirs taken in. - sh.peers.boundary(core); - upgrade.locate(); - // Asked in the step (the word), done between steps: the session whole. - if (sh.upgrade_asked) |pane| sh.upgradeNow(pane); - // A terminal (`pardes --attach`) or an adopted shell, handed on by - // the daemon's thread to this loop; started after the first frame, - // off a startup's way. - daemon.watch(loop, deliverNote); - if (core.takeRestore()) |rp| blk: { - // ponytail: a Restore replaces the core its clients replicate; - // they are let go, and attach again. - sh.peers.dropAll(core); - const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { - core.reportError(core.active, "Restore", err); - break :blk; - }; - defer gpa.free(bytes); - const nc = dump.restore(core, bytes, rp) catch |err| { - core.reportError(core.active, "Restore", err); - break :blk; - }; - if (sh.lsp_task) |*task| { - task.future.cancel(io); - sh.lsp_task = null; - } - sh.pipe_tasks.cancelAll(io); - for (&sh.gens) |*generation| generation.* +%= 1; - for (&sh.ptys) |*slot| if (slot.*) |*pt| { - pt.reader.cancel(io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - slot.* = null; - }; - for (0..pardes.MAX_PANES) |wid| file_watch.watchPane( - sh.inotify_fd, - &sh.watches, - @intCast(wid), - null, - 0, - .{ .text = 0 }, - ); - _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); - // ponytail: a restored session is one view, the live one's - // terminal: the others are let go, as a detach of each. - const live = sh.term().?; - for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) { - stopInput(io, &sc.thread); - sh.dropScreen(sc, .detach); - slot.* = null; - }; - sh.terms = @splat(null); - sh.terms[0] = live; - stopInput(io, &live.thread); - live.feed.view = 0; - sh.from = 0; - if (live.on) startInput(loop, live) catch {}; - if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); - nc.native_images = live.on and live.vx.caps.kitty_graphics; - nc.unattended = !live.on; - sh.peers.alone_unattended = !live.on; - if (fs) |f| f.reset(nc); - core.deinit(); - core = nc; - sh.core = nc; - if (comptime pardes.pdf_enabled) if (live.on) { - updateCoreTerminalSize(core, live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix); - }; - } - } - if (fs) |f| { - f.deinit(gpa); - fs = null; - sh.fs = null; - } -} - -fn clearNativeImages( - kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), - vx: *vaxis.Vaxis, - tty: *vaxis.Tty, -) void { - var iterator = kitty_handles.valueIterator(); - while (iterator.next()) |handle| vx.freeImage(tty.writer(), handle.id); - kitty_handles.clearRetainingCapacity(); -} - -const Adoption = struct { pid: posix.pid_t, fd: posix.fd_t, pane: ?u8 }; - -/// The daemon's thread: what it says, onto the loop's queue. -fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const loop: *Loop = @ptrCast(@alignCast(ctx)); - switch (note) { - .attach => |a| if (a.tty < 0) { - if (a.stub >= 0) daemon.refuseStub(a.stub, "a terminal session takes a terminal"); - } else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch { - _ = libc.close(a.tty); - _ = libc.close(a.stub); - }, - .adopted => |a| { - for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch { - _ = libc.close(fd); - }; - loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {}; - }, - .replica => |j| loop.postEvent(.{ .replica = j }) catch { - _ = libc.close(j.fd); - }, - } -} - -/// A replica reader's post: the session's wait ends, and its step -/// boundary takes the post in. -fn wakeForReplica(ctx: ?*anyopaque) void { - const loop: *Loop = @ptrCast(@alignCast(ctx.?)); - // Never waits: a full queue wakes the loop anyway, and a reader the - // loop is joining (a client let go) must not wait on it. - _ = loop.tryPostEvent(.replica_mail) catch {}; -} - -const Shell = struct { - io: std.Io, - gpa: std.mem.Allocator, - lsp_gpa: std.mem.Allocator, - core: *pardes.Pardes, - prompt_rcs: *const host_io.Shell.PromptFiles, - loop: *Loop, - /// Each view's terminal, by view (views.zig): the session's own first; - /// none in tests. - terms: [pardes.views.max]?*Screen = @splat(null), - /// The view the input taken now is from (`Command.value.from`). - from: u8 = 0, - frame: *std.heap.ArenaAllocator, - paste_buf: *std.Io.Writer.Allocating, - inotify_fd: c_int, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: [pardes.MAX_PANES]Adoption = undefined, - adoptions_len: usize = 0, - adopted: usize = 0, - fs: ?*ninep_io.Listener = null, - ptys: [pardes.MAX_PANES]?Pty = @splat(null), - gens: [pardes.MAX_PANES]u32 = @splat(0), - watches: file_watch.Table = @splat(null), - watch_task: ?std.Io.Future(anyerror!void) = null, - lsp_task: ?host_io.Lsp.Task = null, - pipe_tasks: PipeTasks = .{}, - threads_ok: bool = false, - check_files: bool = false, - // ponytail: one bracketed paste at a time for every terminal: keys - // another terminal sends while one pastes join its paste. - in_paste: bool = false, - /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the - /// running-out wait moves it: the core's next wake. - test_clock: ?u64 = null, - /// The tick the last paced frame was due at (waitInput), and whether - /// this wait read an input (its frame is drawn at once). - pace_ns: u64 = 0, - input_seen: bool = false, - wake_to: u64 = 0, - /// waitInput's pacing of output: whether this wait read a pane's output, - /// and when the last frame was written, the last input was read and the - /// focused pane's output last was. - output_seen: bool = false, - drawn_ns: u64 = 0, - input_ns: u64 = 0, - focused_ns: u64 = 0, - /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). - upgrade_asked: ?u8 = null, - /// Its pty readers stopped for it: their end of file is not a shell's. - upgrading: bool = false, - /// The session's replica clients (src/replica.zig), on sockets. - peers: replica.Peers = .{}, - /// This wait took only a replica's post (its input, its join): the - /// pump after it reads no new time, so it moves nothing the replicas' - /// speculations stand on (a replica takes such a unit as is). - mail_only: bool = false, - waited: bool = false, - /// This wait's steps so far, and the input held for the next (`split`). - took_input: bool = false, - took_output: bool = false, - held: ?@TypeOf(Command.value) = null, - /// This process a replica client of a session elsewhere (`remote`): - /// its inputs go to the replica, never straight to the core. - remote: ?*Remote = null, - - const Leaving = enum { detach, exit }; - - /// A terminal's input, to the core, or to a replica client's engine - /// (applied at once there, and sent to the session). - fn feed(s: *Shell, ev: pardes.Event) void { - const c = s.remote orelse return s.core.update(ev); - c.link.input(ev); - } - - /// Whether a terminal of this process's shows the session, or - /// nothing (a test) can. - fn local(s: *const Shell) bool { - for (s.terms) |slot| if (slot != null) return true; - return false; - } - - /// Whether anyone looks at the session: a terminal here, or a replica - /// client (Peers keeps it attended while one is there). - fn setAttended(s: *Shell, on: bool) void { - s.peers.alone_unattended = !on; - s.core.unattended = !on and s.peers.count() == 0; - } - - fn of(ctx: ?*anyopaque) *Shell { - return @ptrCast(@alignCast(ctx.?)); - } - - fn host(s: *Shell) host_io.Host { - return .{ .ctx = s, .vtable = if (comptime pardes.isolated) &isolated_vtable else &vtable }; - } - - const isolated_vtable: host_io.Host.VTable = .{ - .wait_input = waitInput, - .now = clockNow, - .present = present, - .post_present = postPresent, - .poll_frame = stepGlide, - }; - - const vtable: host_io.Host.VTable = .{ - .wait_input = waitInput, - .now = clockNow, - .present = present, - .post_present = postPresent, - .poll_frame = pollFrame, - .watched = watched, - .detach = detach, - .adopt = adopt, - .upgrade = upgradeAsked, - .newer_build = newerBuild, - .spawn = spawn, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePty, - .tty_taken = ttyTaken, - .fg_name = fgName, - .kill_job = killJob, - .write_file = writeFile, - .write_dump = writeDump, - .watch_file = watchFile, - .watch_theme = watchTheme, - .dump_themes = dumpThemes, - .set_clipboard = setClipboard, - .read_clipboard = readClipboard, - .open_link = openLink, - .lsp = lsp, - .pipe = pipe, - .search = search, - }; - - fn clockNow(ctx: ?*anyopaque) u64 { - const s = of(ctx); - if (s.waited) { - s.waited = false; - if (s.mail_only and s.peers.count() > 0 and s.core.clock_started) return s.core.now_ns; - } - return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - } - - /// The live view's terminal (null in tests). - fn term(s: *const Shell) ?*Screen { - return s.terms[s.core.view]; - } - - fn attached(s: *const Shell) bool { - const screen = s.term() orelse return true; - return screen.on; - } - - /// Drawn only while a terminal shows it: a replica client's view live - /// (its input the last), whichever terminal here shows another. - fn watched(ctx: ?*anyopaque) bool { - const s = of(ctx); - if (s.term() == null and s.local()) { - for (s.terms) |slot| if (slot) |sc| if (sc.on) return true; - return false; - } - return s.attached(); - } - - /// Detach: the terminal put back and let go, the stub told (it ends, - /// and the shell has its terminal again), the session left running. - fn detach(ctx: ?*anyopaque) void { - const s = of(ctx); - // A replica client's: its link ends. - if (s.peers.detach(s.core.view)) return; - if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached"); - // One of several: its view goes, and the session stays on the rest. - if (pardes.views.count(s.core) > 1) return s.dropView(s.core.view, .detach); - if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session (it is its terminal's job)"); - s.leaveTerminal(); - } - - /// View `k`'s terminal let go (detached, or gone) while others stay: the - /// view goes with it. - fn dropView(s: *Shell, k: u8, how: Leaving) void { - const sc = s.terms[k] orelse return; - stopInput(s.io, &sc.thread); - s.terms[k] = null; - s.core.closeView(k); - s.dropScreen(sc, how); - } - - /// A terminal put back and its stub told; an attached one's Screen freed - /// (the session's own stays, a view of none). - fn dropScreen(s: *Shell, sc: *Screen, how: Leaving) void { - if (sc.primary) { - sc.leave(); - return sc.sayDetached(); - } - sc.leave(); - switch (how) { - .detach => sc.sayDetached(), - .exit => { - daemon.tellExit(sc.stub, 0); - sc.stub = -1; - }, - } - sc.glide.deinit(s.gpa); - sc.kitty.deinit(); - s.gpa.free(sc.buf); - s.gpa.destroy(sc); - } - - fn leaveTerminal(s: *Shell) void { - const screen = s.term() orelse return; - stopInput(s.io, &screen.thread); - screen.leave(); - s.core.native_images = false; - s.setAttended(false); - // The stub's stdin, stdout and stderr were its terminal too. - const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); - if (null_fd >= 0) { - for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); - if (null_fd > 2) _ = libc.close(null_fd); - } - screen.sayDetached(); - daemon.setState(true); - } - - /// `pardes --attach`'s terminal: for a detached session its own again, - /// entered as the first one was; for one attached already, a view of - /// its own (views.zig). Sized, asked what it can do, and drawn whole. - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - // A replica client's view live (its input the last) has no terminal - // here: the session's own is the one a terminal takes, or joins. - const live = s.term() orelse for (s.terms) |slot| { - if (slot) |sc| if (sc.primary) break sc; - } else { - _ = libc.close(fd); - return refuse(stub, "that session has no terminal of its own to attach to"); - }; - const screen = if (!live.on) live else extra: { - const sc = s.gpa.create(Screen) catch break :extra null; - const buf = s.gpa.alloc(u8, 0x10000) catch { - s.gpa.destroy(sc); - break :extra null; - }; - sc.* = .{ .io = s.io, .gpa = s.gpa, .env = live.env, .buf = buf, .kitty = .init(s.gpa) }; - break :extra sc; - } orelse { - _ = libc.close(fd); - return refuse(stub, "that session has no room for another terminal"); - }; - const extra = screen != live; - const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { - _ = libc.close(fd); - if (extra) s.freeScreen(screen) else daemon.setState(true); - return refuse(stub, "that terminal would not go raw"); - }; - screen.enter(tty) catch { - if (extra) s.freeScreen(screen) else daemon.setState(true); - return refuse(stub, "that terminal would not take the screen"); - }; - if (extra) { - const k = s.core.openView() orelse { - screen.leave(); - s.freeScreen(screen); - return refuse(stub, "that session has as many terminals as it takes"); - }; - screen.feed.view = k; - s.terms[k] = screen; - } - screen.setStub(stub); - s.setAttended(true); - startInput(s.loop, screen) catch {}; - screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; - s.core.needs_frame = true; - daemon.setState(false); - } - - fn freeScreen(s: *Shell, sc: *Screen) void { - sc.kitty.deinit(); - s.gpa.free(sc.buf); - s.gpa.destroy(sc); - } - - /// A terminal refused: its stub told why (a test's has none). - fn refuse(stub: posix.fd_t, why: []const u8) void { - if (stub >= 0) daemon.refuseStub(stub, why); - } - - /// Adopt: the daemon is asked for the shells of sessions that died - /// holding them; each comes back (`adopted`) as a terminal pane here. - fn adopt(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); - s.adopted = 0; - daemon.adopt(); - } - - /// A client's own build is not the session's to say (its core's host - /// is the session's, through the tape). - fn newerBuild(ctx: ?*anyopaque) bool { - return of(ctx).remote == null and upgrade.newer(); - } - - fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place"); - s.upgrade_asked = pane; - } - - /// Upgrade, between steps: this process exec'd as the pardes now at the - /// path it was started from, the session in its dump, and its ptys, - /// terminals, stubs and daemon link kept open across (upgrade.zig). - /// Returns only when it could not be, the session going on as it was. - fn upgradeNow(s: *Shell, pane: u8) void { - if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty - s.upgrade_asked = null; - const core = s.core; - var why: [800]u8 = undefined; - const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from"); - // 9P is served while the new binary is asked (its clients' clunks - // and reads after the word are answered), and not after. - pardes.turn.rest(); - const checked = upgrade.check(path, &why); - pardes.turn.wake(); - switch (checked) { - .no => |w| return core.reportFailure(pane, w), - .ok => {}, - } - // Nothing more read from a pty or a terminal, and what was read - // goes in; a reader's cancel posts an end of file, passed over. - s.upgrading = true; - defer s.upgrading = false; - for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; - for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread); - while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); - core.settle(); - // Its replica clients told, their views gone before the dump: each - // dials the session again once it is back. - s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); - var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); - for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{ - .view = @intCast(k), - .fd = sc.tty.fd.handle, - .stub = if (sc.primary) daemon.stub else sc.stub, - .primary = sc.primary, - .termios = sc.tty.termios, - }); - var popped = false; - var at_buf: [1024:0]u8 = undefined; - const failed: []const u8 = failed: { - const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is"; - const bytes = pardes.dump.dumpBytes(core) catch |err| { - var words: [128]u8 = undefined; - break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump"; - }; - defer s.gpa.free(bytes); - if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written"; - rec.dump = at; - rec.old = upgrade.openSelf(); - // What this process put in its terminals that the next puts in - // again: its images, and its keyboard mode, a stack. - for (s.terms) |slot| if (slot) |sc| if (sc.on) { - clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); - if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[<u") catch {}; - sc.vx.state.kitty_keyboard = false; - sc.tty.writer().flush() catch {}; - }; - popped = true; - unlinkKittyShm(); - daemon.upgraded(); - if (s.fs) |f| f.flushOut(); - const err_words = upgrade.exec(s.gpa, path, -1, &rec); - // Still here: the exec failed. - _ = libc.unlink(at); - if (rec.old >= 0) _ = libc.close(rec.old); - break :failed std.fmt.bufPrint(&why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start"; - }; - // As it was: its ptys read on, its terminals' keys as they were. - for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; - }; - for (s.terms) |slot| if (slot) |sc| if (sc.on) { - if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; - startInput(s.loop, sc) catch {}; - }; - core.reportFailure(pane, failed); - } - - /// An upgraded session's shells, running on: each its pane's pty again, - /// or, when its dump would not load (`fresh`), adopted as new panes. - fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { - for (rec.ptys[0..rec.nptys]) |k| { - const pane = if (rec.fresh) null else s.core.panes[k.pane]; - if (pane == null or !pane.?.isTerminal()) { - s.adoptShell(k.pid, k.fd); - continue; - } - const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } }; - s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - - /// An upgraded session's terminals, each its view's again (`primary`, - /// run's, entered already); in a fresh session each but the primary a - /// view of its own, as `--attach` makes one. A view left with none - /// closes, but a replica client's, kept for its rejoin (views.away). - fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void { - if (comptime builtin.is_test) unreachable; - const core = s.core; - if (rec.fresh) { - for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios); - return; - } - s.terms = @splat(null); - if (rec.nttys == 0) { - // The live view alone (never one kept for a rejoin) is the - // session's own. - for (0..pardes.views.max) |k| if (k != core.view and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - s.terms[core.view] = primary; - primary.feed.view = core.view; - return; - } - for (rec.ttys[0..rec.nttys]) |t| { - if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) { - if (t.primary) continue; - _ = libc.close(t.fd); - if (t.stub >= 0) daemon.tellDetached(t.stub); - continue; - } - const sc = if (t.primary) primary else extra: { - const sc = s.gpa.create(Screen) catch break :extra null; - const buf = s.gpa.alloc(u8, 0x10000) catch { - s.gpa.destroy(sc); - break :extra null; - }; - sc.* = .{ .io = s.io, .gpa = s.gpa, .env = primary.env, .buf = buf, .kitty = .init(s.gpa) }; - const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch { - s.freeScreen(sc); - break :extra null; - }; - sc.enter(tty) catch { - s.freeScreen(sc); - break :extra null; - }; - sc.setStub(t.stub); - startInput(s.loop, sc) catch {}; - sc.vx.queryTerminalSend(sc.tty.writer()) catch {}; - break :extra sc; - } orelse { - _ = libc.close(t.fd); - if (t.stub >= 0) daemon.tellDetached(t.stub); - continue; - }; - sc.feed.view = t.view; - s.terms[t.view] = sc; - } - for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - if (s.terms[core.view] == null) s.terms[core.view] = primary; - } - - /// One shell of a dead session (`pid` 0: the last of them was told). - fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void { - const core = s.core; - if (pid == 0) { - var buf: [96]u8 = undefined; - return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in"); - } - if (s.adoptions_len < s.adoptions.len) { - // A terminal pane, as the Tty word makes one; its spawn takes - // this pty instead of forking a shell (`spawn`). - s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null }; - s.adoptions_len += 1; - if (core.adoptShell()) |id| { - s.adoptions[s.adoptions_len - 1].pane = id; - s.adopted += 1; - return; - } - s.adoptions_len -= 1; - } - // No room for it: its master goes, and the shell with this session. - _ = libc.close(fd); - var buf: [96]u8 = undefined; - core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell"); - } - - fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { - const s = of(ctx); - // The wait is the 9P connections' turn with the core. A timeout (the - // core's next wake) arrives through the same queue (`wakeWatch`). - // While anything moves, a frame a tick (animation.frame_ns) on a grid - // of them, as the GUI paces to its display: the loop ran as fast as - // the terminal answered, a frame every 2 ms, each a write. An input - // ends the wait at once and its frame is drawn then; the ticks after - // it run from it. - var wait = timeout_ms; - // Detached, nobody's key dismisses a message: they go on the clock - // (the pump's, after this wait), which wakes it. - if (!s.attached()) { - for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { - wait = if (wait == 0) 100 else @min(wait, 100); - break; - }; - } - const paced = s.test_clock == null and s.core.continuous(); - var tick: u64 = 0; - if (paced) { - const period = pardes.animation.frame_ns; - const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now; - if (tick < now) tick += (now - tick) / period * period; - s.pace_ns = tick; - wait = @intCast(@max(1, (tick -| now) / std.time.ns_per_ms)); - } - s.input_seen = false; - s.output_seen = false; - s.took_input = false; - s.took_output = false; - s.mail_only = true; - defer s.waited = true; - // Paced, what is not an input (a frame's ack, a pty's output) is - // taken in and the wait goes on to the tick: the acks alone ran the - // loop at the terminal's round trip. - while (true) { - s.waitOnce(wait); - if (!paced or s.input_seen or s.core.quit) break; - const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (now + std.time.ns_per_ms > tick) break; - wait = @intCast((tick - now) / std.time.ns_per_ms); - } - if (paced and s.input_seen) s.pace_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - // Output alone is drawn a frame a tick at most, what came in till - // then in one: a flood (`yes`, 4 KB a read) was drawn a read at a - // time, nearly all of its frames written over before they were - // seen. Never while what someone waits on is undrawn: an input - // (its frame held for the terminal's answer, FrameAck), or the - // focused pane's output soon after one, its echo (a remote shell's - // an RTT later). - while (!paced and s.output_seen and !s.input_seen and !s.core.quit and s.test_clock == null) { - if (s.input_ns > s.drawn_ns) break; - if (s.focused_ns > s.drawn_ns and s.focused_ns -| s.input_ns < std.time.ns_per_s) break; - const due = s.drawn_ns + pardes.animation.frame_ns; - const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (now + std.time.ns_per_ms > due) break; - s.waitOnce(@intCast((due - now) / std.time.ns_per_ms)); - } - } - - fn waitOnce(s: *Shell, wait: u32) void { - var batch: usize = 0; - const first = if (s.held) |held| held: { - s.held = null; - break :held held; - } else next: { - if (wait != 0) { - // A virtual clock moves a frame a wake while anything moves - // continuously (the glide), as the real one would. - s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0; - requestWake(s.io, wait); - } - pardes.turn.rest(); - const got = s.loop.nextEvent() catch { - pardes.turn.wake(); - s.core.quit = true; - return s.reloadWatched(); - }; - pardes.turn.wake(); - break :next got; - }; - batch = 1; - // A run of queued motions is one move to its last cell: each would - // otherwise redo hover and selection work the next one undoes. - var motion: ?@TypeOf(Command.value) = null; - var ev = first; - while (true) { - if (s.split(ev)) break; - if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) { - if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or - @as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods))) - { - _ = s.apply(m); - }; - motion = ev; - } else { - if (motion) |m| _ = s.apply(m); - motion = null; - if (s.apply(ev)) break; - } - if (!s.in_paste and batch >= 64) break; - ev = (s.loop.tryEvent() catch null) orelse break; - batch += 1; - } - if (motion) |m| _ = s.apply(m); - // An exit's wake (a .nop) or output an exit waited behind: told - // here, inside the step, so the frame after it shows it. - s.takeExits(); - s.reloadWatched(); - } - - /// With replica clients, a wait (one pump, one unit) takes one step of - /// a person's input, and none after a pty's output: a step reads the - /// terminals as the clients' deltas bring them, sent after each unit - /// (docs/next-daemon.md, part B terminal notes). One that must wait is - /// held for the next. Whether `ev` is. - fn split(s: *Shell, ev: @TypeOf(Command.value)) bool { - if (!s.peers.recording) return false; - switch (ev) { - .pty_read => { - s.took_output = true; - return false; - }, - .key_press => if (s.in_paste) return false, - .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {}, - else => return false, - } - if (s.took_output or s.took_input) { - s.held = ev; - s.input_seen = true; - return true; - } - s.took_input = true; - return false; - } - - fn apply(s: *Shell, event: @TypeOf(Command.value)) bool { - const core = s.core; - const tz_event = tracy.zone(@src(), "event"); - defer tz_event.end(); - // A key's or a click's time, for its latency to the frame that - // answers it (FrameStats): when the loop takes it in. - switch (event) { - .key_press => { - core.frames.input(pardes.FrameStats.nowNs()); - s.input_seen = true; - }, - .mouse => |m| if (m.type == .press) { - core.frames.input(pardes.FrameStats.nowNs()); - s.input_seen = true; - }, - .paste, .paste_start, .winsize => s.input_seen = true, - else => {}, - } - if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (event != .replica_mail) s.mail_only = false; - // A terminal's input goes into its view; a closed one's last is - // dropped. - switch (event) { - .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { - if (s.terms[s.from] == null and s.local()) { - if (event == .paste) s.gpa.free(@constCast(event.paste)); - return false; - } - if (s.local() and s.remote == null) core.toView(s.from); - }, - else => {}, - } - switch (event) { - .nop => {}, - .from => |k| s.from = k, - .winched => s.winched(), - // A terminal hung up (its stub passes the hangup on) or its stub - // died (a forked session's death signal): that one's input has - // ended. A HUP says not whose: each is asked. - .hangup => for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on and sc.hungUp()) { - s.from = @intCast(k); - if (s.apply(.quit)) return true; - }, - .wake => if (s.test_clock) |*virtual| { - virtual.* = @max(virtual.*, s.wake_to); - }, - .quit => { - if (s.remote) |c| { - c.link.quit = true; - return true; - } - // One of several: its view goes with it. - if (pardes.views.count(core) > 1) { - s.dropView(core.view, .detach); - return true; - } - // The terminal went: a session the daemon keeps carries on - // without it, to be attached again. Gone before the first - // frame, the reader that takes the daemon's `ok` (kept - // waits on it) is not started yet: started here. - daemon.watch(s.loop, deliverNote); - if (daemon.kept()) { - if (s.attached()) s.leaveTerminal(); - return true; - } - core.quit = true; - return true; - }, - .attach => |a| s.attachTerminal(a.tty, a.stub, null), - .adopted => |a| s.adoptShell(a.pid, a.fd), - .replica => |j| { - s.peers.handed(j.fd, j.view); - s.input_seen = true; - }, - .replica_mail => s.input_seen = true, - .said => |said| if (s.remote) |c| { - c.link.take(said); - if (said == .refused) return true; - } else switch (said) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), - .checked => {}, - }, - .link_gone => if (s.remote) |c| { - c.link.quit = true; - c.link.gone = true; - return true; - }, - .focus_in => s.feed(.{ .focus = true }), - .focus_out => { - s.feed(.pointer_leave); - s.feed(.{ .focus = false }); - }, - .winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws), - .pty_read => |pr| { - tookRead(s.io, pr.id); - s.output_seen = true; - if (pr.id == core.active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (s.gens[pr.id] == pr.gen) - core.update(.{ .output = .{ .pane = @intCast(pr.id), .bytes = pr.bytes } }); - s.gpa.free(pr.bytes); - // An exit waiting behind this output may be told now. - s.takeExits(); - return true; - }, - .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) { - if (s.ptys[e.id]) |*pt| { - pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks - // A command's pty stays open until its child has exited: - // closing it would hang up one that runs on without it. - // Its exit, if it came first, is told now its output is in. - if (pt.cmd.watched) { - host_io.commandEof(core, &s.ptys, e.id, s, closeWatched); - return true; - } - _ = libc.close(pt.file.handle); - // Unwatched, a command's exit is read here, as its end, - // and a shell's, for a run waiting on it and the log. - const command = if (core.panes[e.id]) |pn| pn.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status == null) host_io.retireShell(pt.pid); - s.ptys[e.id] = null; - if (command or status != null) core.update(.{ .exited = .{ .pane = @intCast(e.id), .status = status } }); - } - core.update(.{ .eof = .{ .pane = @intCast(e.id) } }); - }, - .key_press => |key| if (s.in_paste) { - const bytes = pasteBytes(key); - const room = max_paste_bytes -| s.paste_buf.written().len; - s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; - } else s.feed(vaxis_input.keyEvent(key)), - .mouse => |m| { - const pdf_before = nativePdfWheelTarget(core, m); - if (mouseEvent(m)) |ev| s.feed(ev); - if (pdf_before) |before| { - if (core.panes[before.pane]) |pane| { - if (pane.pdfPage()) |page| { - if (page != before.page) return true; - } - } - } - }, - .paste => |bytes| { - s.feed(.{ .paste = bytes }); - s.gpa.free(@constCast(bytes)); - }, - .paste_start => { - s.in_paste = true; - s.paste_buf.clearRetainingCapacity(); - }, - .paste_end => { - s.in_paste = false; - const pasted = s.paste_buf.written(); - if (pasted.len > 0) s.feed(.{ .paste = pasted }); - s.paste_buf.clearRetainingCapacity(); - }, - .files_changed => s.check_files = true, - .fs_ready => {}, - .lsp_done => |d| { - core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); - if (d.rows) |rows| s.lsp_gpa.free(rows); - if (s.lsp_task) |*t| if (t.id == d.id) { - t.future.await(s.io); - s.lsp_task = null; - }; - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - core.setStatus(core.active, message.stamp(&mbuf, "lsp", text)); - s.lsp_gpa.free(text); - }, - .pipe_done => |response_value| { - var response = response_value; - core.update(.{ .pipe_resp = .{ - .id = response.id, - .success = response.success, - .outputs = response.outputs, - .failure = response.failure, - } }); - response.deinit(s.gpa); - s.pipe_tasks.finish(s.io, response_value.id); - }, - .search_rows => |b| { - core.update(.{ .search = b }); - b.deinit(s.gpa); - }, - } - return false; - } - - /// Terminal `screen` (the live view's) is `ws` big. - fn resized(s: *Shell, screen: ?*Screen, ws: vaxis.Winsize) void { - if (screen) |sc| { - sc.size = ws; - sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {}; - } - s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } }); - } - - /// A SIGWINCH: each terminal whose size it changed is resized, in its - /// view (a terminal reporting in band says so as input). - fn winched(s: *Shell) void { - for (s.terms, 0..) |slot, k| { - const sc = slot orelse continue; - if (!sc.on or sc.vx.state.in_band_resize) continue; - const ws = sc.tty.getWinsize() catch continue; - if (sc.size) |was| if (std.meta.eql(was, ws)) continue; - if (s.remote == null) s.core.toView(@intCast(k)); - s.resized(sc, ws); - } - } - - fn reloadWatched(s: *Shell) void { - if (!s.check_files) return; - s.check_files = false; - if (file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) - s.loop.postEvent(.files_changed) catch {}; - } - - /// ponytail: a terminal's scrollback under the wheel lands here (the - /// wheel reaches the core as a mouse event, not counted as the GUI's - /// notches are); `wheeled` from the mouse event if it should glide. - fn stepGlide(ctx: ?*anyopaque) void { - const s = of(ctx); - if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null); - } - - fn pollFrame(ctx: ?*anyopaque) void { - const s = of(ctx); - stepGlide(ctx); - if (s.fs) |f| if (f.tick().pending) { - _ = s.loop.tryPostEvent(.fs_ready) catch {}; - }; - for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); - }; - - const sc = s.term() orelse return; - s.core.native_image_patches = sc.feed.shm.load(.acquire); - if (sc.caps_pending and sc.on and sc.vx.queries_done.load(.unordered)) { - sc.caps_pending = false; - sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; - s.core.native_images = sc.vx.caps.kitty_graphics; - if (sc.vx.caps.kitty_graphics) kittyShmProbe(sc.tty.writer(), &sc.feed); - sc.vx.queueRefresh(); - s.core.needs_frame = true; - } - } - - fn present(ctx: ?*anyopaque, canonical: *const pardes.Surface) void { - const s = of(ctx); - const sc = s.term() orelse return; - const vx = &sc.vx; - sc.tracks = canonical.panelTracks(); - // The last frame is not answered yet: this one stays owed, and the - // answer's wake draws the state as it is then. - if (sc.feed.ack.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { - s.core.present_skipped = true; - return; - } - _ = s.frame.reset(.retain_capacity); - const surface = panel_compositor.compose( - s.frame.allocator(), - @constCast(canonical), - sc.tracks, - s.core.theme().bg, - ) catch return; - const tz_cells = tracy.zone(@src(), "surface->vaxis"); - const win = vx.window(); - const truecolor = vx.caps.rgb or colortermTruecolor(); - // Each of the shell's own motions below asks for frames while it runs. - if (sc.glide.pending) sc.glide.measure(s.gpa, canonical); - if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion); - s.core.shell_continuous = sc.glide.moving(); - s.core.frames.scroll = @round(sc.glide.follow.offset); - const glided = pardes.glide.shifted(&sc.glide, s.frame.allocator(), surface) catch surface; - const shadowed = chipShadows(s.frame.allocator(), glided, s.core, truecolor) catch glided; - const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; - const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; - paintCells(win, trailed.cells, trailed.cols, trailed.rows); - if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), trailed.cols, trailed.rows); - tz_cells.end(); - for (surface.images[0..surface.nimages]) |maybe| { - const place = maybe orelse continue; - if (panel_compositor.hidesAttachment(surface.panelTracks(), place.serial)) continue; - if (comptime pardes.pdf_enabled) { - if (!kittyImageRepresentable(place)) continue; - } - const key = place.cacheKey(); - if (!sc.kitty.contains(key) and vx.caps.kitty_graphics and sc.feed.shm.load(.acquire)) shm: { - var buf: [64]u8 = undefined; - kitty_shm_serial +%= 1; - // Bounded: a segment this many transmissions old was never - // read (a terminal reads one as its command arrives), and a - // tmpfs holds it in memory until it goes. - if (kitty_shm_serial > kitty_shm_window) { - var old_buf: [64]u8 = undefined; - if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {} - } - const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; - if (!kittyShmWrite(name, place.rgba)) break :shm; - if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| - sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id) - else - _ = libc.shm_unlink(name); - } - if (!sc.kitty.contains(key) and vx.caps.kitty_graphics) { - const enc = std.base64.standard.Encoder; - if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { - defer s.gpa.free(b64); - _ = enc.encode(b64, place.rgba); - if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| - sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); - } else |_| {} - } - if (sc.kitty.get(key)) |cached| { - if (comptime !pardes.pdf_enabled) { - const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); - cached.draw(child, .{ .scale = .contain }) catch {}; - } else { - if (place.native.exact) { - if (exactKittyPlacement(place, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix)) |placement| { - // The cell keeps its own glyph and colours - // (Image.draw would reset them): a fragment - // short of the cell shows the pane under it. - const x = place.x + placement.cell_x; - if (win.readCell(x, place.y)) |under| { - var cell = under; - cell.image = .{ .img_id = cached.id, .options = placement.options }; - win.writeCell(x, place.y, cell); - } - } - } else if (place.native.fit == .contain) { - const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); - cached.draw(child, .{ .scale = .contain }) catch {}; - } else if (kittyPlacement( - place, - vx.screen.width, - vx.screen.height, - vx.screen.width_pix, - vx.screen.height_pix, - )) |placement| { - const child = win.child(.{ - .x_off = @as(i17, place.x) + placement.cell_x, - .y_off = @as(i17, place.y) + placement.cell_y, - .width = placement.cell_cols, - .height = placement.cell_rows, - }); - cached.draw(child, placement.options) catch {}; - } - } - } - } - while (true) { - var stale: [pardes.MAX_PANES]pardes.ImageCacheKey = undefined; - var stale_len: usize = 0; - var image_iterator = sc.kitty.iterator(); - while (image_iterator.next()) |entry| { - if (surfaceHasKittyKey(surface, entry.key_ptr.*)) continue; - stale[stale_len] = entry.key_ptr.*; - stale_len += 1; - if (stale_len == stale.len) break; - } - for (stale[0..stale_len]) |key| if (sc.kitty.fetchRemove(key)) |removed| - vx.freeImage(sc.tty.writer(), removed.value.id); - if (stale_len < stale.len) break; - } - if (glided.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar); - const tz_render = tracy.zone(@src(), "vx.render"); - const before = sc.tty.tty_writer.pos + sc.tty.writer().end; - vx.render(sc.tty.writer()) catch {}; - // The frame's cost to the terminal (FrameStats.Frame.bytes): what - // vaxis's diff of the cells wrote. - s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), sc.tty.tty_writer.pos + sc.tty.writer().end -| before)); - if (sc.tty.tty_writer.pos + sc.tty.writer().end != before) sc.feed.ack.ask(sc.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); - s.drawn_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - tz_render.end(); - } - - fn postPresent(ctx: ?*anyopaque) void { - const s = of(ctx); - if (s.term()) |sc| s.core.acknowledgePanelPresentation(sc.tracks); - tracy.frameMark(); - } - - fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { - const s = of(ctx); - for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) { - std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]); - s.adoptions_len -= 1; - 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.screen_h, s.core.screen_w, s.fs) 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: 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.threads_ok)) - 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); - copyToClipboard(&sc.vx, &sc.tty, s.gpa, text); - } - - 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 }); - requestClipboard(&sc.vx, &sc.tty); - } - - 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); - s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); - } - - 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.active, "pipe", error.WorkersUnavailable); - } - selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); - } - - 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); - } - - /// 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; - }; - 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); - } -}; - -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_wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_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_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_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.active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_wait.?.id, - .kind = .status, - .pane = @intCast(core.active), - .offset = 0, - .arg = "", - }; - Shell.lsp(&shell, req); - try std.testing.expect(core.lsp_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 copyToClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty, gpa: std.mem.Allocator, text: []const u8) void { - if (text.len == 0) return; - vx.copyToSystemClipboard(tty.writer(), text, gpa) catch {}; -} - -fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { - vx.requestSystemClipboard(tty.writer()) catch {}; -} - -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: @TypeOf(Command.value) = 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; - } - } - } -} - -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 {}; -} - -/// 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 pasteBytes(key: vaxis.Key) []const u8 { - const text = key.text orelse ""; - if (text.len > 0) return text; - const cp = vaxis_input.mapKey(vaxis_input.effCp(key)); - if (cp == pardes.Key.tab) return "\t"; - if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n"; - return ""; -} - -test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - vx.queries_done.store(false, .unordered); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - var reader: Reader = .{ - .parts = &.{ - // The startup width queries' answers from a terminal without - // explicit width (foot, ghostty, tmux): two F3s, typed at the prompt. - "\x1b[1;1R\x1b[1;1R\x1b[?62;c", - // Kitty reports Ctrl and Shift pressed on their own: the Ctrl of a - // Ctrl-V typed `\x1b[57442;5u` into the shell. - "\x1b[57442;5u\x1b[57441;2u\x1b[57358u", - // F3, F5 and Insert the kitty way, F3 the legacy way and the - // keypad's Up: once typed as private-use junk, now what htop, - // mc and vim read them as. - "\x1b[13~\x1b[15~\x1b[2~\x1bOR\x1b[57419u", - "\x1b[104;;104u", - }, - }; - try readInput(&loop, &reader, &vx, &feed); - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - while (try loop.tryEvent()) |event| switch (event) { - .key_press => |key| core.update(vaxis_input.keyEvent(key)), - else => {}, - }; - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings("\x1bOR\x1b[15~\x1b[2~\x1bOR\x1b[Ah", written.written()); -} - -test "the terminal's keys reach a program as its cursor keys' mode and keyboard flags say" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - // What the outer terminal sends, what the program asked for, and what - // it should read. - const Case = struct { modes: []const u8, in: []const u8, sent: []const u8 }; - const cases = [_]Case{ - .{ .modes = "", .in = "\x1b[A\x1b[H\x1bOP\x1b[15~", .sent = "\x1b[A\x1b[H\x1bOP\x1b[15~" }, - .{ .modes = "\x1b[?1h", .in = "\x1b[A\x1b[F\x1b[1;5D", .sent = "\x1bOA\x1bOF\x1b[1;5D" }, - .{ .modes = "\x1b[?1l\x1b[>7u", .in = "\x1b[99;5u\x1b[97;3u\x1b[A", .sent = "\x1b[99;5u\x1b[97;3u\x1b[1;1:1A" }, - }; - for (cases) |case| { - core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); - while (core.nextEffect()) |_| {} - var parser: vaxis.Parser = .{}; - var bytes = case.in; - while (bytes.len > 0) { - const result = try parser.parse(bytes, gpa); - if (result.n == 0) break; - bytes = bytes[result.n..]; - if (result.event) |event| switch (event) { - .key_press => |key| core.update(vaxis_input.keyEvent(key)), - else => {}, - }; - } - written.clearRetainingCapacity(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings(case.sent, written.written()); - } -} - -test "keypad Enter matches Return for editor input terminal writes and paste" { - for ([_]u21{ vaxis.Key.enter, vaxis.Key.kp_enter }) |codepoint| { - const key: vaxis.Key = .{ .codepoint = codepoint }; - const event = vaxis_input.keyEvent(key); - try std.testing.expectEqual(pardes.Key.enter, event.key.cp); - try std.testing.expectEqualStrings("\n", pasteBytes(key)); - { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("ab"); - core.update(.{ .key = .{ .cp = 'i' } }); - core.update(event); - try std.testing.expectEqualStrings("\nab", pane.file.?.content); - } - { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - core.update(event); - var written: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer written.deinit(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings("\r", written.written()); - } - } -} - -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(); - for ([_][]const u8{ "\x1b[<1;42;0M", "\x1b[<0;0;5M", "\x1b[<32;0;0M", "\x1b[<0;0;0m" }) |sequence| { - var parser: vaxis.Parser = .{}; - const result = try parser.parse(sequence, std.testing.allocator); - const m = result.event.?.mouse; - const event = mouseEvent(m) orelse continue; - try std.testing.expect(event.mouse.col <= 41 and event.mouse.row <= 4); - p.update(event); - } -} - -test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 and X2 are" { - for ([_]vaxis.Mouse.Button{ .button_8, .button_9 }, [_]pardes.Mouse.Button{ .back, .forward }) |from, to| { - const event = mouseEvent(.{ .col = 3, .row = 2, .button = from, .mods = .{}, .type = .press }).?; - try std.testing.expectEqual(to, event.mouse.button); - } -} - -/// 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. -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 = vaxisStyle(cell.style), - }); - } - } -} - -test "a fade sends the text it dims, not the blanks beside it" { - const gpa = std.testing.allocator; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(std.testing.io, gpa, &env, .{}); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - defer vx.deinit(gpa, &out.writer); - try vx.resize(gpa, &out.writer, .{ .rows = 1, .cols = 32, .x_pixel = 0, .y_pixel = 0 }); - // `a`, a gap, `b`, a two-cell gap, `c`, a gap, an underlined blank - // (which shows its ink) and one more blank. - var cells: [32]pardes.Cell = @splat(.{ .default = false }); - cells[0].text[0] = 'a'; - cells[12].text[0] = 'b'; - cells[15].text[0] = 'c'; - cells[30].style.ul = .single; - var sent: [2][]u8 = .{ &.{}, &.{} }; - defer for (sent) |bytes| gpa.free(bytes); - for ([_][3]u8{ .{ 200, 200, 200 }, .{ 90, 90, 90 } }, 0..) |ink, frame| { - for (&cells) |*cell| cell.style.fg = .{ .rgb = ink }; - out.clearRetainingCapacity(); - paintCells(vx.window(), &cells, 32, 1); - try vx.render(&out.writer); - sent[frame] = try out.toOwnedSlice(); - } - // Against a cleared screen every cell goes. After the fade the letters - // go and the underlined blank; every plain blank is jumped. - try std.testing.expectEqual(@as(usize, 29), std.mem.count(u8, sent[0], " ")); - try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, sent[1], " ")); - try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'b') != null); - try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'c') != null); - try std.testing.expect(std.mem.indexOf(u8, sent[1], "90:90:90") != null); - try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'a') != null); -} - -/// T1 (§9.2): each notice chip casts a shadow one cell right and one down, -/// inside its own pane's body: its ground 35% toward black in OKLab on a -/// cell with text; on a blank one a half block (▌ on the right, ▀ below, -/// ▘ at the corner) in the darker colour, so the shadow is half a cell -/// thick and reads as one. Never the cursor's cell, a selection, a tag or -/// another chip. Truecolor terminals only. -fn chipShadows(arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { - if (!core.settings.chip_shadow or !truecolor) return surface; - const regions = surface.regionList(); - const any = for (regions) |region| { - if (region.kind == .notice) break true; - } else false; - if (!any) return surface; - const out = try arena.create(pardes.Surface); - out.* = surface.*; - out.cells = try arena.dupe(pardes.Cell, surface.cells); - const theme = core.theme(); - const page = theme.bg orelse pardes.colors.null_page; - for (regions) |chip| { - if (chip.kind != .notice or chip.rect.w == 0) continue; - const body = for (regions) |region| { - if (region.kind == .body and region.owner == chip.owner) break region.rect; - } else continue; - const right = chip.rect.x + chip.rect.w; - const below = chip.rect.y + chip.rect.h; - // The column right of it (from its second row), the row below (from - // its second column), and the corner. - var y = chip.rect.y; - while (y <= below) : (y += 1) { - var x = chip.rect.x; - while (x <= right) : (x += 1) { - const side = x == right and y > chip.rect.y and y < below; - const foot = y == below and x > chip.rect.x and x < right; - const corner = x == right and y == below; - if (!side and !foot and !corner) continue; - if (x < body.x or y < body.y or x >= body.x + body.w or y >= body.y + body.h or x >= out.cols or y >= out.rows) continue; - if (surface.cursor) |cu| if (cu.x == x and cu.y == y) continue; - const covered = for (regions) |region| { - if ((region.kind == .notice or region.kind == .tag or region.kind == .grip) and x >= region.rect.x and x < region.rect.x + region.rect.w and y >= region.rect.y and y < region.rect.y + region.rect.h) break true; - } else false; - if (covered) continue; - const cell = &out.cells[@as(usize, y) * out.cols + x]; - const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue; - const dark = pardes.colors.mixOklab(ground, .{ 0, 0, 0 }, 0.35); - const blank = cell.default or cell.len == 0 or (cell.len == 1 and cell.text[0] == ' '); - if (blank) { - const glyph: []const u8 = if (corner) "▘" else if (side) "▌" else "▀"; - cell.* = .{ .default = false, .style = .{ .fg = .{ .rgb = dark }, .bg = .{ .rgb = ground } } }; - @memcpy(cell.text[0..glyph.len], glyph); - cell.len = @intCast(glyph.len); - } else { - cell.default = false; - cell.style.bg = .{ .rgb = dark }; - } - } - } - } - return out; -} - -/// T7 (§9.2): a pane whose view moved (Region.line) has its scroll thumb -/// brighten, drawn most of the way to the text's colour, and fade back -/// over 250 ms with an ease-out: where you are in the file, as you move. -/// The rail is chrome, not a focus indicator. Truecolor terminals only. -const ThumbFlash = struct { - lines: [pardes.MAX_PANES]i32 = @splat(std.math.minInt(i32)), - since: [pardes.MAX_PANES]u64 = @splat(0), - - const life_ns: u64 = 250 * std.time.ns_per_ms; - - fn apply(flash: *ThumbFlash, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { - const on = core.settings.thumb_flash and truecolor and core.settings.motion != .off; - var out: ?*pardes.Surface = null; - const theme = core.theme(); - const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc }; - for (surface.regionList()) |body| { - if (body.kind != .body or body.owner >= flash.lines.len) continue; - const id = body.owner; - if (flash.lines[id] != std.math.minInt(i32) and flash.lines[id] != body.line) flash.since[id] = core.now_ns; - flash.lines[id] = body.line; - const age = core.now_ns -| flash.since[id]; - if (!on or flash.since[id] == 0 or age >= life_ns) continue; - const rail = for (surface.regionList()) |region| { - if (region.kind == .rail and region.owner == id) break region; - } else continue; - if (rail.thumb_h == 0) continue; - const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); - const strength = 0.6 * (1 - t) * (1 - t); - if (out == null) { - const copy = try arena.create(pardes.Surface); - copy.* = surface.*; - copy.cells = try arena.dupe(pardes.Cell, surface.cells); - out = copy; - } - const o = out.?; - var y = rail.rect.y + rail.thumb_y; - while (y < rail.rect.y + rail.thumb_y + rail.thumb_h and y < o.rows) : (y += 1) { - var x = rail.rect.x; - while (x < rail.rect.x + rail.rect.w and x < o.cols) : (x += 1) { - const cell = &o.cells[@as(usize, y) * o.cols + x]; - const ground: [3]u8 = switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => continue, - }; - if (!std.mem.eql(u8, &ground, &core.chromeTheme().scroll_thumb)) continue; - cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) }; - } - } - core.shell_continuous = true; - } - return out orelse surface; - } -}; - -/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does -/// not answer vaxis's query (§9.2: vaxis caps or COLORTERM). -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"); -} - -/// T2 (docs/render-pipeline.md §9.2): the cursor jumping three cells or -/// more leaves a trail of three to five cells along its path, just behind -/// it, their ground drawn toward the text's colour, most beside the -/// cursor, all fading out over 120 ms. Truecolor terminals only; a cell a -/// frame changes, a few bytes. Never the cursor's own cell, a selection or -/// anything outside the focused pane's body; off with Motion off. -const JumpTrail = struct { - last: ?[2]u16 = null, - from: [2]u16 = .{ 0, 0 }, - to: [2]u16 = .{ 0, 0 }, - start_ns: u64 = 0, - active: bool = false, - - const life_ns: u64 = 120 * std.time.ns_per_ms; - - fn apply(trail: *JumpTrail, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { - defer core.shell_continuous = trail.active or core.shell_continuous; - const on = core.settings.jump_trail and truecolor and core.settings.motion != .off; - const cursor = surface.cursor orelse { - trail.active = false; - return surface; - }; - const here: [2]u16 = .{ cursor.x, cursor.y }; - if (trail.last) |was| { - const dx = @as(i32, here[0]) - was[0]; - const dy = @as(i32, here[1]) - was[1]; - if (on and @max(@abs(dx), @abs(dy)) >= 3) { - trail.* = .{ .last = here, .from = was, .to = here, .start_ns = core.now_ns, .active = true }; - } - } - trail.last = here; - if (!on or !trail.active) { - trail.active = false; - return surface; - } - const age = core.now_ns -| trail.start_ns; - if (age >= life_ns or !std.meta.eql(trail.to, here)) { - trail.active = false; - return surface; - } - const out = try arena.create(pardes.Surface); - out.* = surface.*; - out.cells = try arena.dupe(pardes.Cell, surface.cells); - const theme = core.theme(); - const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc }; - const page = theme.bg orelse pardes.colors.null_page; - const body = for (surface.regionList()) |region| { - if (region.kind == .body and region.owner == core.active) break region.rect; - } else return out; - const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); - const fade = (1 - t) * (1 - t); - const dx = @as(f32, @floatFromInt(@as(i32, trail.from[0]) - trail.to[0])); - const dy = @as(f32, @floatFromInt(@as(i32, trail.from[1]) - trail.to[1])); - const span = @max(@abs(dx), @abs(dy)); - const n: usize = @intFromFloat(std.math.clamp(@round(span / 4), 3, 5)); - var k: usize = 1; - var last_cell: ?[2]i32 = null; - var step: f32 = 1; - while (k <= n and step <= span) : (step += 1) { - const x: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[0])) + dx * step / span)); - const y: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[1])) + dy * step / span)); - if (last_cell) |seen| if (seen[0] == x and seen[1] == y) continue; - last_cell = .{ x, y }; - defer k += 1; - if (x < body.x or y < body.y or x >= @as(i32, body.x) + body.w or y >= @as(i32, body.y) + body.h) continue; - const cell = &out.cells[@as(usize, @intCast(y)) * out.cols + @as(usize, @intCast(x))]; - const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue; - const strength = 0.55 * fade * (1 - @as(f32, @floatFromInt(k - 1)) / @as(f32, @floatFromInt(n))); - if (strength < 0.02) continue; - const was_default = cell.default; - cell.default = false; - if (was_default) cell.style = .{}; - cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) }; - } - return out; - } -}; - -fn paintCursor(win: vaxis.Window, x: u16, y: u16, bar: bool) void { - win.showCursor(x, y); - win.setCursorShape(if (bar) .beam else .default); -} - -fn vaxisStyle(s: pardes.CellStyle) vaxis.Style { - return .{ - .fg = vaxisColor(s.fg), - .bg = vaxisColor(s.bg), - .bold = s.bold, - .dim = s.dim, - .italic = s.italic, - .blink = s.blink, - .reverse = s.reverse, - .invisible = s.invisible, - .strikethrough = s.strikethrough, - .ul_style = switch (s.ul) { - .off => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; -} - -fn vaxisColor(c: pardes.Color) vaxis.Color { - return switch (c) { - .default => .default, - .index => |i| .{ .index = i }, - .rgb => |rgb| .{ .rgb = rgb }, - }; -} - -test "a jump leaves a trail of a few cells behind the cursor that fades in 120 ms" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); - try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); - core.settings.jump_trail = true; - for (0..40) |_| core.update(.tick); - core.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const s = try core.render(arena.allocator()); - const body = for (s.regionList()) |region| { - if (region.kind == .body) break region.rect; - } else return error.NoBody; - var trail: JumpTrail = .{}; - core.now_ns = std.time.ns_per_s; - s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; - _ = try trail.apply(arena.allocator(), s, core, true); - // Ten cells right: a trail back toward where it was. - s.cursor = .{ .x = body.x + 12, .y = body.y + 1 }; - core.now_ns += 16 * std.time.ns_per_ms; - const lit = try trail.apply(arena.allocator(), s, core, true); - try std.testing.expect(trail.active and core.shell_continuous); - var changed: usize = 0; - for (lit.cells, s.cells, 0..) |a, b, i| { - if (std.meta.eql(a.style.bg, b.style.bg)) continue; - changed += 1; - // On the cursor's row, behind it, never its own cell. - try std.testing.expectEqual(@as(usize, body.y + 1), i / s.cols); - try std.testing.expect(i % s.cols < body.x + 12 and i % s.cols > body.x + 2); - } - try std.testing.expect(changed >= 3 and changed <= 5); - // Gone by 120 ms; a step of a cell leaves none; nor a terminal without - // truecolor. - core.now_ns += 130 * std.time.ns_per_ms; - core.shell_continuous = false; - const faded = try trail.apply(arena.allocator(), s, core, true); - try std.testing.expect(faded == s and !trail.active and !core.shell_continuous); - s.cursor = .{ .x = body.x + 13, .y = body.y + 1 }; - try std.testing.expect(try trail.apply(arena.allocator(), s, core, true) == s); - s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; - try std.testing.expect(try trail.apply(arena.allocator(), s, core, false) == s); -} - -test "a notice chip casts a cell's shadow right and down, inside its body, off the cursor" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); - try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); - core.settings.chip_shadow = true; - try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice")); - for (0..60) |_| core.update(.tick); - core.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const s = try core.render(arena.allocator()); - const chip = for (s.regionList()) |region| { - if (region.kind == .notice) break region.rect; - } else return error.NoNotice; - s.cursor = null; - const out = try chipShadows(arena.allocator(), s, core, true); - try std.testing.expect(out != s); - var changed: usize = 0; - for (out.cells, s.cells, 0..) |a, b, i| { - if (std.meta.eql(a, b)) continue; - changed += 1; - const x = i % s.cols; - const y = i / s.cols; - // Right of the chip or below it, never inside it. - try std.testing.expect(x == chip.x + chip.w or y == chip.y + chip.h); - try std.testing.expect(!(x >= chip.x and x < chip.x + chip.w and y >= chip.y and y < chip.y + chip.h)); - } - try std.testing.expect(changed >= chip.w - 1); - // Off, or without truecolor: the frame as it was. - try std.testing.expect(try chipShadows(arena.allocator(), s, core, false) == s); - core.settings.chip_shadow = false; - try std.testing.expect(try chipShadows(arena.allocator(), s, core, true) == s); -} - -test "a scrolled pane's thumb brightens and fades back in 250 ms" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([200][20]u8, @splat("some text on a line\n".*)))); - try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); - core.settings.thumb_flash = true; - for (0..40) |_| core.update(.tick); - core.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var flash: ThumbFlash = .{}; - core.now_ns = std.time.ns_per_s; - const first = try core.render(arena.allocator()); - try std.testing.expect(try flash.apply(arena.allocator(), first, core, true) == first); - pane.scrollBy(20); - core.now_ns += 16 * std.time.ns_per_ms; - const moved = try core.render(arena.allocator()); - const lit = try flash.apply(arena.allocator(), moved, core, true); - try std.testing.expect(lit != moved and core.shell_continuous); - var brighter: usize = 0; - for (lit.cells, moved.cells) |a, b| { - if (!std.meta.eql(a.style.bg, b.style.bg)) brighter += 1; - } - try std.testing.expect(brighter >= 1); - core.now_ns += 300 * std.time.ns_per_ms; - core.shell_continuous = false; - const later = try core.render(arena.allocator()); - try std.testing.expect(try flash.apply(arena.allocator(), later, core, true) == later); - try std.testing.expect(!core.shell_continuous); -} |
