diff options
Diffstat (limited to 'src/terminal.zig')
| -rw-r--r-- | src/terminal.zig | 316 |
1 files changed, 158 insertions, 158 deletions
diff --git a/src/terminal.zig b/src/terminal.zig index 81fae5db..6fdd46f0 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -8,7 +8,6 @@ const Pardes = pardes.Pardes; const Surface = pardes.Surface; const modal = @import("modal.zig"); const tracy = @import("tracy.zig"); -const dump = @import("dump.zig"); const tagline = @import("tagline.zig"); const Key = pardes.Key; const Pane = panes.Pane; @@ -183,6 +182,121 @@ pub const State = struct { text.writer.flush() catch {}; h.* = text.hasher; } + + /// What the dump keeps of a terminal beside its emulator, by name as + /// every dump is (src/walk.zig). + const Parts = struct { + reply: []const u8 = "", + reply_dropped: u32 = 0, + mouse_cell: ?ghostty_vt.Coordinate = null, + petscii: bool = false, + /// The view's top row, counted from the top of the history. + view: usize = 0, + phase: @FieldType(MarkedHandler, "phase") = .none, + started: u32 = 0, + prompts: u32 = 0, + declined: u32 = 0, + continuation: bool = false, + lost: bool = false, + finished: @FieldType(MarkedHandler, "finished") = null, + out_start: ?ghostty_vt.Coordinate = null, + out_end: ?ghostty_vt.Coordinate = null, + }; + + fn pinAt(s: *const State, slot: ?*ghostty_vt.Pin) ?ghostty_vt.Coordinate { + const pin = slot orelse return null; + const screen = s.vt.screens.get(.primary) orelse return null; + return (screen.pages.pointFromPin(.screen, pin.*) orelse return null).screen; + } + + /// The dump's: ghostty's snapshot of the emulator (both screens, their + /// history, styles, links and kitty images), then `Parts`. A sequence + /// its program had begun and not ended is not kept: the snapshot is at + /// the ground state. + pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { + if (comptime !enabled) return; + const h = &s.stream.handler; + const parts: Parts = .{ + .reply = s.reply[0..s.reply_len], + .reply_dropped = s.reply_dropped, + .mouse_cell = s.mouse_cell, + .petscii = if (comptime images_enabled) s.images.petscii else false, + .view = s.vt.screens.active.pages.scrollbar().offset, + .phase = h.phase, + .started = h.started, + .prompts = h.prompts, + .declined = h.declined, + .continuation = h.continuation, + .lost = h.lost, + .finished = h.finished, + .out_start = s.pinAt(h.out_start), + .out_end = s.pinAt(h.out_end), + }; + const bytes = try pardes.walk.save(Parts, gpa, &parts); + defer gpa.free(bytes); + try w.writeAll(std.mem.asBytes(&@as(u64, bytes.len))); + try w.writeAll(bytes); + try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); + } + + /// What `dumpRead` made, freed: a load that failed after it. + pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { + if (comptime !enabled) return; + if (comptime images_enabled) s.images.deinit(gpa); + s.stream.deinit(); + s.vt.deinit(gpa); + } + + /// `dumpWrite`'s back into `out`, a new State, as `create` makes one. + pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { + if (comptime !enabled) { + out.* = .{ .vt = {}, .stream = {} }; + return; + } + if (bytes.len < 8) return error.EndOfDump; + const n = std.mem.bytesToValue(u64, bytes[0..8]); + if (bytes.len - 8 < n) return error.EndOfDump; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const parts = try pardes.walk.load(Parts, arena.allocator(), bytes[8..][0..n], null); + var reader: std.Io.Reader = .fixed(bytes[8 + n ..]); + var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ + .max_continuation_bytes = 0, + .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + }); + defer decoded.deinit(gpa); + out.* = .{ .vt = decoded.toOwned(), .stream = undefined }; + if (comptime images_enabled) inline for (.{ .primary, .alternate }) |key| { + if (out.vt.screens.get(key)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); + }; + out.stream = .init(.{ .handler = .{ .inner = out.vt.vtHandler() }, .allocator = gpa }); + out.stream.handler.inner.effects.write_pty = ptyReport; + out.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + out.stream.handler.inner.effects.size = ptySize; + const reply = parts.reply[0..@min(parts.reply.len, out.reply.len)]; + @memcpy(out.reply[0..reply.len], reply); + out.reply_len = @intCast(reply.len); + out.reply_dropped = parts.reply_dropped; + out.mouse_cell = parts.mouse_cell; + out.images = if (images_enabled) .{ .petscii = parts.petscii } else {}; + if (comptime images_enabled) TerminalImages.installPngDecoder(); + const h = &out.stream.handler; + h.phase = parts.phase; + h.started = parts.started; + h.prompts = parts.prompts; + h.declined = parts.declined; + h.continuation = parts.continuation; + h.lost = parts.lost; + h.finished = parts.finished; + if (out.vt.screens.get(.primary)) |screen| { + inline for (.{ .{ "out_start", parts.out_start }, .{ "out_end", parts.out_end } }) |pair| if (pair[1]) |at| { + if (screen.pages.pin(.{ .screen = at })) |pin| @field(h, pair[0]) = screen.pages.trackPin(pin) catch null; + }; + } + const screen = out.vt.screens.active; + const bottom = screen.pages.scrollbar().offset; + screen.scroll(.{ .delta_row = @as(isize, @intCast(parts.view)) - @as(isize, @intCast(bottom)) }); + } }; const GColor = ghostty_vt.color; @@ -714,42 +828,25 @@ pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { /// Where a restored terminal's history ends and its new shell begins. pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; -/// Rebuild a dump's terminal emulator from its recorded output. `live`: a -/// shell will be spawned into it, so the history is marked off from what -/// that shell prints and the pane waits for it like any new terminal. -/// Registration and tag/cwd policy stay with the core; raw VT replay and -/// viewport restoration belong here. -pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { - const terminal = src.terminal.?; - if (comptime !enabled) { - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - errdefer p.gpa.destroy(pane); - if (terminal.stream.len > 0) - pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; - return pane; - } - const bytes = if (terminal.stream_b64.len > 0) - try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) - else - &.{}; - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - if (live) { - if (bytes.len > 0) { - ingest(pane, bytes); - ingest(pane, restored_banner); - } - followOutput(pane); - // A view left scrolled back stays on what it was showing: the - // banner's line breaks scrolled a full screen by that many more. - if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); - armShellSpawn(pane); - } else if (bytes.len > 0) { - ingest(pane, bytes); - followOutput(pane); - if (src.scroll > 0) - scrollGrid(pane, -@as(i32, @intCast(src.scroll))); - } - return pane; +/// A terminal loaded from a dump, its shell not there, made ready for a new +/// one: its program's screen modes reset (the old program is gone), its +/// history marked off from what the new shell prints, and the pane waiting +/// for it like any new terminal (a line queued for the old one goes to it). +pub fn reviveShell(pane: *Pane) void { + if (comptime !enabled) return; + if (pane.terminal == null) return; + // The primary screen, modes and mouse as a shell starts with them. + ingest(pane, "\x1b[?1049l\x1b[!p\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[<u"); + ingest(pane, restored_banner); + // What the old shell was, ran and said is gone with it: the REPL it + // ran, the Tty+ word naming it. + pane.shell_spoke = false; + pane.had_shell = false; + pane.shell_failed = false; + pane.shell_tail_len = 0; + pane.repl = null; + pane.sent_command = null; + pane.pending_command.wait = .spawn; } /// Feed the emulator. Live output and restoration share this byte path, @@ -822,32 +919,32 @@ test "terminal state keeps parser fragments and sends emulator replies through i try std.testing.expectEqual(@as(u16, 0), state.reply_len); } -test "a terminal stream restores the cells it drew" { +test "a terminal's dump restores the cells it drew, its history and where its view was" { if (comptime !enabled) 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].?; - const drawn = "\x1b[31mred\x1b[0m\r\ncafé\r\n"; - feedOutput(p, pane, drawn); - const encoded = try dump.encodeBytes(gpa, drawn); - defer gpa.free(encoded); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = pane.cols, - .rows = pane.rows, - .terminal = .{ .stream_b64 = encoded }, - }, false); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - const before = try screenTextAlloc(pane, gpa); - defer gpa.free(before); - const after = try screenTextAlloc(restored, gpa); - defer gpa.free(after); - try std.testing.expectEqualStrings(before, after); + 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" { @@ -860,8 +957,8 @@ test "a restored command pane comes back finished, its command not run again" { _ = try p.newCommand(cmd, "/tmp", "make test"); feedOutput(p, p.panes[cmd].?, "ok\r\n"); p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try dump.dumpState(p); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); + 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) { @@ -890,8 +987,8 @@ test "a restored terminal keeps its history above a marker and gets a shell wher feedOutput(p, pane, "old output\r\n$ ls\r\n"); try pane.setOwnedCwd("/tmp"); pane.shell = try gpa.dupe(u8, "bash"); // `Tty bash`: it comes back as bash - try dump.dumpState(p); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + 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) { @@ -1729,103 +1826,6 @@ pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { overlay.text = new; } -/// The shell's screen and scrollback (the primary screen, even under a -/// full-screen program) as VT that replays to what was shown: styled -/// text, soft-wrapped lines rejoined so they reflow at another width. -fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { - const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; - var out: std.Io.Writer.Allocating = .init(arena); - try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); - return out.written(); -} - -/// Serialize terminal-only state; the core supplies shared pane metadata. -pub fn dumpPane( - pane: *Pane, - arena: std.mem.Allocator, - tag: []const u8, - body: []const u8, - scroll: usize, -) !dump.Pane { - if (!enabled or pane.terminal == null) { - const text = if (pane.ovl) |overlay| overlay.text else ""; - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = try arena.dupe(u8, text), - .stream_b64 = &.{}, - .cursor = .{ .col = 0, .row = 0 }, - }, - }; - } - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); - const extra = if (pane.ovl) |overlay| overlay.text.len else 0; - const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); - var len: usize = 0; - var lines = std.mem.splitAny(u8, full, "\n"); - var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - var row: i32 = 0; - var skip: i32 = 0; - while (lines.next()) |raw| : (row += 1) { - // Hidden overlay rows still consume prompt pins to keep them aligned. - const prompt = if (pane.body.mode != .tty) prompts.next() else null; - if (skip > 0) { - skip -= 1; - continue; - } - if (row > 0) { - stream[len] = '\n'; - len += 1; - } - if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { - @memcpy(stream[len..][0..overlay.text.len], overlay.text); - len += overlay.text.len; - skip = overlay.rows - 1; - continue; - }; - const shown = if (prompt) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - @memcpy(stream[len..][0..shown.len], shown); - len += shown.len; - } - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), - .stream_is_screen = true, - .petscii = petscii(pane) orelse false, - .cursor = .{ - .col = pane.terminal.?.vt.screens.active.cursor.x, - .row = pane.terminal.?.vt.screens.active.cursor.y, - }, - }, - }; -} fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); |
