summaryrefslogtreecommitdiff
path: root/src/tui/tui.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-18 21:23:22 -0300
committerGabriel Schneider <[email protected]>2026-11-18 21:43:03 -0300
commitf9a3179542012ec1a700e2020ac9f616b819f972 (patch)
tree73f4cb241876196331f7b28c9f773301bd341a7f /src/tui/tui.zig
parenta75956bb3443aa8aac778d2ff12c42f5ef99e0e9 (diff)
downloadpardes-f9a3179542012ec1a700e2020ac9f616b819f972.tar.gz
pardes-f9a3179542012ec1a700e2020ac9f616b819f972.zip
dev: the frontends (dev/tui, dev/gui, the macOS app's Swift and resources in dev/macos), host_io, file_watch, fonts, the lsp client and Scip, Art, jump_trail, glide and vaxis_input into dev/ (the reorganisation's tree, step 2b): module `dev` (dev/root.zig) beside the core and the runtime, each naming the others; the window wired into it, sketchbook's devices imported as `sketchbook` (its `dev` would be ours); pardes.zig keeps its re-exports (host_io, file_watch, glide, fonts) so every caller reads as before; core-test and shell-test run the devices' test program too, so the same tests run (the ledger, tui and gui); nothing else changes: frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/tui/tui.zig')
-rw-r--r--src/tui/tui.zig3386
1 files changed, 0 insertions, 3386 deletions
diff --git a/src/tui/tui.zig b/src/tui/tui.zig
deleted file mode 100644
index cb709ff1..00000000
--- a/src/tui/tui.zig
+++ /dev/null
@@ -1,3386 +0,0 @@
-const filesystem = @import("../fs.zig");
-const std = @import("std");
-const builtin = @import("builtin");
-const posix = std.posix;
-/// libc: termios, signals, kitty shm segments and the fds a terminal hands over.
-const libc = std.c;
-const vaxis = @import("vaxis");
-const pardes = @import("../pardes.zig");
-const JumpTrail = @import("../jump_trail.zig");
-const Art = @import("../Art.zig");
-const vaxis_input = @import("../vaxis_input.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("runtime").ninep_io;
-const daemon = @import("runtime").daemon;
-const host_io = @import("../host_io.zig");
-const upgrade = @import("runtime").upgrade;
-const replica = @import("../replica.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 the terminal's input reader keeps: its graphemes, the frame it
-/// waits on the answer to, and the shm probe.
-const Feed = struct {
- 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),
-};
-
-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 {};
-}
-
-/// What the loop's queue carries: a terminal's input, a pane's output, a
-/// worker's answer, a wake.
-const Msg = 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,
- /// 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,
- /// A kind's job done on a worker (host_io.KindJob).
- kind_job: *host_io.KindJob,
- 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,
-};
-const Loop = vaxis.Loop(Msg);
-
-fn startInput(loop: *Loop, sc: *Screen) !void {
- 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)});
- };
- loop.postEvent(.quit) catch {};
-}
-
-fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void {
- try loop.postEvent(.{ .winsize = try tty.getWinsize() });
- var parser: vaxis.Parser = .{};
- var buf: [1024]u8 = undefined;
- 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(loop, vx, &feed.cache, Msg, event, vx.opts.system_clipboard_allocator) catch |err| {
- if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste));
- 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;
-}
-
-/// What a test of a terminal's input needs: vaxis (its capabilities, its
-/// parser's allocator), the loop's queue and a feed, set up in place (vaxis
-/// keeps the environment's address) and torn down in the order vaxis needs.
-const TestInput = struct {
- env: std.process.Environ.Map,
- vx: vaxis.Vaxis,
- out: std.Io.Writer.Allocating,
- loop: Loop,
- feed: Feed,
-
- fn init(t: *TestInput) !void {
- const gpa = std.testing.allocator;
- t.env = try std.testing.environ.createMap(gpa);
- errdefer t.env.deinit();
- t.vx = try vaxis.init(std.testing.io, gpa, &t.env, .{ .system_clipboard_allocator = gpa });
- t.out = .init(gpa);
- t.loop = .init(std.testing.io, undefined, &t.vx);
- t.feed = .{};
- }
-
- fn deinit(t: *TestInput) void {
- t.vx.deinit(std.testing.allocator, &t.out.writer);
- t.out.deinit();
- t.env.deinit();
- }
-};
-
-/// A terminal that hands over `parts`, a read each (an empty one passed
-/// over), and says more follows (within `gap_ms`) while some are left.
-const TestReader = struct {
- parts: []const []const u8,
- next: usize = 0,
- gap_ms: u32 = 0,
- asked: bool = false,
-
- fn getWinsize(_: *TestReader) !vaxis.Winsize {
- return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
- }
-
- pub fn inputFollows(r: *TestReader, ms: u32) bool {
- r.asked = true;
- return r.next < r.parts.len and r.gap_ms <= ms;
- }
-
- fn read(r: *TestReader, buf: []u8) !usize {
- while (r.next < r.parts.len) {
- const part = r.parts[r.next];
- r.next += 1;
- if (part.len == 0) continue;
- @memcpy(buf[0..part.len], part);
- return part.len;
- }
- return 0;
- }
-};
-
-const PipeTasks = selection_pipe.Tasks;
-
-const Pty = struct {
- file: std.Io.File,
- pid: posix.pid_t,
- reader: std.Io.Future(error{OutOfMemory}!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 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 (one cell row): its `src` into its
-/// `at`, inside that 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.Placement,
- screen_cols: u16,
- screen_rows: u16,
- screen_pixel_w: u16,
- screen_pixel_h: u16,
-) ?KittyPlacement {
- const g: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at 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.dst.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.dst.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 },
- },
- };
-}
-
-/// A PDF's page over its body: declared to kitty by its columns where it
-/// is as wide as the body (fit to width), else by its rows, and its source
-/// cut so the declared cells never run past its clipped bottom.
-fn kittyPlacement(
- place: pardes.Placement,
- screen_cols: u16,
- screen_rows: u16,
- screen_pixel_w: u16,
- screen_pixel_h: u16,
-) ?KittyPlacement {
- const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8);
- const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16);
- const geometry: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null };
- const fit: enum { width, height } = if (geometry.dst.w >= @as(u32, place.dst.w) * cell_w) .width else .height;
-
- 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 (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,
- );
- },
- }
- if (declared_rows == 0 or declared_rows > safe_rows_u32) return null;
-
- const src_x = std.math.cast(u16, geometry.src.x) orelse return null;
- const src_y = std.math.cast(u16, geometry.src.y) orelse return null;
- const src_w = std.math.cast(u16, geometry.src.w) orelse return null;
- const src_h = std.math.cast(u16, safe_src_h) orelse return null;
- const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null;
- const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null;
- if (cell_x >= place.dst.w or cell_y >= place.dst.h) return null;
- const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null;
- const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null;
- const cell_cols = std.math.cast(u16, @min(
- @as(u32, place.dst.w - cell_x),
- (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w,
- )) orelse return null;
- const cell_rows = std.math.cast(u16, @min(
- @as(u32, place.dst.h - cell_y),
- (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h,
- )) orelse return null;
- if (cell_cols == 0 or cell_rows == 0) return null;
-
- return .{
- .cell_x = cell_x,
- .cell_y = cell_y,
- .cell_cols = cell_cols,
- .cell_rows = cell_rows,
- .options = .{
- .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h },
- .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null,
- .size = switch (fit) {
- .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null },
- .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null },
- },
- },
- };
-}
-
-fn kittyImageRepresentable(place: pardes.Placement) bool {
- return place.raster.w > 0 and place.raster.h > 0 and
- place.raster.w <= std.math.maxInt(u16) and place.raster.h <= std.math.maxInt(u16);
-}
-
-fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool {
- for (surface.placements.items) |place| {
- if (place.art.glyph or !kittyImageRepresentable(place)) continue;
- if (place.key == key) return true;
- }
- return false;
-}
-
-/// 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, detached 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 }, detached };
-
-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) };
- 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)),
- .detached => {},
- }
- 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 (`runClient`), drawn here.
-const Client = 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: *Client, 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 runClient(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;
- const allocs = pardes.memory.init(gpa);
- defer pardes.memory.deinit();
- pardes.Term.start(allocs.image);
- pardes.Kind.heap = allocs.addon;
- pardes.syntax.start(allocs.tree_sitter);
- defer {
- pardes.Term.stop();
- pardes.syntax.stop();
- }
- var o = opts;
- o.image_allocator = allocs.image;
- var joined: replica.Joined = undefined;
- var r = replica.join(gpa, &joined, path, session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
-
- 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) };
- defer screen.kitty.deinit();
- try screen.enter(try vaxis.Tty.init(io, &tty_buf));
- defer screen.leave();
- defer screen.glide.deinit(gpa);
- defer screen.art.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 client_link: Client = .{ .link = .{ .r = r, .fd = joined.fd } };
- const link = &client_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,
- .own = joined.view,
- .screen = &screen,
- .client = &client_link,
- };
-
- pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw };
- defer pardes.Kind.drawer = null;
- 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) {
- sh.core = r.core();
- sh.own = joined.view;
- link.reset(r, &joined);
- 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) {
- client_link.draw(&sh);
- } else if (sh.moving() and r.core().surface.cells.len != 0) {
- // The tty's own motions (its glide, a jump's trail): the last
- // frame again, moved on, as the session's terminal draws them
- // (`ownFrame`), not rendered again. One the terminal's answer
- // holds is skipped (the next tick's moves on): nothing of it
- // is written in the core, as `Client.draw` puts it back.
- const skipped = r.core().present_skipped;
- Shell.present(&sh, &r.core().surface);
- r.core().present_skipped = skipped;
- link.again += 1;
- }
- // Idle, its frame drawn: the next key needs no copy taken.
- if (loop.tryEvent() catch null) |ev| sh.held = ev else r.ready();
- // The session's own wait: an input drawn at once, the session's
- // units and deltas a frame a tick at most, the tty's own motions
- // on its grid of ticks; predictions judged a frame at a time.
- var wait: u32 = if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) @intCast(pardes.frame_ns / std.time.ns_per_ms) else 0;
- if (link.quietCheck()) |ms| wait = if (wait == 0) ms else @min(wait, ms);
- Shell.waitInput(&sh, wait);
- r.settle();
- // A rollback since it drew (`toConfirmed`): its frame is drawn
- // again, never moved on from cells the copy put back.
- if (r.moved) {
- r.moved = false;
- link.dirty = true;
- }
- 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;
- 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, .blob => |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.
- r = replica.join(gpa, &joined, path, session, o, have, &why, r) orelse {
- screen.leave();
- Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
- };
- }
-}
-
-/// 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), its stub `daemon.stub`. One a
-/// process: a second terminal on a session is a replica client of it.
-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,
- feed: Feed = .{},
- thread: ?std.Io.Future(void) = null,
- /// The kitty images it holds, by placement key.
- kitty: std.AutoHashMap(u64, vaxis.Image),
- /// The glyph art of the pictures it shows so (all of them without
- /// kitty graphics).
- art: Art = .{},
- caps_pending: bool = true,
- /// Its size as last taken (`Shell.resized`).
- size: ?vaxis.Winsize = null,
- /// The view's glide, the GUI's motion drawn at whole rows (anim 12).
- glide: pardes.glide.Glide = .{},
- /// The cursor's jump trail (JumpTrail), on the tty's own clock.
- trail: JumpTrail = .{},
-
- /// `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) {
- Killed.arm(sc.tty.fd.handle, sc.tty.termios);
- // What a panic puts back (vaxis.recover).
- vaxis.tty.global_tty = sc.tty;
- }
- sc.feed = .{};
- sc.caps_pending = true;
- sc.size = null;
- sc.on = true;
- }
-
- fn leave(sc: *Screen) void {
- if (!sc.on) return;
- sc.on = false;
- Killed.disarm();
- 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) vaxis.tty.global_tty = null;
- sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets
- }
-
- /// Its terminal hung up, or the stub that waits on it is gone.
- fn hungUp(sc: *const Screen) bool {
- // vaxis's test tty off Linux has no fd.
- if (comptime !@hasField(@TypeOf(sc.tty), "fd")) return false;
- const stub = daemon.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);
- }
-};
-
-/// SIGTERM or SIGHUP: the 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 fd: posix.fd_t = -1;
- var cooked: 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) void {
- cooked = termios;
- fd = 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);
- }
-
- /// 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() void {
- fd = -1;
- }
-
- fn handle(sig: posix.SIG) callconv(.c) void {
- if (fd >= 0) {
- _ = std.c.write(fd, reset, reset.len);
- _ = std.c.tcsetattr(fd, .FLUSH, &cooked);
- }
- // 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.tree_sitter_allocator = allocs.tree_sitter;
- options.frame_allocator = allocs.frame;
-
- host_io.startWorkers(allocs);
- defer host_io.stopWorkers();
- options.addons = pardes.Addon.scan();
-
- 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.screen = 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);
- defer screen.art.deinit(gpa);
- 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.list[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);
- sh.job_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);
- 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),
- .kind_job => |j| j.drop(),
- .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;
- pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw };
- defer pardes.Kind.drawer = null;
- // An upgraded session's terminals, its own again.
- if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec);
- // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig).
- sh.setAttended(!sh.detached());
- 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);
-
- 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);
- // Detached, the unit is its clients' frame: its output is paced to
- // it as a terminal's frame paces it (waitInput), a unit a frame, not
- // a unit and a delta for every read of a flood.
- if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(io).nanoseconds);
- 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: {
- const nc = host_io.restoreCore(gpa, core, rp, &sh.peers, sh.inotify_fd, &sh.watches) orelse 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 (0..pardes.MAX_PANES) |pane| Shell.closePty(&sh, @intCast(pane));
- // One view, the terminal's (host_io.restoreCore).
- const live = screen;
- stopInput(io, &live.thread);
- sh.own = 0;
- if (live.on) startInput(loop, live) catch {};
- if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty);
- nc.view().frontend.native_images = live.on and live.vx.caps.kitty_graphics;
- nc.unattended = !live.on;
- sh.peers.detached = !live.on;
- if (fs) |f| f.reset(nc);
- core.deinit();
- core = nc;
- sh.core = nc;
- if (live.on) core.update(.{ .resize = terminalSize(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(u64, 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();
-}
-
-/// 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.tellStub(a.stub, "r{s}", .{"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,
- /// The terminal (none in tests), and the view it shows: a second
- /// terminal on the session is a replica client (`pardes --attach`).
- screen: ?*Screen = null,
- own: 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: host_io.Adoptions = .{},
- 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(void) = null,
- lsp_task: ?host_io.Lsp.Task = null,
- pipe_tasks: PipeTasks = .{},
- job_tasks: PipeTasks = .{},
- threads_ok: bool = false,
- check_files: bool = false,
- 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: ?Msg = null,
- /// This process a replica client of a session elsewhere (`runClient`):
- /// its inputs go to the replica, never straight to the core.
- client: ?*Client = null,
-
- /// 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.client 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 {
- return s.screen != null;
- }
-
- /// 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.detached = !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 = ownFrame,
- };
-
- 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,
- .start = host_io.startDetached,
- .lsp = lsp,
- .pipe = pipe,
- .search = search,
- .job = job,
- };
-
- 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.clock.now_ns;
- }
- return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
- }
-
- /// The terminal, while its view is live (null in tests, and while a
- /// replica client's is: its input the last).
- fn term(s: *const Shell) ?*Screen {
- return if (s.core.live == s.own) s.screen else null;
- }
-
- /// No terminal of its own (a test's, with none at all, is not detached).
- fn detached(s: *const Shell) bool {
- const screen = s.screen orelse return false;
- return !screen.on;
- }
-
- /// Drawn only while a terminal shows it.
- fn watched(ctx: ?*anyopaque) bool {
- return !of(ctx).detached();
- }
-
- /// 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.live)) return;
- if (s.detached()) return s.core.reportFailure(s.core.view().active, "Detach: detached already (no terminal of its own)");
- if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
- s.leaveTerminal();
- }
-
- fn leaveTerminal(s: *Shell) void {
- const screen = s.screen orelse return;
- stopInput(s.io, &screen.thread);
- screen.leave();
- s.core.view().frontend.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);
- }
- daemon.tellStubDetached();
- daemon.setState(true);
- }
-
- /// `pardes --attach`'s terminal, for a detached session: its own again,
- /// entered as the first one was, sized, asked what it can do, and drawn
- /// whole. One attached already takes no other (the daemon makes a second
- /// a replica client).
- fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void {
- const screen = s.screen orelse {
- _ = libc.close(fd);
- return refuse(stub, "that session has no terminal of its own to attach to");
- };
- if (screen.on) {
- _ = libc.close(fd);
- return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=<socket>:<name>`");
- }
- const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch {
- _ = libc.close(fd);
- daemon.setState(true);
- return refuse(stub, "that terminal would not go raw");
- };
- screen.enter(tty) catch {
- daemon.setState(true);
- return refuse(stub, "that terminal would not take the screen");
- };
- daemon.stub = stub;
- s.setAttended(true);
- startInput(s.loop, screen) catch {};
- screen.vx.queryTerminalSend(screen.tty.writer()) catch {};
- s.core.needs_frame = true;
- daemon.setState(false);
- }
-
- /// 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.tellStub(stub, "r{s}", .{why});
- }
-
- fn adopt(ctx: ?*anyopaque, pane: u8) void {
- const s = of(ctx);
- s.adoptions.ask(s.core, pane);
- }
-
- /// 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).client == 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 {};
- if (s.screen) |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);
- if (s.screen) |sc| if (sc.on) rec.addTty(.{
- .view = s.own,
- .fd = sc.tty.fd.handle,
- .stub = daemon.stub,
- .primary = true,
- .termios = sc.tty.termios,
- });
- var popped = false;
- var at_buf: [1024:0]u8 = undefined;
- const failed: []const u8 = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse failed: {
- // What this process put in its terminals that the next puts in
- // again: its images, and its keyboard mode, a stack.
- if (s.screen) |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();
- break :failed upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why);
- };
- // 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;
- };
- if (s.screen) |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.adoptions.adoptShell(s.core, 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 terminal, its view's again (`primary`, run's,
- /// entered already); every other view but a replica client's, kept for
- /// its rejoin (views.away), closes. A terminal another build kept for a
- /// view of its own is let go, its stub told it is detached: one again
- /// is a replica client.
- fn resumeTerminals(s: *Shell, rec: *const upgrade.Record) void {
- if (comptime builtin.is_test) unreachable;
- const core = s.core;
- s.own = core.live;
- for (rec.ttys[0..rec.nttys]) |t| {
- if (t.primary) {
- if (!rec.fresh and pardes.views.isOpen(core, t.view)) s.own = t.view;
- continue;
- }
- _ = libc.close(t.fd);
- if (t.stub >= 0) daemon.tellStub(t.stub, "d{s}", .{daemon.name()});
- }
- if (rec.fresh) return;
- for (0..pardes.views.max) |k| if (k != s.own and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k));
- }
-
- 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 (pardes.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;
- // The tty's own motions (its glide, a jump's trail) wake it a frame at
- // a time while they move: on a virtual clock a millisecond's wait
- // moves it a frame (waitOnce), on the real one the pace below sets it.
- if (s.moving()) wait = 1;
- // Detached, nobody's key dismisses a message: they go on the clock
- // (the pump's, after this wait), which wakes it.
- if (s.detached()) {
- 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.moving();
- var tick: u64 = 0;
- if (paced) {
- const period = pardes.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).
- // Detached, its clients' echo is the frame's after an input: what a
- // flood says after that goes a unit a frame (their own echo is
- // predicted, src/echo.zig), not a unit and a delta a read for a second.
- const echo_ns: u64 = if (s.detached()) pardes.frame_ns else std.time.ns_per_s;
- 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 < echo_ns) break;
- const due = s.drawn_ns + pardes.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 the tty's own
- // motions move (the glide), as the real one would.
- s.wake_to = s.core.nextWake() orelse if (s.moving()) s.core.clock.now_ns + pardes.frame_ns else 0;
- requestWake(s.io, wait);
- }
- pardes.turn.rest();
- const got = s.loop.nextEvent() catch {
- pardes.turn.wake();
- if (s.client) |c| c.link.quit = true;
- 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: ?Msg = 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: Msg) 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: Msg) 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;
- // The terminal's input goes into its view.
- switch (event) {
- .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => {
- if (s.local() and s.client == null) core.toView(s.own);
- },
- else => {},
- }
- switch (event) {
- .nop => {},
- .winched => s.winched(),
- // The terminal hung up (its stub passes the hangup on) or its
- // stub died (a forked session's death signal): its input has
- // ended.
- .hangup => if (s.screen) |sc| if (sc.on and sc.hungUp()) {
- if (s.apply(.quit)) return true;
- },
- .wake => if (s.test_clock) |*virtual| {
- virtual.* = @max(virtual.*, s.wake_to);
- },
- .quit => {
- if (s.client) |c| {
- c.link.quit = true;
- 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.detached()) s.leaveTerminal();
- return true;
- }
- core.quit = true;
- return true;
- },
- .attach => |a| s.attachTerminal(a.tty, a.stub, null),
- .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd),
- .replica => |j| {
- s.peers.handed(j.fd, j.view);
- s.input_seen = true;
- },
- .replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) {
- s.input_seen = true;
- },
- .said => |said| if (s.client) |c| {
- // The session's units and deltas are a client's output
- // (waitInput paces it): a terminal's delta, or the unit
- // that answers its own input, is its echo, drawn at once.
- s.output_seen = true;
- const echo = switch (said) {
- .screen => true,
- .unit => |b| if (replica.parseUnit(b)) |u| u.origin == c.link.r.id else false,
- else => false,
- };
- if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
- c.link.take(said);
- if (said == .refused) return true;
- } else switch (said) {
- .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
- },
- .link_gone => if (s.client) |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.detached()) s.resized(s.screen, ws),
- .pty_read => |pr| {
- tookRead(s.io, pr.id);
- s.output_seen = true;
- if (pr.id == core.view().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 = vaxis_input.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| if (mouseEvent(m)) |ev| s.feed(ev),
- .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.view().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);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(core);
- // A client's draw done: its frame is its own to draw again.
- if (s.client) |cl| cl.link.dirty = true;
- },
- }
- return false;
- }
-
- /// Terminal `screen` (its view live) 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 = terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) });
- }
-
- /// A SIGWINCH: the terminal, if it changed size, resized in its view
- /// (one reporting in band says so as input).
- fn winched(s: *Shell) void {
- const sc = s.screen orelse return;
- if (!sc.on or sc.vx.state.in_band_resize) return;
- const ws = sc.tty.getWinsize() catch return;
- if (sc.size) |was| if (std.meta.eql(was, ws)) return;
- if (s.client == null) s.core.toView(s.own);
- 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 {};
- }
-
- /// The tty's own motions (its glide, a jump's trail) are under way.
- fn moving(s: *const Shell) bool {
- const sc = s.term() orelse return false;
- return sc.glide.moving() or sc.trail.active;
- }
-
- /// The tty's own motions draw their frames themselves: the last frame
- /// again, moved on, when the core has none to draw.
- fn ownFrame(ctx: ?*anyopaque) void {
- const s = of(ctx);
- if (s.moving() and !s.core.needs_frame and s.core.surface.cells.len != 0) present(ctx, &s.core.surface);
- }
-
- fn pollFrame(ctx: ?*anyopaque) void {
- const s = of(ctx);
- defer ownFrame(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.view().frontend.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.view().frontend.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;
- // 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 tz_cells = tracy.zone(@src(), "surface->vaxis");
- const win = vx.window();
- // The tty's own motions, on its own clock, from the frame alone.
- const now: u64 = s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
- // The pictures it shows as glyph art, in a copy of the frame: all
- // of them where the terminal has no kitty graphics.
- const cell_h = terminalCellPixels(vx.screen.height_pix, vx.screen.height, 16);
- const arted = sc.art.frame(s.gpa, s.frame.allocator(), canonical, vx.caps.kitty_graphics, cell_h) catch canonical;
- sc.glide.frame(s.gpa, arted, now, null, null);
- s.core.frames.scroll = @round(sc.glide.follow.offset);
- const glided = glideRows(s.frame.allocator(), arted, &sc.glide) catch arted;
- const truecolor = vx.caps.rgb or colortermTruecolor();
- const trail_on = s.core.settings.jump_trail and truecolor;
- const shown = trailCells(s.frame.allocator(), glided, &sc.trail, trail_on, now) catch glided;
- paintCells(win, shown.cells, shown.cols, shown.rows);
- if (s.client) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), shown.cols, shown.rows);
- tz_cells.end();
- if (vx.caps.kitty_graphics) for (canonical.placements.items) |place| {
- if (place.art.glyph or !kittyImageRepresentable(place)) continue;
- const key = place.key;
- const rgba = place.raster.bytes();
- if (!sc.kitty.contains(key) 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, rgba)) break :shm;
- if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.raster.w), @intCast(place.raster.h), .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)) {
- const enc = std.base64.standard.Encoder;
- if (s.gpa.alloc(u8, enc.calcSize(rgba.len))) |b64| {
- defer s.gpa.free(b64);
- _ = enc.encode(b64, rgba);
- if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.raster.w), @intCast(place.raster.h), .rgba) catch null) |handle|
- sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id);
- } else |_| {}
- }
- const cached = sc.kitty.get(key) orelse continue;
- const d = place.dst;
- if (place.at == null) {
- // Fitted: kitty's own contain, at the top left.
- const child = win.child(.{ .x_off = d.x, .y_off = d.y, .width = d.w, .height = d.h });
- cached.draw(child, .{ .scale = .contain }) catch {};
- } else if (d.h == 1) {
- 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 = d.x + placement.cell_x;
- if (win.readCell(x, d.y)) |under| {
- var cell = under;
- cell.image = .{ .img_id = cached.id, .options = placement.options };
- win.writeCell(x, d.y, cell);
- }
- }
- } 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, d.x) + placement.cell_x,
- .y_off = @as(i17, d.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]u64 = undefined;
- var stale_len: usize = 0;
- var image_iterator = sc.kitty.iterator();
- while (image_iterator.next()) |entry| {
- if (surfaceHasKittyKey(canonical, 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 (shown.cursor) |cur| {
- win.showCursor(cur.x, cur.y);
- win.setCursorShape(if (cur.bar) .beam else .default);
- }
- 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() != null) s.core.presented();
- tracy.frameMark();
- }
-
- fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void {
- const s = of(ctx);
- if (s.adoptions.take(pane)) |a| return s.takeShell(pane, a);
- // The new shell starts before a running one goes: one that cannot
- // start leaves the running one be (pty/ctl's exec).
- const running = s.ptys[pane] != null;
- const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| {
- if (running) return s.core.restartFailed(pane, err);
- return s.core.shellFailed(pane, err);
- };
- closePty(ctx, pane); // a shell still in the slot goes, reaped
- s.gens[pane] +%= 1;
- const command = if (s.core.panes[pane]) |pn| pn.command != null else false;
- s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } };
- var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
- // Only a shell given no directory is asked where it is: one given a
- // directory is named by it already (newShell), and asked now, before
- // its chdir, it would answer this process's, a rename to undo.
- if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
- if (s.threads_ok) {
- if (s.ptys[pane]) |*pt| {
- pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader;
- }
- }
- }
-
- /// An adopted shell, running already, as pane `pane`'s: told the size
- /// twice (a size it never had, then the pane's), which makes it redraw.
- fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void {
- closePty(s, pane);
- s.gens[pane] +%= 1;
- const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } };
- s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} };
- var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
- s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid));
- var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined;
- if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd);
- const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 };
- _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny));
- if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1));
- if (s.threads_ok) if (s.ptys[pane]) |*pt| {
- pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader;
- };
- }
-
- fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void {
- const s = of(ctx);
- if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes);
- }
-
- fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void {
- const s = of(ctx);
- if (s.ptys[pane]) |pt| {
- const ws = host_io.ptyWinsize(s.core, cols, rows);
- _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws));
- }
- }
-
- fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void {
- const s = of(ctx);
- // A command whose exit is recorded is reaped: its group may be
- // another's by now.
- if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched);
- }
-
- /// The pane is gone: hang its pty up, which the kernel passes on to the
- /// shell as SIGHUP, and retire the shell. Output still in flight
- /// carries the old generation and is dropped.
- fn closePty(ctx: ?*anyopaque, pane: u8) void {
- const s = of(ctx);
- var pt = s.ptys[pane] orelse return;
- s.ptys[pane] = null;
- s.gens[pane] +%= 1;
- pt.reader.cancel(s.io) catch {};
- _ = libc.close(pt.file.handle);
- daemon.closed(pt.pid);
- host_io.retireShell(pt.pid);
- }
-
- fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool {
- const s = of(ctx);
- const pt = s.ptys[pane] orelse return false;
- return host_io.ttyTaken(pt.pid, pt.file.handle);
- }
-
- fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 {
- const s = of(ctx);
- const pt = s.ptys[pane] orelse return null;
- return host_io.foregroundName(pt.pid, pt.file.handle, buf);
- }
-
- /// The command panes' exits, told once their output is in (host_io).
- fn takeExits(s: *@This()) void {
- host_io.takeExits(s.core, &s.ptys, s, closeWatched);
- }
-
- fn closeWatched(s: *@This(), id: usize) void {
- const pt = &(s.ptys[id] orelse return);
- _ = libc.close(pt.file.handle);
- s.ptys[id] = null;
- }
-
- fn killJob(ctx: ?*anyopaque, pane: u8) bool {
- const s = of(ctx);
- const pt = s.ptys[pane] orelse return false;
- return host_io.killJob(pt.pid, pt.file.handle);
- }
-
- fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void {
- const s = of(ctx);
- host_io.writeFile(s.core, &s.watches, pane, path, bytes);
- }
-
- fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
- host_io.writeDump(of(ctx).core, bytes);
- }
-
- fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void {
- const s = of(ctx);
- if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode))
- s.loop.postEvent(.files_changed) catch {};
- }
-
- fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void {
- const s = of(ctx);
- if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on))
- s.loop.postEvent(.files_changed) catch {};
- }
-
- fn dumpThemes(ctx: ?*anyopaque, pane: u8) void {
- const s = of(ctx);
- host_io.dumpThemes(s.core, s.io, s.gpa, pane);
- }
-
- fn setClipboard(ctx: ?*anyopaque, text: []const u8) void {
- const s = of(ctx);
- // Detached, the session keeps it (a 9P read, a paste here).
- const sc = s.term() orelse return s.core.fallback.setClipboard(text);
- if (!sc.on) return s.core.fallback.setClipboard(text);
- if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {};
- }
-
- fn readClipboard(ctx: ?*anyopaque) void {
- const s = of(ctx);
- const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items });
- if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items });
- sc.vx.requestSystemClipboard(sc.tty.writer()) catch {};
- }
-
- fn openLink(_: ?*anyopaque, url: []const u8) void {
- look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly
- }
-
- fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void {
- const s = of(ctx);
- if (!s.threads_ok) {
- s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
- return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable);
- }
- host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows);
- }
-
- fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
- const s = of(ctx);
- 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.view().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);
- }
-
- /// A draw (api.draw) on a worker, as a job is.
- fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
- const s = of(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct {
- fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop();
- }
- }.deliver);
- }
-
- fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void {
- const s = of(ctx);
- if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token);
- host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct {
- fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop();
- }
- }.deliver);
- }
-
- /// 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);
- }
-};
-
-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) 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 (`runClient`): a hangup is its end, whoever sent it.
-var hangup_quits = false;
-
-fn winchWatch(loop: *Loop) void {
- var set = posix.sigemptyset();
- posix.sigaddset(&set, posix.SIG.WINCH);
- if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP);
- while (true) {
- var sig: c_int = 0;
- if (libc.sigwait(&set, &sig) != 0) continue;
- // The terminals are the loop's: it asks each its size, and takes a
- // hangup as the end of the one that hung up.
- const ev: Msg = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup;
- loop.postEvent(ev) catch {};
- }
-}
-
-/// A wait with a timeout: post one `.wake` when it runs out. The wake joins
-/// the input queue, so a key or a click that lands first is handled at once
-/// instead of after a blind sleep; vaxis's queue has no timed wait. Each
-/// request bumps `wake_gen`, which cuts short a sleep still timing an
-/// earlier, longer request (an 800 ms linger interrupted by a key that
-/// starts a 16 ms fall) and times the new one instead.
-var wake_gen: std.atomic.Value(u32) = .init(0);
-var wake_ms: std.atomic.Value(u32) = .init(0);
-
-fn requestWake(io: std.Io, ms: u32) void {
- wake_ms.store(ms, .release);
- _ = wake_gen.fetchAdd(1, .acq_rel);
- io.futexWake(u32, &wake_gen.raw, 1);
-}
-
-fn wakeWatch(io: std.Io, loop: *Loop) void {
- var seen = wake_gen.load(.acquire);
- while (true) {
- // Asleep until a request.
- while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen);
- seen = wake_gen.load(.acquire);
- if (timeWake(io, &seen)) loop.postEvent(.wake) catch {};
- }
-}
-
-/// Sleep out the latest request; true when it ran its course, false when
-/// none is pending. A newer request met on the way restarts the timing.
-fn timeWake(io: std.Io, seen: *u32) bool {
- while (true) {
- const ms = wake_ms.load(.acquire);
- const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms;
- while (true) {
- const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds);
- if (now >= deadline) return true;
- io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{
- .raw = .fromNanoseconds(@intCast(deadline - now)),
- .clock = .awake,
- } }) catch {};
- const gen = wake_gen.load(.acquire);
- if (gen != seen.*) {
- seen.* = gen;
- break;
- }
- }
- }
-}
-
-fn wakeFs(ctx: ?*anyopaque) void {
- const loop: *Loop = @ptrCast(@alignCast(ctx.?));
- _ = loop.tryPostEvent(.fs_ready) catch {};
-}
-
-/// Each pane's reads posted and not yet taken in. Two at most: a flood the
-/// loop cannot keep up with waits in its pty, not in the queue ahead of a
-/// key and its echo (hundreds of 4 KB reads queued were half a second).
-var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0));
-
-/// A read of pane `id` taken in (or dropped): its reader may read on. Never
-/// below zero, for an event no reader posted (a test's).
-fn tookRead(io: std.Io, id: usize) void {
- var queued = reads_queued[id].load(.acquire);
- while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse {
- if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1);
- return;
- };
-}
-
-fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) error{OutOfMemory}!void {
- // One buffer, read into directly: a Reader around it only added a second
- // (and in a safe build, filled both as `undefined` on every start).
- var buf: [0x10000]u8 = undefined;
- read: while (true) {
- while (true) {
- const queued = reads_queued[id].load(.acquire);
- if (queued < 2) break;
- io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read;
- }
- const n = pty.readStreaming(io, &.{&buf}) catch break;
- if (n == 0) break;
- const bytes = try gpa.dupe(u8, buf[0..n]);
- _ = reads_queued[id].fetchAdd(1, .acq_rel);
- loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch {
- tookRead(io, id);
- gpa.free(bytes);
- break;
- };
- }
- _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {};
-}
-
-const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes;
-
-fn mouseEvent(m: vaxis.Mouse) ?pardes.Event {
- const button: pardes.Mouse.Button = switch (m.button) {
- .left => .left,
- .middle => .middle,
- .right => .right,
- .wheel_up => .wheel_up,
- .wheel_down => .wheel_down,
- .wheel_left => .wheel_left,
- .wheel_right => .wheel_right,
- // A mouse's side buttons, as xterm reports them: Back and Forward.
- .button_8 => .back,
- .button_9 => .forward,
- .none => .none, // button-less motion: hover tracking
- else => return null,
- };
- return .{ .mouse = .{
- .button = button,
- .kind = switch (m.type) {
- .press => .press,
- .release => .release,
- .motion => .motion,
- .drag => .drag,
- },
- .col = cellOf(m.col),
- .row = cellOf(m.row),
- .ctrl = m.mods.ctrl,
- .shift = m.mods.shift,
- .alt = m.mods.alt,
- } };
-}
-
-/// A report's cell, 0-based: one before the first (SGR's 0, a drag past
-/// the window's top or left edge, in cells or in 1016's pixels) is the
-/// first, never a panic; past the far edge the core clamps it.
-pub fn cellOf(v: i16) u16 {
- return @intCast(@max(0, v));
-}
-
-/// A replica client's own line over its frame's last row (`Client.notify`),
-/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps
-/// the slices).
-fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void {
- if (rows == 0) return;
- for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{
- .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " },
- .style = .{ .reverse = true },
- });
-}
-
-/// A blank whose ink alone changed is not sent: vaxis's render skips it
-/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows
-/// nowhere. Deciding that here cost every cell of every frame a look at the
-/// frame before; vaxis already makes that comparison.
-/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind
-/// the cursor in its body, on the page's own ground, that ground drawn
-/// toward the text's colour; a copy of `shown` while it fades.
-fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface {
- var at: [5]JumpTrail.Cell = undefined;
- const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at);
- if (lit.len == 0) return shown;
- const cursor = shown.cursor.?;
- const body = for (shown.regionList()) |region| {
- if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and
- cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect;
- } else return shown;
- const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc };
- const page = shown.chrome.page orelse pardes.colors.null_page;
- const out = try arena.create(pardes.Surface);
- out.* = shown.*;
- out.cells = try arena.dupe(pardes.Cell, shown.cells);
- for (lit) |cell| {
- if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue;
- const c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))];
- // On the page's own ground alone: never a selection or a match.
- const ground: [3]u8 = if (c.default) page else switch (c.style.bg) {
- .rgb => |rgb| rgb,
- else => page,
- };
- if (!std.mem.eql(u8, &ground, &page)) continue;
- if (c.default) c.style = .{};
- c.default = false;
- c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) };
- }
- return out;
-}
-
-/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does
-/// not answer vaxis's query.
-fn colortermTruecolor() bool {
- const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false);
- return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit");
-}
-
-/// The tty's picture of the glide (glide.zig, anim 12): the body's rows
-/// moved by the offset rounded to whole rows (the position rounded, never
-/// the step, so a slowing glide's steps come further apart), the rows that
-/// left in the gap it opens, and a caret whose line rode the scroll carried
-/// with it; `canonical` itself while the picture is where the core is, else
-/// a copy of it in `arena`. The rows are walked from the side they move
-/// toward, so each is read before a move writes over it.
-fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface {
- const k: i32 = @intFromFloat(@round(glide.follow.offset));
- const w = glide.bw();
- const h = glide.body_h;
- const x0 = glide.rect.x + pardes.config.GUTTER;
- const y0 = glide.body_y;
- if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical;
- const out = try arena.create(pardes.Surface);
- out.* = canonical.*;
- out.cells = try arena.dupe(pardes.Cell, canonical.cells);
- const cols: usize = out.cols;
- for (0..h) |i| {
- const r = if (k > 0) i else h - 1 - i;
- const from = @as(i32, @intCast(r)) + k;
- const to = out.cells[(y0 + r) * cols + x0 ..][0..w];
- const kept: ?[]const pardes.Cell = if (from >= 0 and from < h)
- out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w]
- else if (from < 0 and -from - 1 < glide.nabove)
- glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w]
- else if (from >= h and from - h < glide.nbelow)
- glide.below[@as(usize, @intCast(from - h)) * w ..][0..w]
- else
- null;
- if (kept) |cells| @memcpy(to, cells) else @memset(to, .{});
- }
- if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) {
- const y = @as(i32, c.y) - k;
- if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null;
- };
- return out;
-}
-
-fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void {
- win.clear();
- var y: u16 = 0;
- while (y < rows) : (y += 1) {
- var x: u16 = 0;
- while (x < cols) : (x += 1) {
- const cell = &cells[@as(usize, y) * cols + x];
- if (cell.default) continue;
- win.writeCell(x, y, .{
- .char = .{ .grapheme = cell.grapheme() },
- .style = vaxis_input.style(cell.style),
- });
- }
- }
-}
-
-test "terminal input preserves fragmented keys queries paste and text after EOF" {
- const gpa = std.testing.allocator;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- t.vx.queries_done.store(false, .unordered);
- var reader: TestReader = .{ .parts = &.{
- "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95",
- "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b",
- } };
- try readInput(&t.loop, &reader, &t.vx, &t.feed);
- try std.testing.expect(t.vx.queries_done.load(.unordered));
- var text: std.ArrayList(u8) = .empty;
- defer text.deinit(gpa);
- var resized = false;
- var up = false;
- var in_paste = false;
- var pasted = false;
- var clipboard = false;
- var escape = false;
- while (try t.loop.tryEvent()) |event| switch (event) {
- .winsize => |size| {
- try std.testing.expect(!resized);
- resized = true;
- try std.testing.expectEqual(@as(u16, 80), size.cols);
- },
- .key_press => |key| {
- try std.testing.expect(resized);
- if (key.codepoint == vaxis.Key.up) {
- up = true;
- } else if (key.codepoint == vaxis.Key.escape) {
- escape = true;
- } else if (key.text) |bytes| {
- if (in_paste) try std.testing.expect(up);
- try text.appendSlice(gpa, bytes);
- } else return error.UnexpectedInputKey;
- },
- .paste_start => {
- try std.testing.expect(up and !in_paste);
- in_paste = true;
- },
- .paste_end => {
- try std.testing.expect(in_paste);
- in_paste = false;
- pasted = true;
- },
- .paste => |bytes| {
- defer gpa.free(@constCast(bytes));
- try std.testing.expect(pasted and !in_paste);
- try std.testing.expectEqualStrings("clip", bytes);
- clipboard = true;
- },
- // The device attributes' wake (a capability answer).
- .nop => try std.testing.expect(t.vx.queries_done.load(.unordered)),
- else => return error.UnexpectedInputEvent,
- };
- try std.testing.expectEqualStrings("plain café 界 😀tail", text.items);
- try std.testing.expect(resized and up and pasted and clipboard and escape);
-}
-
-test "terminal replies and malformed sequences never become typed text" {
- const gpa = std.testing.allocator;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- t.vx.queries_done.store(false, .unordered);
- var reader: TestReader = .{
- .parts = &.{
- // The startup width queries' answers where the terminal has no
- // explicit width: both used to arrive as a bare F3, typed as text.
- "a\x1b[1;1R\x1b[1;1R",
- // A late report somewhere else on the screen, and DECXCPR.
- "\x1b[12;40R\x1b[?3;7;1R",
- // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`.
- "b\x1b\x1b[A",
- // A kitty graphics reply cut inside its ST sliced past its input.
- "\x1b_Gi=1;OK\x1b",
- "\\",
- // An X10 mouse report cut after `CSI M` left three bytes as text.
- "\x1b[M",
- " !!",
- // Malformed color and clipboard replies failed the parse, which
- // ended input altogether; and a reply ended by BEL ran on to the
- // next sequence's ESC, leaving what lay between as text.
- "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07",
- // Device reports whose fields end early.
- "\x1b[?1;y\x1b[?997;n\x1b[c",
- "\x1b[?62;c",
- "c",
- },
- };
- try readInput(&t.loop, &reader, &t.vx, &t.feed);
- try std.testing.expect(t.vx.queries_done.load(.unordered));
- try std.testing.expect(t.vx.caps.kitty_graphics);
- var text: std.ArrayList(u8) = .empty;
- defer text.deinit(gpa);
- var alt_up = false;
- var clicked = false;
- while (try t.loop.tryEvent()) |event| switch (event) {
- .winsize => {},
- .key_press => |key| {
- if (key.codepoint == vaxis.Key.up and key.mods.alt) {
- alt_up = true;
- } else if (key.text) |bytes| {
- try text.appendSlice(gpa, bytes);
- } else return error.UnexpectedInputKey;
- },
- .mouse => |mouse| {
- try std.testing.expectEqual(@as(i16, 0), mouse.col);
- clicked = true;
- },
- .nop => {}, // the device attributes' wake
- else => return error.UnexpectedInputEvent,
- };
- try std.testing.expectEqualStrings("abc", text.items);
- try std.testing.expect(alt_up and clicked);
-}
-
-test "terminal input split at every byte with a gap reads as it does whole" {
- const gpa = std.testing.allocator;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- // Two reads with `gap_ms` between them, as an ssh link delivers a
- // sequence cut across two packets (TestReader).
- const Events = struct {
- /// What the loop was handed, one line per event.
- fn of(l: *Loop, out: *std.ArrayList(u8)) !void {
- out.clearRetainingCapacity();
- while (try l.tryEvent()) |event| switch (event) {
- .winsize => {},
- .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }),
- .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }),
- .paste => |bytes| {
- try out.print(std.testing.allocator, "paste {s}\n", .{bytes});
- std.testing.allocator.free(@constCast(bytes));
- },
- else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}),
- };
- }
- };
- const Case = struct { bytes: []const u8, kitty: bool = false };
- const cases = [_]Case{
- .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V
- .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text
- .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own
- .{ .bytes = "\x1b[27u", .kitty = true }, // Escape
- .{ .bytes = "\x1b[A" },
- .{ .bytes = "\x1bOA" },
- .{ .bytes = "\x1b[3;5~" },
- .{ .bytes = "\x1b\x1b[A" },
- // Four wheel notches: cut at a `;` with 60 ms between the halves,
- // ssh's framing lost all four.
- .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" },
- .{ .bytes = "\x1b[200~pasted\x1b[201~" },
- .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" },
- .{ .bytes = "\x1b_Gi=1;OK\x1b\\" },
- .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" },
- };
- var whole: std.ArrayList(u8) = .empty;
- defer whole.deinit(gpa);
- var split: std.ArrayList(u8) = .empty;
- defer split.deinit(gpa);
- for (cases) |case| {
- t.vx.caps.kitty_keyboard = case.kitty;
- const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" });
- defer gpa.free(all);
- const whole_parts = [_][]const u8{ all, "" };
- var one: TestReader = .{ .parts = &whole_parts };
- try readInput(&t.loop, &one, &t.vx, &t.feed);
- try Events.of(&t.loop, &whole);
- for (1..all.len) |cut| {
- // A cut just after an ESC is the one that has to wait, and a
- // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut
- // anywhere else is carried however long the gap.
- const after_esc = all[cut - 1] == 0x1b;
- const halves = [_][]const u8{ all[0..cut], all[cut..] };
- var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 };
- try readInput(&t.loop, &two, &t.vx, &t.feed);
- try Events.of(&t.loop, &split);
- std.testing.expectEqualStrings(whole.items, split.items) catch |err| {
- std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut });
- return err;
- };
- }
- }
- t.vx.caps.kitty_keyboard = false;
-}
-
-test "an ESC read by itself is the Escape key at once" {
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- // More always follows at once: a reader that waited on the ESC would
- // take `j` for the rest of its sequence (Alt-j).
- for ([_]bool{ false, true }) |kitty| {
- t.vx.caps.kitty_keyboard = kitty;
- var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } };
- try readInput(&t.loop, &reader, &t.vx, &t.feed);
- try std.testing.expect(!reader.asked);
- try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
- const escape = (try t.loop.tryEvent()).?.key_press;
- try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
- try std.testing.expect(!escape.mods.alt);
- const j = (try t.loop.tryEvent()).?.key_press;
- try std.testing.expectEqual(@as(u21, 'j'), j.codepoint);
- try std.testing.expect(!j.mods.alt);
- try std.testing.expect(try t.loop.tryEvent() == null);
- }
- t.vx.caps.kitty_keyboard = false;
-}
-
-test "a frame's answer is taken wherever the reads cut it, and never typed" {
- const gpa = std.testing.allocator;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- const all = "x" ++ FrameAck.answer ++ "y";
- defer t.feed.ack.waiting.store(false, .release);
- for (0..all.len) |cut| {
- t.feed.ack.waiting.store(true, .release);
- const halves = [_][]const u8{ all[0..cut], all[cut..] };
- var reader: TestReader = .{ .parts = &halves };
- try readInput(&t.loop, &reader, &t.vx, &t.feed);
- try std.testing.expect(!t.feed.ack.waiting.load(.acquire));
- var typed: std.ArrayList(u8) = .empty;
- defer typed.deinit(gpa);
- var woke = false;
- while (try t.loop.tryEvent()) |event| switch (event) {
- .winsize => {},
- .nop => woke = true,
- .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey),
- else => return error.UnexpectedInputEvent,
- };
- std.testing.expectEqualStrings("xy", typed.items) catch |err| {
- std.debug.print("cut at {d}\n", .{cut});
- return err;
- };
- try std.testing.expect(woke);
- }
- // An Escape pressed just before an answer, in the same read, is the
- // Escape key, not Alt on the answer.
- t.feed.ack.waiting.store(true, .release);
- var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } };
- try readInput(&t.loop, &glued, &t.vx, &t.feed);
- try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
- try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?));
- const escape = (try t.loop.tryEvent()).?.key_press;
- try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
- try std.testing.expect(!escape.mods.alt);
- try std.testing.expectEqual(@as(u21, 'j'), (try t.loop.tryEvent()).?.key_press.codepoint);
- try std.testing.expect(try t.loop.tryEvent() == null);
-}
-
-test "a terminal that never answers a frame stops being asked after one timeout" {
- const io = std.testing.io;
- var ack: FrameAck = .{};
- var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
- defer out.deinit();
- const t0: u64 = 5 * std.time.ns_per_s;
- ack.ask(&out.writer, t0);
- try std.testing.expectEqualStrings(FrameAck.request, out.written());
- // Unanswered: the next frame waits, until the timeout.
- try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io));
- try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io));
- try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io));
- // Then never again: no request, no wait.
- out.clearRetainingCapacity();
- ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s);
- try std.testing.expectEqual(@as(usize, 0), out.written().len);
- try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io));
-}
-
-test "terminal input cancellation joins blocked reads and queued EOF" {
- const io = std.testing.io;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- const Reader = struct {
- file: std.Io.File,
- eof: bool,
- entered: std.Io.Event = .unset,
- release: std.Io.Event = .unset,
- returned: std.Io.Event = .unset,
- fn getWinsize(_: *@This()) !vaxis.Winsize {
- return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 };
- }
- pub fn inputFollows(_: *@This(), _: u32) bool {
- return false;
- }
- fn read(self: *@This(), buf: []u8) !usize {
- self.entered.set(std.testing.io);
- if (self.eof) {
- try self.release.wait(std.testing.io);
- self.returned.set(std.testing.io);
- return 0;
- }
- return self.file.readStreaming(std.testing.io, &.{buf});
- }
- fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void {
- inputReader(loop, reader, vx_, feed);
- }
- };
- const Case = enum { blocked_read, cancel_eof, deliver_eof };
- for (std.enums.values(Case)) |case| {
- const eof = case != .blocked_read;
- var fds: [2]c_int = undefined;
- if (libc.pipe(&fds) != 0) return error.PipeFailed;
- defer _ = libc.close(fds[0]);
- defer _ = libc.close(fds[1]);
- var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof };
- var loop: Loop = .init(io, undefined, &t.vx);
- var feed: Feed = .{};
- var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.vx, &feed });
- defer stopInput(io, &thread);
- try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent()));
- try reader.entered.wait(io);
- if (eof) {
- for (0..512) |_| try loop.postEvent(.nop);
- reader.release.set(io);
- try reader.returned.wait(io);
- }
- if (case == .deliver_eof) {
- try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent()));
- thread.?.await(io);
- }
- stopInput(io, &thread);
- try std.testing.expect(thread == null);
- var count: usize = 0;
- while (try loop.tryEvent()) |event| {
- const expected: std.meta.Tag(Msg) = if (case == .deliver_eof and count == 511) .quit else .nop;
- try std.testing.expectEqual(expected, std.meta.activeTag(event));
- count += 1;
- }
- try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count);
- }
-}
-
-test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" {
- var place = pardes.Placement{
- .pane = 0,
- .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 },
- .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 },
- .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 },
- .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 },
- .key = pardes.Placement.keyOf(3, 7, 0),
- };
- // 10x20 pixel cells: a whole row, one to one.
- const full = exactKittyPlacement(place, 100, 30, 1000, 600).?;
- try std.testing.expectEqual(@as(u16, 0), full.cell_x);
- try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols);
- try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows);
- try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y);
- try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width);
- try std.testing.expect(full.options.pixel_offset == null);
-
- // The top of a letterboxed picture: 7 pixels down into the row, 13
- // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns
- // only, its source no taller than the 13 pixels left in the row at
- // that scale.
- place.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 };
- place.at = .{ .x = 35, .y = 7, .w = 205, .h = 13 };
- const top = exactKittyPlacement(place, 100, 30, 1000, 600).?;
- try std.testing.expectEqual(@as(u16, 3), top.cell_x);
- try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x);
- try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y);
- try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols);
- try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows);
- const w = top.options.clip_region.?.width.?;
- const h = top.options.clip_region.?.height.?;
- try std.testing.expectEqual(@as(u16, 205), w);
- try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13);
-
- // Narrower than its cells round to: the source is cut to their scale.
- place.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 };
- place.at = .{ .x = 0, .y = 0, .w = 204, .h = 20 };
- const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?;
- try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols);
- try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width);
-}
-
-test "Kitty PDF fragments never declare pixels beyond their clipped bottom" {
- // As wide as the body: fit to width.
- const base = pardes.Placement{
- .pane = 0,
- .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 },
- .src = .{ .w = 96, .h = 10 },
- .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 },
- .at = .{ .y = 195, .w = 304, .h = 29 },
- .key = pardes.Placement.keyOf(1, 0, 1),
- };
- const width = kittyPlacement(base, 80, 16, 640, 256) orelse
- return error.MissingSafeKittyWidthFragment;
- const width_clip = width.options.clip_region.?;
- const width_size = width.options.size.?;
- try std.testing.expectEqual(@as(u16, 5), width_clip.height.?);
- try std.testing.expectEqual(@as(u16, 38), width_size.cols.?);
- try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y);
- const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? +
- width_clip.width.? - 1) / width_clip.width.?;
- const inferred_rows = (aspect_pixels + 15) / 16;
- try std.testing.expect(inferred_rows * 16 <= base.at.?.h);
-
- // Narrower than the body: fit to height.
- var height = base;
- height.at.?.w = 300;
- height.src.h = 9;
- const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse
- return error.MissingSafeKittyHeightFragment;
- try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?);
- try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <=
- height.at.?.h);
-
- height.at.?.h = 13;
- try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null);
-}
-
-test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 });
- defer core.deinit();
- core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } });
- const pane = core.panes[0].?;
- pane.body.mode = .tty;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- const a = frame.allocator();
- const px = try a.alloc(u8, 64 * 64 * 3);
- for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 };
- const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len));
- _ = std.base64.standard.Encoder.encode(enc, px);
- core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } });
- while (core.nextEffect()) |_| {}
- const s = try core.render(a);
- try std.testing.expectEqual(@as(usize, 4), s.placements.items.len);
- var art: Art = .{};
- defer art.deinit(gpa);
- try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16));
- const shown = try art.frame(gpa, a, s, false, 16);
- const r = core.view().rects[0];
- const x0 = r.x + pardes.config.GUTTER + 7;
- const y0 = core.bodyTop(pane, r) + 1;
- var painted: usize = 0;
- for (0..4) |dy| for (0..8) |dx| {
- const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy)));
- const bg = switch (cell.style.bg) {
- .rgb => |rgb| rgb,
- else => continue,
- };
- for (Art.commodore) |c| {
- if (std.mem.eql(u8, &c, &bg)) painted += 1;
- }
- };
- try std.testing.expectEqual(@as(usize, 32), painted);
-}
-
-test "TTY queued results reject old PTY generations and LSP request IDs" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
- defer core.deinit();
- var shell: Shell = .{
- .io = std.testing.io,
- .gpa = gpa,
- .lsp_gpa = gpa,
- .core = core,
- .prompt_rcs = undefined,
- .loop = undefined,
- .frame = undefined,
- .paste_buf = undefined,
- .inotify_fd = -1,
- };
- shell.gens[0] = 2;
- _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } });
- _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } });
- const text = try pardes.Term.scrollback(core.panes[0].?.terminal, gpa);
- defer gpa.free(text);
- try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null);
- try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null);
-
- core.lspRequest(0, .status, "");
- const old_id = core.lsp_ask.wait.?.id;
- core.lspRequest(0, .status, "");
- const current_id = core.lsp_ask.wait.?.id;
- shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } };
- _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } });
- try std.testing.expect(shell.lsp_task != null);
- try std.testing.expectEqual(current_id, shell.lsp_task.?.id);
- try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id);
- _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } });
- try std.testing.expect(shell.lsp_task == null);
- try std.testing.expect(core.lsp_ask.wait == null);
-}
-
-test "TTY worker setup failures finish matching LSP and pipe requests" {
- const gpa = std.testing.allocator;
- var failing_vtable = std.testing.io.vtable.*;
- failing_vtable.concurrent = std.Io.failingConcurrent;
- const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable };
- for (0..2) |failure| {
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
- const pane = try core.setTestFile("abc");
- var failing = std.testing.FailingAllocator.init(gpa, .{
- .fail_index = if (failure == 0) 0 else std.math.maxInt(usize),
- });
- var shell: Shell = .{
- .io = failing_io,
- .gpa = failing.allocator(),
- .lsp_gpa = failing.allocator(),
- .core = core,
- .prompt_rcs = undefined,
- .loop = undefined,
- .frame = undefined,
- .paste_buf = undefined,
- .inotify_fd = -1,
- .threads_ok = true,
- };
- core.lspRequest(core.view().active, .status, "");
- const req: host_io.Lsp.Request = .{
- .id = core.lsp_ask.wait.?.id,
- .kind = .status,
- .pane = @intCast(core.view().active),
- .offset = 0,
- .arg = "",
- };
- Shell.lsp(&shell, req);
- try std.testing.expect(core.lsp_ask.wait == null);
- try std.testing.expectEqualStrings("abc", pane.file.?.content);
-
- pane.body.cur_col = 2;
- pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true };
- core.update(.{ .key = .{ .cp = '|' } });
- core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
- core.update(.{ .key = .{ .cp = pardes.Key.enter } });
- const pipe_id = core.pipe.wait.?.id;
- Shell.pipe(&shell, pipe_id);
- try std.testing.expect(core.pipe.wait == null);
- try std.testing.expectEqualStrings("abc", pane.file.?.content);
- try std.testing.expect(shell.lsp_task == null);
- try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len);
- }
-}
-
-test "a short wake request cuts short a long one still sleeping" {
- const io = std.testing.io;
- var seen = wake_gen.load(.acquire);
- requestWake(io, 800);
- seen = wake_gen.load(.acquire);
- const Timer = struct {
- fn run(timer_io: std.Io, start_seen: u32, done: *std.atomic.Value(u64)) void {
- var local = start_seen;
- _ = timeWake(timer_io, &local);
- done.store(@intCast(std.Io.Clock.awake.now(timer_io).nanoseconds), .release);
- }
- };
- var done: std.atomic.Value(u64) = .init(0);
- const start: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds);
- const thread = try std.Thread.spawn(.{}, Timer.run, .{ io, seen, &done });
- try io.sleep(.fromMilliseconds(50), .awake);
- requestWake(io, 16);
- thread.join();
- // The 16 ms request lands about 66 ms in: well before the 800 ms one
- // would have, however loaded the machine.
- try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms);
-}
-
-test "a terminal pane gets function keys as their sequences and lone modifiers not at all" {
- const gpa = std.testing.allocator;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- t.vx.queries_done.store(false, .unordered);
- var reader: TestReader = .{
- .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(&t.loop, &reader, &t.vx, &t.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 t.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", vaxis_input.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());
- }
- }
-}
-
-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);
- }
-}
-
-test "a jump's trail tints the ground behind the cursor in its body, and is gone by 120 ms" {
- std.testing.refAllDecls(JumpTrail);
- const gpa = std.testing.allocator;
- 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.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 = .{};
- const ms = std.time.ns_per_ms;
- s.cursor = .{ .x = body.x + 2, .y = body.y + 1 };
- _ = try trailCells(arena.allocator(), s, &trail, true, 1000 * ms);
- // Ten cells right: a trail back toward where it was.
- s.cursor = .{ .x = body.x + 12, .y = body.y + 1 };
- const lit = try trailCells(arena.allocator(), s, &trail, true, 1016 * ms);
- var changed: usize = 0;
- for (lit.cells, s.cells, 0..) |a, b, i| {
- if (std.meta.eql(a, b)) 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);
- try std.testing.expect(trail.active);
- try std.testing.expect(try trailCells(arena.allocator(), s, &trail, true, 1150 * ms) == s);
- try std.testing.expect(!trail.active);
-}
-
-test "a fade sends the text it dims, not the blanks beside it" {
- const gpa = std.testing.allocator;
- var t: TestInput = undefined;
- try t.init();
- defer t.deinit();
- try t.vx.resize(gpa, &t.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 };
- t.out.clearRetainingCapacity();
- paintCells(t.vx.window(), &cells, 32, 1);
- try t.vx.render(&t.out.writer);
- sent[frame] = try t.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);
-}
-
-test "the tty draws a glide at whole rows: once a flick or a spin slows, its steps a tick never grow and its one-row steps come further apart, to where the core is" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 30, .tty_only = true });
- defer core.deinit();
- var text: std.ArrayList(u8) = .empty;
- defer text.deinit(gpa);
- for (0..3000) |i| try text.print(gpa, "{d:0>5} line\n", .{i});
- _ = try core.setTestFile(text.items);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- var glide: pardes.glide.Glide = .{};
- defer glide.deinit(gpa);
- var now: u64 = std.time.ns_per_s;
- // One tick of the tty: the frame, the picture.
- const tick = struct {
- fn f(c: *pardes.Pardes, g: *pardes.glide.Glide, a: *std.heap.ArenaAllocator, t: u64) !i32 {
- c.advance(t);
- _ = a.reset(.retain_capacity);
- const s = try c.render(a.allocator());
- g.frame(std.testing.allocator, s, t, null, null);
- _ = try glideRows(a.allocator(), s, g);
- return @intFromFloat(@round(g.follow.offset));
- }
- }.f;
- _ = try tick(core, &glide, &arena, now);
- for ([_]usize{ 4, 24 }) |notches| {
- for (0..notches) |i| {
- core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 20, .row = 10 } });
- if (i % 2 == 1) {
- now += pardes.frame_ns;
- _ = try tick(core, &glide, &arena, now);
- }
- }
- var drawn = try tick(core, &glide, &arena, now + pardes.frame_ns);
- now += pardes.frame_ns;
- var last_step: i32 = std.math.maxInt(i32);
- var last_gap: usize = 0;
- var since: usize = 0;
- var ticks: usize = 0;
- while (glide.moving()) : (ticks += 1) {
- try std.testing.expect(ticks < 200);
- now += pardes.frame_ns;
- const k = try tick(core, &glide, &arena, now);
- const step = k - drawn;
- drawn = k;
- since += 1;
- if (step == 0) continue;
- // Toward the core, never past it, each step no longer than the last.
- try std.testing.expect(step > 0 and k <= 0);
- try std.testing.expect(step <= last_step);
- if (step == 1 and last_step == 1) try std.testing.expect(since >= last_gap);
- if (step == 1) last_gap = since;
- last_step = step;
- since = 0;
- }
- try std.testing.expectEqual(@as(i32, 0), drawn);
- }
- // j held on the bottom row: the text glides a row a key under a caret
- // that stays on its cell (it does not ride: its row is kept).
- const keys = struct {
- fn j(c: *pardes.Pardes) void {
- c.update(.{ .key = .{ .cp = 'j', .text = "j" } });
- }
- };
- for (0..40) |_| keys.j(core);
- now += std.time.ns_per_s;
- _ = try tick(core, &glide, &arena, now);
- const row = (core.surface.cursor orelse return error.NoCursor).y;
- for (0..20) |i| {
- if (i % 2 == 0) keys.j(core);
- now += pardes.frame_ns;
- _ = try tick(core, &glide, &arena, now);
- const shown = try glideRows(arena.allocator(), &core.surface, &glide);
- try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y);
- }
-}