diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-09 00:52:52 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-09 01:28:28 -0300 |
| commit | 5157579ff7f9ae0cfc3c7629e953da05bce340fc (patch) | |
| tree | 02147789efdcea998981efcfe05d4bcb3e9bb7b0 /src/terminal.zig | |
| parent | 4c4b9bf54d77dbc0f9f4e2619746908e501c6001 (diff) | |
| download | pardes-5157579ff7f9ae0cfc3c7629e953da05bce340fc.tar.gz pardes-5157579ff7f9ae0cfc3c7629e953da05bce340fc.zip | |
tests: at the end of their files: every top-level test block of the 46 files that had one mid-file (the locality analysis's 45 and test/hxdiff.zig; gui.zig, macos.zig, look, host_io, 9p_io, terminal, tui, mouse, fs, replica, layout among them, 11,429 test lines), with the functions only tests call, moved after the file's code in their order, a mechanical move (.scratch/suites/tests_to_end.py), zig fmt'd; the unit suites pass as before (tui 1486/1487, gui 1536/1537, core 956/956 on both), macos.zig only parse-checked here
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
Diffstat (limited to 'src/terminal.zig')
| -rw-r--r-- | src/terminal.zig | 839 |
1 files changed, 419 insertions, 420 deletions
diff --git a/src/terminal.zig b/src/terminal.zig index 16ffb34b..d8f279dc 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -565,7 +565,7 @@ pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4; pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { const m = &state.stream.handler; var w: std.Io.Writer = .fixed(buf); - w.writeByte(@intFromEnum(m.phase)) catch unreachable; + w.writeByte(@backingInt(m.phase)) catch unreachable; inline for (.{ m.started, m.prompts, m.declined }) |n| w.writeInt(u32, n, .little) catch unreachable; w.writeAll(&.{ @intFromBool(m.continuation), @intFromBool(m.lost) }) catch unreachable; w.writeInt(u32, if (m.finished) |f| f.seq else std.math.maxInt(u32), .little) catch unreachable; @@ -577,7 +577,7 @@ pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { pub fn takeMarks(state: *State, bytes: []const u8) void { if (bytes.len != marks_len) return; const m = &state.stream.handler; - m.phase = @enumFromInt(bytes[0]); + m.phase = @fromBackingInt(@intCast(bytes[0])); m.started = std.mem.readInt(u32, bytes[1..5], .little); m.prompts = std.mem.readInt(u32, bytes[5..9], .little); m.declined = std.mem.readInt(u32, bytes[9..13], .little); @@ -949,188 +949,6 @@ fn ingest(pane: *Pane, bytes: []const u8) void { pane.terminal.?.changes +%= 1; } -test "replay ownership is terminal-only and construction rolls back on allocation failure" { - const Case = struct { - fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqual(terminal, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field - // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). - const Filling = struct { - child: std.mem.Allocator, - fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - const ptr = self.child.rawAlloc(len, a, ra) orelse return null; - @memset(ptr[0..len], 0xAA); - return ptr; - } - fn resize(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawResize(buf, a, n, ra); - } - fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.child.rawRemap(buf, a, n, ra); - } - fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { - const self: *@This() = @ptrCast(@alignCast(ctx)); - self.child.rawFree(buf, a, ra); - } - const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free }; - }; - var filling: Filling = .{ .child = std.testing.allocator }; - const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expect(pane.terminal.?.resize_to == null); -} - -test "document construction allocates only the pane and has inert terminal defaults" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); - const allocator = failing.allocator(); - const pane = try createDoc(allocator, 40, 12); - defer allocator.destroy(pane); - defer deinitEmulator(pane, allocator); - try std.testing.expect(pane.terminal == null); - try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); - try std.testing.expectEqual(@as(usize, 0), failing.resize_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expect(!bracketedPaste(pane)); - try std.testing.expect(!reportsMouse(pane)); - try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, 80, 24); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var replies: usize = 0; - while (p.nextEffect()) |effect| { - if (effect != .write) continue; - try std.testing.expectEqual(@as(u8, 0), effect.write.pane); - try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - replies += 1; - } - try std.testing.expectEqual(@as(usize, 1), replies); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); -} - -test "a terminal's dump restores the cells it drew, its history and where its view was" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - for (0..30) |i| { - var line: [16]u8 = undefined; - feedOutput(p, pane, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); - } - scrollGrid(pane, -5); - const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); - defer gpa.free(bytes); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const state = try gpa.create(State); - defer gpa.destroy(state); - state.* = try pardes.walk.load(State, gpa, bytes, null); - defer { - state.stream.deinit(); - state.vt.deinit(gpa); - } - try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); - try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try panes.newCommand(p, cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - try std.testing.expectEqualStrings("make test", again.command.?); - try std.testing.expect(again.command_done); - try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "old output\r\n$ ls\r\n"); - try pane.setOwnedCwd("/tmp"); - pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash - try pardes.dump.dumpState(p); - const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - try std.testing.expectEqualStrings("bash", again.shell.?); - try std.testing.expect(again.command == null); - try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; - const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; - try std.testing.expect(old_at < mark_at); -} - /// What a pane says when a position kept over its terminal's rows could /// not follow the output (no memory for its pin), so it was reset. const positions_lost = "terminal edit position reset: out of memory"; @@ -1434,42 +1252,6 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) bool { return failed; } -test "a position that cannot follow the output for want of memory is said on the message row, and logged" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - feedOutput(p, pane, "one\r\ntwo\r\n"); - // More positions than the emulator's pins have room for: following them - // through the output needs memory, and there is none. - try std.testing.expect(pane.body.reserveSels()); - for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; - pane.body.nsel = 8; - failing.fail_index = failing.alloc_index; - feedOutput(p, pane, "three\r\n"); - failing.fail_index = std.math.maxInt(usize); - try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualStrings(positions_lost, pane.msg[0..pane.msg_len]); - const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; - try std.testing.expectEqualStrings(positions_lost, logged.slice()); -} - -test "raw terminal output needs no position tracking allocations" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - feedOutput(p, pane, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - feedOutput(p, pane, " output"); - try std.testing.expectEqual(allocations, failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); -} - /// A full-screen program has the emulator on its alternate screen. pub fn onAlternateScreen(pane: *const Pane) bool { const state = pane.terminal orelse return false; @@ -1834,17 +1616,6 @@ pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { return c.rows; } -test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = p.panes[0].?; - try std.testing.expect(pane.terminal != null); - _ = try shellRows(p, pane); - // A pane's teardown drops its entry; the rows stay until the sweep. - p.shell_rows.dropPane(pane); - _ = try shellRows(p, pane); -} - /// The full modal motion surface: shell history with the live edit overlay /// spliced into the rows it covers. pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { @@ -1976,7 +1747,6 @@ pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { overlay.text = new; } - /// Set while a frame is drawn: what it reads is no step's. pub var drawing = false; @@ -2400,7 +2170,7 @@ fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghost // cast takes one to the other (cellStyle, pager.zig). comptime { for (@typeInfo(@FieldType(pardes.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| - if (@intFromEnum(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); + if (@backingInt(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); } fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { @@ -2415,7 +2185,7 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor .reverse = style.flags.inverse, .invisible = style.flags.invisible, .strikethrough = style.flags.strikethrough, - .ul = @enumFromInt(@intFromEnum(style.flags.underline)), + .ul = @fromBackingInt(@intCast(@backingInt(style.flags.underline))), }; if (filtered == null) switch (ci.cell.content_tag) { .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), @@ -2604,6 +2374,421 @@ fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { return @intCast(dr * dr + dg * dg + db * db); } +pub fn palColor(p: *Pardes, idx: u8) pardes.Color { + if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; + return .{ .index = idx }; +} + +fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { + return switch (color) { + .none => blk: { + const t = if (is_bg) p.theme().bg else p.theme().fg; + break :blk if (t) |c| .{ .rgb = c } else .default; + }, + .palette => |idx| palColor(p, idx), + .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, + }; +} + +/// executing at a prompt with typed text below it: pad the output area +/// with newlines so the command's output doesn't overwrite the buffer +pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { + // Nothing to pad away from: with no emulator there is no prompt and no + // child whose output could land on top of the edit buffer. + const pane = p.panes[id] orelse return; + const o = pane.ovl orelse return; + if (!pane.isTerminal()) return; + const state = pane.terminal orelse return; + if (!state.vt.cursorIsAtPrompt()) return; + // the buffer's LAST surface row: its lines may outnumber the shell + // rows it covers, and it is the bottom one output must clear + const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; + const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); + const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); + const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); + var i: i32 = 0; + while (i < pad) : (i += 1) p.emitWrite(id, "\r"); +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + pane.body.remember(p.gpa, pane.ovl); +} + +/// Undo (back) or redo one step of the edit overlay. +pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) void { + const to = pane.body.step(p.gpa, pane.ovl, back) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = to.ovl; + pane.ensureCursorVisible(); +} + +fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + // A cut answer is worse than none: the program would read the start of + // a sequence and wait, or misparse what follows. + if (data.len > room) { + state.reply_dropped +|= 1; + return; + } + @memcpy(state.reply[state.reply_len..][0..data.len], data); + state.reply_len += @intCast(data.len); +} + +fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { + return .{}; +} + +/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a +/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. +fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { + const t = handler.terminal; + if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; + return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; +} + +/// The emulator's size in pixels follows the shell's cells: kitty graphics +/// placements are sized by it, and CSI 14/16 t report it. +fn syncPixels(p: *const Pardes, pane: *Pane) void { + if (comptime !images_enabled) return; + const state = pane.terminal orelse return; + const vt = &state.vt; + vt.width_px = @as(u32, vt.cols) * p.view().cell_pixels.w; + vt.height_px = @as(u32, vt.rows) * p.view().cell_pixels.h; +} + +/// When the pane's next kitty animation frame is due (ms on the core's +/// clock), as its last drawn frame left it; null when nothing plays. +pub fn animationDueMs(pane: *const Pane) ?u64 { + if (comptime !images_enabled) return null; + const state = pane.terminal orelse return null; + return state.images.animation_due_ms; +} + +/// The Petscii builtin on a terminal: its kitty graphics as glyph art, +/// or back to pixels where the shell draws pixels. +pub fn togglePetscii(pane: *Pane) void { + if (comptime !images_enabled) return; + const state = pane.terminal orelse return; + state.images.petscii = !state.images.petscii; +} + +/// Whether the pane draws its kitty graphics as glyph art by choice; null +/// for a pane with no emulator. +pub fn petscii(pane: *const Pane) ?bool { + if (comptime !images_enabled) return null; + const state = pane.terminal orelse return null; + return state.images.petscii; +} + +/// Whether the screen showing holds any kitty graphics image. +pub fn hasImages(pane: *const Pane) bool { + if (comptime !images_enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active.kitty_images.images.count() > 0; +} + +/// Draw the pane's kitty graphics images over its body rows (after the +/// rows and their colours: placeholder cells are blanked here). +pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + if (comptime !images_enabled) return; + const state = pane.terminal orelse return; + const screen = state.vt.screens.active; + syncPixels(p, pane); + // A body taller than this draws its images on the rows that fit. + var rows_of: [1024]?u16 = undefined; + const vp_rows: usize = @min(scrollbar(pane).len, rows_of.len); + @memset(rows_of[0..vp_rows], null); + var any_placeholder = false; + var walk: BodyWalk = .init(pane); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + const vi = switch (row) { + .grid => |v| v, + .edit => continue, + }; + if (vi < 0 or vi >= vp_rows) continue; + const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const flags = row_pin.rowAndCell().row; + // A prompt row outside tty mode is cut or hidden: its columns are + // not the grid's. + if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; + any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; + rows_of[@intCast(vi)] = vr; + } + // Nothing to draw, no placeholder to blank and nothing cached to let + // go: the common case costs the rows' flags. + if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; + state.images.draw(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); +} + +/// Every byte the core wrote to each pane's pty since the last call, `\n` +/// between panes' shares: "0:<bytes>\n1:<bytes>\n" for panes that got any. +fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); + defer for (&per) |*b| b.deinit(p.gpa); + while (p.nextEffect()) |effect| { + if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); + } + for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); + return out.items; +} + +/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the +/// right, with the rest of the control data `extra` (`c=2,r=1` places it +/// over two cells). +inline fn kittyTransmit(comptime extra: []const u8) []const u8 { + return comptime blk: { + const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; + const pixels = row ++ row; + var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; + const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; + break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; + }; +} + +fn imagePlaces(s: *const Surface) []const pardes.Placement { + return s.placements.items; +} + +/// `n` line breaks: enough of them push the screen's rows into history. +fn lineBreaks(comptime n: usize) [2 * n]u8 { + var out: [2 * n]u8 = undefined; + for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; + return out; +} + +test "replay ownership is terminal-only and construction rolls back on allocation failure" { + const Case = struct { + fn run(gpa: std.mem.Allocator, terminal: bool) !void { + const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqual(terminal, pane.terminal != null); + } + }; + try std.testing.expect(@sizeOf(Pane) < 128 * 1024); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); +} + +test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { + // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field + // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). + const Filling = struct { + child: std.mem.Allocator, + fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + const ptr = self.child.rawAlloc(len, a, ra) orelse return null; + @memset(ptr[0..len], 0xAA); + return ptr; + } + fn resize(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) bool { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.child.rawResize(buf, a, n, ra); + } + fn remap(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + return self.child.rawRemap(buf, a, n, ra); + } + fn free(ctx: *anyopaque, buf: []u8, a: std.mem.Alignment, ra: usize) void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + self.child.rawFree(buf, a, ra); + } + const vtable: std.mem.Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free }; + }; + var filling: Filling = .{ .child = std.testing.allocator }; + const gpa: std.mem.Allocator = .{ .ptr = &filling, .vtable = &Filling.vtable }; + const pane = try create(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expect(pane.terminal.?.resize_to == null); +} + +test "document construction allocates only the pane and has inert terminal defaults" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const allocator = failing.allocator(); + const pane = try createDoc(allocator, 40, 12); + defer allocator.destroy(pane); + defer deinitEmulator(pane, allocator); + try std.testing.expect(pane.terminal == null); + try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); + try std.testing.expectEqual(@as(usize, 0), failing.resize_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expect(!bracketedPaste(pane)); + try std.testing.expect(!reportsMouse(pane)); + try std.testing.expect(!promptInputReady(pane)); + scrollGrid(pane, 100); + followOutput(pane); + resizeGrid(pane, 80, 24); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); + try std.testing.expect(!failing.has_induced_failure); +} + +test "terminal state keeps parser fragments and sends emulator replies through its owner" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + const state = pane.terminal.?; + try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); + while (p.nextEffect()) |effect| { + if (effect == .write) return error.PrematureTerminalReply; + } + p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); + var replies: usize = 0; + while (p.nextEffect()) |effect| { + if (effect != .write) continue; + try std.testing.expectEqual(@as(u8, 0), effect.write.pane); + try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); + replies += 1; + } + try std.testing.expectEqual(@as(usize, 1), replies); + try std.testing.expectEqual(@as(u16, 0), state.reply_len); +} + +test "a terminal's dump restores the cells it drew, its history and where its view was" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + for (0..30) |i| { + var line: [16]u8 = undefined; + feedOutput(p, pane, std.fmt.bufPrint(&line, "line {d}\r\n", .{i}) catch unreachable); + } + scrollGrid(pane, -5); + const bytes = try pardes.walk.save(State, gpa, pane.terminal.?); + defer gpa.free(bytes); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const state = try gpa.create(State); + defer gpa.destroy(state); + state.* = try pardes.walk.load(State, gpa, bytes, null); + defer { + state.stream.deinit(); + state.vt.deinit(gpa); + } + try std.testing.expectEqual(pardes.walk.digest(State, pane.terminal.?), pardes.walk.digest(State, state)); + try std.testing.expectEqual(pane.terminal.?.vt.screens.active.pages.scrollbar(), state.vt.screens.active.pages.scrollbar()); +} + +test "a restored command pane comes back finished, its command not run again" { + if (comptime pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const cmd = p.freeSlot().?; + _ = try panes.newCommand(p, cmd, "/tmp", "make test"); + feedOutput(p, p.panes[cmd].?, "ok\r\n"); + p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); + defer restored.deinit(); + var spawns: usize = 0; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => spawns += 1, + else => {}, + }; + try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command + const again = for (restored.panes) |slot| { + if (slot) |pane| if (pane.command != null) break pane; + } else return error.CommandPaneLost; + try std.testing.expectEqualStrings("make test", again.command.?); + try std.testing.expect(again.command_done); + try std.testing.expectEqual(@as(?u8, 2), again.command_status); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); +} + +test "a restored terminal keeps its history above a marker and gets a shell where it was" { + if (comptime pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "old output\r\n$ ls\r\n"); + try pane.setOwnedCwd("/tmp"); + pane.shell = try gpa.dupe(u8, "bash"); // `Term bash`: it comes back as bash + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + defer restored.deinit(); + var spawned = false; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), + else => {}, + }; + try std.testing.expect(spawned); + const again = restored.panes[0].?; + try std.testing.expectEqualStrings("bash", again.shell.?); + try std.testing.expect(again.command == null); + try std.testing.expectEqual(.spawn, again.pending_command.wait); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; + const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; + try std.testing.expect(old_at < mark_at); +} + +test "a position that cannot follow the output for want of memory is said on the message row, and logged" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[0].?; + feedOutput(p, pane, "one\r\ntwo\r\n"); + // More positions than the emulator's pins have room for: following them + // through the output needs memory, and there is none. + try std.testing.expect(pane.body.reserveSels()); + for (pane.body.sels[0..8], 0..) |*range, i| range.* = .{ .row = @intCast(i), .col = 0, .arow = @intCast(i), .acol = 1 }; + pane.body.nsel = 8; + failing.fail_index = failing.alloc_index; + feedOutput(p, pane, "three\r\n"); + failing.fail_index = std.math.maxInt(usize); + try std.testing.expect(failing.has_induced_failure); + try std.testing.expectEqualStrings(positions_lost, pane.msg[0..pane.msg_len]); + const logged = p.messages.at(p.messages.len -| 1) orelse return error.NothingLogged; + try std.testing.expectEqualStrings(positions_lost, logged.slice()); +} + +test "raw terminal output needs no position tracking allocations" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + feedOutput(p, pane, "warm"); + const allocations = failing.alloc_index; + failing.fail_index = allocations; + const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); + feedOutput(p, pane, " output"); + try std.testing.expectEqual(allocations, failing.alloc_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); +} + +test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = p.panes[0].?; + try std.testing.expect(pane.terminal != null); + _ = try shellRows(p, pane); + // A pane's teardown drops its entry; the rows stay until the sweep. + p.shell_rows.dropPane(pane); + _ = try shellRows(p, pane); +} + test "the luminance table answers exactly what ghostty computes" { for (0..256) |i| { const c: u8 = @intCast(i); @@ -2985,168 +3170,6 @@ test "a prompt row hidden end to end paints nothing at all" { try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); } -pub fn palColor(p: *Pardes, idx: u8) pardes.Color { - if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; - return .{ .index = idx }; -} - -fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { - return switch (color) { - .none => blk: { - const t = if (is_bg) p.theme().bg else p.theme().fg; - break :blk if (t) |c| .{ .rgb = c } else .default; - }, - .palette => |idx| palColor(p, idx), - .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, - }; -} - -/// executing at a prompt with typed text below it: pad the output area -/// with newlines so the command's output doesn't overwrite the buffer -pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { - // Nothing to pad away from: with no emulator there is no prompt and no - // child whose output could land on top of the edit buffer. - const pane = p.panes[id] orelse return; - const o = pane.ovl orelse return; - if (!pane.isTerminal()) return; - const state = pane.terminal orelse return; - if (!state.vt.cursorIsAtPrompt()) return; - // the buffer's LAST surface row: its lines may outnumber the shell - // rows it covers, and it is the bottom one output must clear - const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; - const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); - const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); - const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); - var i: i32 = 0; - while (i < pad) : (i += 1) p.emitWrite(id, "\r"); -} - -pub fn pushUndo(p: *Pardes, pane: *Pane) void { - pane.body.remember(p.gpa, pane.ovl); -} - -/// Undo (back) or redo one step of the edit overlay. -pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) void { - const to = pane.body.step(p.gpa, pane.ovl, back) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = to.ovl; - pane.ensureCursorVisible(); -} - -fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: []const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - // A cut answer is worse than none: the program would read the start of - // a sequence and wait, or misparse what follows. - if (data.len > room) { - state.reply_dropped +|= 1; - return; - } - @memcpy(state.reply[state.reply_len..][0..data.len], data); - state.reply_len += @intCast(data.len); -} - -fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) ghostty_vt.device_attributes.Attributes { - return .{}; -} - -/// CSI 14/16/18 t: the pane's size, and its cells' in pixels, which a -/// program sizes its kitty graphics by (yazi asks 16 t). Unknown, not asked. -fn ptySize(handler: *ghostty_vt.TerminalStream.Handler) ?ghostty_vt.size_report.Size { - const t = handler.terminal; - if (t.width_px == 0 or t.height_px == 0 or t.cols == 0 or t.rows == 0) return null; - return .{ .rows = t.rows, .columns = t.cols, .cell_width = t.width_px / t.cols, .cell_height = t.height_px / t.rows }; -} - -/// The emulator's size in pixels follows the shell's cells: kitty graphics -/// placements are sized by it, and CSI 14/16 t report it. -fn syncPixels(p: *const Pardes, pane: *Pane) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - const vt = &state.vt; - vt.width_px = @as(u32, vt.cols) * p.view().cell_pixels.w; - vt.height_px = @as(u32, vt.rows) * p.view().cell_pixels.h; -} - -/// When the pane's next kitty animation frame is due (ms on the core's -/// clock), as its last drawn frame left it; null when nothing plays. -pub fn animationDueMs(pane: *const Pane) ?u64 { - if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; - return state.images.animation_due_ms; -} - -/// The Petscii builtin on a terminal: its kitty graphics as glyph art, -/// or back to pixels where the shell draws pixels. -pub fn togglePetscii(pane: *Pane) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - state.images.petscii = !state.images.petscii; -} - -/// Whether the pane draws its kitty graphics as glyph art by choice; null -/// for a pane with no emulator. -pub fn petscii(pane: *const Pane) ?bool { - if (comptime !images_enabled) return null; - const state = pane.terminal orelse return null; - return state.images.petscii; -} - -/// Whether the screen showing holds any kitty graphics image. -pub fn hasImages(pane: *const Pane) bool { - if (comptime !images_enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active.kitty_images.images.count() > 0; -} - -/// Draw the pane's kitty graphics images over its body rows (after the -/// rows and their colours: placeholder cells are blanked here). -pub fn drawImages(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16) void { - if (comptime !images_enabled) return; - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - syncPixels(p, pane); - // A body taller than this draws its images on the rows that fit. - var rows_of: [1024]?u16 = undefined; - const vp_rows: usize = @min(scrollbar(pane).len, rows_of.len); - @memset(rows_of[0..vp_rows], null); - var any_placeholder = false; - var walk: BodyWalk = .init(pane); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - const vi = switch (row) { - .grid => |v| v, - .edit => continue, - }; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = screen.pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const flags = row_pin.rowAndCell().row; - // A prompt row outside tty mode is cut or hidden: its columns are - // not the grid's. - if (pane.body.mode != .tty and flags.semantic_prompt != .none) continue; - any_placeholder = any_placeholder or flags.kitty_virtual_placeholder; - rows_of[@intCast(vi)] = vr; - } - // Nothing to draw, no placeholder to blank and nothing cached to let - // go: the common case costs the rows' flags. - if (!any_placeholder and screen.kitty_images.placements.count() == 0 and state.images.converted.count() == 0) return; - state.images.draw(p, s, &state.vt, @intCast(id), pane.serial, tx, body_y, @min(tw, pane.cols), rows_of[0..vp_rows]); -} - -/// Every byte the core wrote to each pane's pty since the last call, `\n` -/// between panes' shares: "0:<bytes>\n1:<bytes>\n" for panes that got any. -fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - var per: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty); - defer for (&per) |*b| b.deinit(p.gpa); - while (p.nextEffect()) |effect| { - if (effect == .write) try per[effect.write.pane].appendSlice(p.gpa, effect.write.bytes.slice()); - } - for (per, 0..) |b, id| if (b.items.len > 0) try out.print(p.gpa, "{d}:{s}\n", .{ id, b.items }); - return out.items; -} - test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); @@ -3185,23 +3208,6 @@ test "a program that asked for focus reports hears CSI I and CSI O as its pane t try std.testing.expectEqualStrings("1:\x1b[O\n", try ptyWritesByPane(p, &out)); } -/// `a=T` of a 4x2 RGB image, `i=7`, red on the left half, blue on the -/// right, with the rest of the control data `extra` (`c=2,r=1` places it -/// over two cells). -inline fn kittyTransmit(comptime extra: []const u8) []const u8 { - return comptime blk: { - const row = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 }; - const pixels = row ++ row; - var buf: [std.base64.standard.Encoder.calcSize(pixels.len)]u8 = undefined; - const b64 = std.base64.standard.Encoder.encode(&buf, &pixels)[0..buf.len].*; - break :blk "\x1b_Ga=T,f=24,s=4,v=2,i=7," ++ extra ++ ";" ++ b64 ++ "\x1b\\"; - }; -} - -fn imagePlaces(s: *const Surface) []const pardes.Placement { - return s.placements.items; -} - test "a terminal's kitty graphics image is drawn where its program placed it, and a delete takes it away" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; @@ -3249,13 +3255,6 @@ test "a terminal's kitty graphics image is drawn where its program placed it, an try std.testing.expectEqual(@as(usize, 0), imagePlaces(s).len); } -/// `n` line breaks: enough of them push the screen's rows into history. -fn lineBreaks(comptime n: usize) [2 * n]u8 { - var out: [2 * n]u8 = undefined; - for (0..n) |i| out[2 * i ..][0..2].* = "\r\n".*; - return out; -} - test "ED 3 takes away a kitty placement whose row it erased: it never comes back at the top" { if (comptime !images_enabled) return error.SkipZigTest; const gpa = std.testing.allocator; |
