summaryrefslogtreecommitdiff
path: root/src/dump.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/dump.zig')
-rw-r--r--src/dump.zig1341
1 files changed, 444 insertions, 897 deletions
diff --git a/src/dump.zig b/src/dump.zig
index 0da2513f..5f5f5870 100644
--- a/src/dump.zig
+++ b/src/dump.zig
@@ -1,20 +1,14 @@
const std = @import("std");
const builtin = @import("builtin");
const limits = @import("memory.zig").limits;
-
-// scoped, not bare std.log: main.zig's logFn drops the unscoped .default scope
-// wholesale (ghostty and uucode log there too), and a corrupt dump's parse
-// diagnostic is the only thing that says WHICH field went bad.
-const log = std.log.scoped(.dump);
const pardes = @import("pardes.zig");
-const tagline = @import("tagline.zig");
-const layout = @import("layout.zig");
+const walk = @import("walk.zig");
+const Handover = @import("Handover.zig");
const filesystem = @import("fs.zig");
+const layout = @import("layout.zig");
const ctlfs = @import("ninep/tree.zig");
const exec = @import("exec.zig");
-const body_layer = @import("body_layer.zig");
const colors = @import("colors.zig");
-const themes = colors.themes;
const config = @import("config.zig");
const pdf_enabled = pardes.pdf_enabled;
const platform = pardes.platform;
@@ -22,15 +16,14 @@ const isolated = pardes.isolated;
const terminal_panes = pardes.terminal_panes;
const MAX_PANES = pardes.MAX_PANES;
const MAX_COLS = pardes.MAX_COLS;
-const column_weight_unit = layout.column_weight_unit;
-const max_column_weight = layout.max_column_weight;
const effect_path_cap = pardes.effect_path_cap;
const Options = pardes.Options;
const Pardes = pardes.Pardes;
+const views = pardes.views;
/// Where the next dump goes. $PARDES_DUMP wins verbatim (the snapshot harness
/// pins it for deterministic goldens); else $XDG_DATA_HOME|~/.local/share
-/// /pardes/pardes-<utc>.zon — timestamped so dumps never overwrite each other.
+/// /pardes/pardes-<utc>.dump — timestamped so dumps never overwrite each other.
/// Creates the directory and any parent missing (a fresh HOME has no
/// ~/.local/share); a failure surfaces at open.
pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 {
@@ -53,15 +46,15 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 {
return uniqueIn(buf, dir, base);
}
-/// `<dir>/<base>.zon`, or `<base>-2.zon` and on when two dumps land in one
+/// `<dir>/<base>.dump`, or `<base>-2.dump` and on when two dumps land in one
/// second: a dump never overwrites another.
fn uniqueIn(buf: *[1024:0]u8, dir: []const u8, base: []const u8) ?[:0]const u8 {
var n: usize = 1;
while (n < 1000) : (n += 1) {
const path = (if (n == 1)
- std.fmt.bufPrintSentinel(buf, "{s}/{s}.zon", .{ dir, base }, 0)
+ std.fmt.bufPrintSentinel(buf, "{s}/{s}.dump", .{ dir, base }, 0)
else
- std.fmt.bufPrintSentinel(buf, "{s}/{s}-{d}.zon", .{ dir, base, n }, 0)) catch return null;
+ std.fmt.bufPrintSentinel(buf, "{s}/{s}-{d}.dump", .{ dir, base, n }, 0)) catch return null;
if (comptime !pardes.hosted) return path;
if (std.c.access(path.ptr, std.c.F_OK) != 0) return path;
}
@@ -76,9 +69,9 @@ test "two dumps in one second get names of their own" {
var buf: [1024:0]u8 = undefined;
const first = try std.testing.allocator.dupe(u8, uniqueIn(&buf, dir, "pardes-x").?);
defer std.testing.allocator.free(first);
- try std.testing.expect(std.mem.endsWith(u8, first, "/pardes-x.zon"));
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-x.zon", .data = "" });
- try std.testing.expect(std.mem.endsWith(u8, uniqueIn(&buf, dir, "pardes-x").?, "/pardes-x-2.zon"));
+ try std.testing.expect(std.mem.endsWith(u8, first, "/pardes-x.dump"));
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-x.dump", .data = "" });
+ try std.testing.expect(std.mem.endsWith(u8, uniqueIn(&buf, dir, "pardes-x").?, "/pardes-x-2.dump"));
}
/// The host's environment; a freestanding core (web, the board) has none
/// and no libc to ask, so only a DumpDir with no `~/` names a directory there.
@@ -136,955 +129,443 @@ pub fn defaultDirectory(buf: []u8) ?[]const u8 {
return null;
}
-pub const magic = "pardes-dump";
-pub const version: u32 = 1;
-pub const max_panes: usize = MAX_PANES;
-pub const max_cols: usize = MAX_COLS;
-/// Output arguments are typed in the same bounded one-line tag storage. Keep
-/// the schema limit named independently so a dump reader can validate it
-/// without importing the output-pane implementation. The bound itself is
-/// `limits.max_tag_tail` — the one place a board-shaped capacity is chosen.
-pub const max_origin_arg: usize = limits.max_tag_tail;
-
-pub const Size = struct {
- cols: u16,
- rows: u16,
-};
-
-pub const Cursor = struct {
- col: u16 = 0,
- row: u16 = 0,
-};
-
-pub const PaneKind = enum {
- terminal,
- file,
- image,
-};
-
-pub const Terminal = struct {
- cwd: []const u8 = "",
- /// The shell it runs when not the configured one (`Tty bash`); empty,
- /// the configured one, as in dumps from before.
- shell: []const u8 = "",
- /// A command pane's line and how it ended (null: unknown, or still
- /// running when dumped); empty for an interactive terminal.
- command: []const u8 = "",
- status: ?u8 = null,
- /// The rendered scrollback and screen as plain text, one row per line.
- stream: []const u8 = "",
- stream_b64: []const u8 = "",
- /// `stream_b64` is the emulator's primary screen and scrollback as clean
- /// VT (ghostty's formatter), which replays to what the screen showed.
- /// Absent (older dumps), it is the raw tail of the pty's output, which
- /// replays faithfully only if it holds the whole session at one size.
- stream_is_screen: bool = false,
- cursor: Cursor = .{},
- /// Petscii on: its kitty graphics drawn as glyph art by choice.
- petscii: bool = false,
-};
-
-pub const LocationRow = struct {
- mark_occurrence: bool = true,
- source_column: usize = 0,
- kind: enum { match, context, preview },
- declaration: bool = false,
- path: []const u8,
- line: usize,
- col: usize = 0,
- end_line: usize = 0,
- end_col: usize = 0,
- location_end: usize,
- code_start: usize,
- colors_b64: []const u8 = "",
-};
-
-pub const File = struct {
- path: []const u8 = "",
- /// The text, in older dumps plain and base64 both; now base64 alone,
- /// and only for a pane whose text is not its file's on disk (unsaved,
- /// an output, a file never written): a clean file's is read from disk.
- content: []const u8 = "",
- content_b64: []const u8 = "",
- dirty: bool = false,
- /// An unsaved pane's: the hash of the file on disk its text was read
- /// against. A Restore that finds another there says it changed, and
- /// Save asks before overwriting it.
- disk_hash: ?u64 = null,
- /// Its file was on disk when dumped: one gone by the Restore is said
- /// deleted, one never written (Config's new file) is not. True in
- /// older dumps.
- on_disk: bool = true,
- tree_context: bool = false,
- location_rows: []const LocationRow = &.{},
- // Builtin names remain stable when enum ordinals change.
- origin: []const u8 = "",
- origin_arg: []const u8 = "",
- mini_source: []const u8 = "",
- mini_colors_b64: []const u8 = "",
- /// Its dot, q0 and q1 in bytes, as acme's dump keeps a window's; null
- /// in older dumps.
- dot: ?[2]u32 = null,
- /// A Zerox twin: the index, in `panes`, of the earlier pane whose
- /// buffer it shares, its text kept there once; null for none.
- twin_of: ?u32 = null,
-};
-
-pub const ImagePalette = enum {
- commodore,
- terminal,
-};
+/// What a load makes a terminal's emulator with, when not the loader's
+/// own: a screen-state replica's are the C heap's (src/replica.zig).
+pub var terminal_gpa: ?std.mem.Allocator = null;
-pub const Image = struct {
- path: []const u8 = "",
- bytes_b64: []const u8 = "",
- // Defaults are the renderer's historical state, so version-1 dumps which
- // predate these fields remain readable without a schema fork.
- petscii: bool = false,
- palette: ImagePalette = .commodore,
- ascii: bool = true,
- /// A PDF's PdfFit and PdfTint, by their tag words (`width`, `filtered`);
- /// empty, the defaults, as in dumps from before.
- pdf_fit: []const u8 = "",
- pdf_tint: []const u8 = "",
-};
+// ---- a whole session to and from a dump (acme keeps this in rows.c) ----
+//
+// A dump (src/walk.zig) is everything the session is but what is the
+// host's, the frame's or worked out again: its panes with their text and
+// undo, terminals with their screens, history and kitty images (ghostty's
+// snapshot), registers, places, tags, layout and settings. It crosses
+// builds: its fields are matched by name.
+//
+// Loading is two halves. `load` makes the core the dump was and nothing
+// else (a replica joining a session takes that, phase 5); `revivePane` and
+// `reviveSession` give it to this host: new shells, watches, PDFs opened.
-pub const Pane = struct {
- kind: PaneKind,
- tag: []const u8,
- body: []const u8,
- scroll: usize = 0,
- cols: u16 = 0,
- rows: u16 = 0,
- vweight: f32 = 1,
- collapsed: bool = false,
- /// Its serial when dumped (0 in older dumps): a Restore logs
- /// `restored <old> <new>` for it.
- serial: u32 = 0,
- /// Exact editable tail when the user touched it. Null retains the live
- /// default; a present empty slice deliberately restores an empty tail.
- tag_tail: ?[]const u8 = null,
- /// The index in `panes` of the pane this one is attached to (layout.zig,
- /// "Attached panes"); null when it is attached to none, and in older dumps.
- attached_to: ?usize = null,
- terminal: ?Terminal = null,
- file: ?File = null,
- image: ?Image = null,
-};
+/// A session's dump: its core, everything it is but what is the host's,
+/// the frame's or worked out again (`replica` in each type, src/walk.zig),
+/// then its 9P mounts, which live with the 9P server's own state, which of
+/// its panes' files were on disk when it was made (one gone by its load is
+/// said deleted: its text is nowhere else now), its theme's name (the
+/// setting is a place in this build's ring of themes, another build's
+/// ring is another), and the views not live (views.zig: the core holds
+/// the live one's).
+const Session = walk.Dump(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8, []const views.Dumped });
+const SessionLoad = walk.Load(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8, []const views.Dumped });
+const OnDisk = [MAX_PANES]bool;
-pub const Column = struct {
- /// Its serial when dumped (0 in older dumps): a Restore logs
- /// `restoredcol <old> <new>` for it.
- serial: u32 = 0,
- tag: ?[]const u8 = null,
- weight: f32 = 1,
- panes: []const usize = &.{},
-};
-
-pub const Mount = struct { name: []const u8, dial: []const u8 };
-
-/// What a grip carried out of its window (Handover.zig): one pane with the
-/// panes attached to it, or a whole column. A session's own dump is none.
-pub const Carried = enum { pane, column };
-
-pub const State = struct {
- magic: []const u8 = magic,
- version: u32 = version,
- screen: Size,
- active: usize = 0,
- topbar: []const u8 = "",
- topbar_custom: ?[]const u8 = null,
- theme: []const u8 = "dark",
- locations_config: @import("locations.zig").Config = .{},
- tree_context_tag_style: bool = true,
- columns: []const Column = &.{},
- panes: []const Pane = &.{},
- mounts: []const Mount = &.{},
- /// The settings that differ from a fresh session's, each a line as the
- /// root ctl takes it (`Placement pardes`); the theme and the locations
- /// config are kept on their own, and the font is the frontend's. Absent
- /// in older dumps.
- settings: []const []const u8 = &.{},
- /// Incl's directories, in order; null in older dumps (the defaults).
- incl: ?[]const []const u8 = null,
- /// A dump a grip carried to another window; null for a session's own.
- carried: ?Carried = null,
-};
-
-/// A header is a text like any other: it may hold newlines, but not a
-/// carriage return or a NUL.
-fn validateTag(bar: []const u8) !void {
- if (bar.len > limits.max_tag_tail or std.mem.indexOfAny(u8, bar, "\r\x00") != null or !std.unicode.utf8ValidateSlice(bar)) return error.BadDumpTag;
+fn onDisk(pane: *const pardes.panes.Pane) bool {
+ if (comptime !pardes.hosted) return false;
+ const f = pane.file orelse return false;
+ if (f.output != null) return false;
+ const local = filesystem.localPath(f.path) orelse return false;
+ return exec.kindOf(local) != null;
}
-pub fn validate(state: State) !void {
- if (state.topbar_custom) |bar| try validateTag(bar);
- for (state.columns) |column| if (column.tag) |bar| try validateTag(bar);
- if (!std.mem.eql(u8, state.magic, magic)) return error.BadDumpMagic;
- if (state.version != version) return error.BadDumpVersion;
- if (state.panes.len == 0 or state.panes.len > max_panes) return error.BadDumpPanes;
- if (state.columns.len == 0 or state.columns.len > max_cols) return error.BadDumpColumns;
- if (state.active >= state.panes.len) return error.BadDumpActive;
- if (state.mounts.len > 8) return error.BadDumpMounts;
- for (state.mounts, 0..) |mount, i| {
- if (mount.name.len == 0 or mount.name.len > 255 or mount.dial.len == 0 or
- std.mem.indexOfScalar(u8, mount.dial, 0) != null) return error.BadDumpMounts;
- if (std.mem.eql(u8, mount.name, ".") or std.mem.eql(u8, mount.name, "..") or
- std.mem.eql(u8, mount.name, "os") or std.mem.eql(u8, mount.name, "self")) return error.BadDumpMounts;
- for (mount.name) |c| if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-' and c != '.') return error.BadDumpMounts;
- for (state.mounts[0..i]) |previous| if (std.mem.eql(u8, mount.name, previous.name)) return error.BadDumpMounts;
- }
- for (state.columns) |col| {
- if (!std.math.isFinite(col.weight) or col.weight <= 0) return error.BadDumpColumns;
- // An empty column is a column, as in acme's dump (rows.c:639).
- if (col.panes.len > max_panes) return error.BadDumpColumns;
- for (col.panes) |pane| {
- if (pane >= state.panes.len) return error.BadDumpPaneRef;
- }
- }
- for (state.panes) |pane| {
- if (!std.math.isFinite(pane.vweight) or pane.vweight <= 0)
- return error.BadDumpPaneWeight;
- if (pane.scroll > std.math.maxInt(i32)) return error.BadDumpPaneScroll;
- if (pane.tag_tail) |tail| if (tail.len > limits.max_tag_tail)
- return error.BadDumpTagTail;
- if (pane.file) |file| if (file.origin_arg.len > max_origin_arg)
- return error.BadDumpOriginArg;
- if (pane.file) |file| {
- if (file.mini_source.len > 4096 or std.mem.indexOfScalar(u8, file.mini_source, 0) != null or
- (file.mini_source.len == 0 and file.mini_colors_b64.len != 0) or
- (file.mini_source.len != 0 and !std.mem.eql(u8, file.origin, "Mini"))) return error.BadDumpMini;
- }
- switch (pane.kind) {
- .terminal => if (pane.terminal == null) return error.BadDumpPaneKind,
- .file => if (pane.file == null) return error.BadDumpPaneKind,
- .image => if (pane.image == null) return error.BadDumpPaneKind,
- }
- }
+pub fn dumpState(p: *Pardes) !void {
+ const bytes = try dumpBytes(p);
+ if (p.dump_out) |d| p.gpa.free(d);
+ p.dump_out = bytes;
+ p.emit(.write_dump);
}
-test "oversized recognized output argument is rejected before restore" {
- var oversized: [max_origin_arg + 1]u8 = @splat('x');
- const pane_ids = [_]usize{0};
- const columns = [_]Column{.{ .panes = &pane_ids }};
- const panes = [_]Pane{.{
- .kind = .file,
- .tag = "+Search",
- .body = "",
- .file = .{
- .path = "/tmp/+Search",
- .origin = "Find",
- .origin_arg = &oversized,
- },
- }};
- const state: State = .{
- .screen = .{ .cols = 80, .rows = 24 },
- .columns = &columns,
- .panes = &panes,
- };
+/// The session as a dump, gpa-owned.
+pub fn dumpBytes(p: *Pardes) ![]u8 {
+ return dumpWith(p, null);
+}
- // Serialize without writeFile: that writer correctly rejects the state
- // too, while this exercises the hostile bytes a restore actually reads.
- var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator);
- defer encoded.deinit();
- try std.zon.stringify.serialize(state, .{}, &encoded.writer);
- try std.testing.expectError(
- error.BadDumpOriginArg,
- readZon(std.testing.allocator, encoded.written(), "oversized-origin-arg"),
- );
+/// A dump for a screen-state replica's join (src/replica.zig): its blobs'
+/// bytes left out and noted in `deferred` (they are the session's, alive
+/// while pinned: memory.zig `pin`), its terminals' emulators left out (the
+/// first delta brings each afresh). What is left is the session's mutable
+/// state, made in its step.
+pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 {
+ slim_terminals = true;
+ defer slim_terminals = false;
+ return dumpWith(p, deferred);
}
-pub const Parsed = struct {
- value: State,
- arena: std.heap.ArenaAllocator,
+/// `dumpJoin`'s: a terminal dumps its size, not its emulator.
+pub var slim_terminals = false;
- pub fn deinit(parsed: *Parsed) void {
- parsed.arena.deinit();
+fn dumpWith(p: *Pardes, deferred: ?*std.ArrayListUnmanaged(walk.Deferred)) ![]u8 {
+ var d = try Session.init(p.gpa);
+ errdefer d.deinit();
+ d.deferred = deferred;
+ try d.put(Pardes, p);
+ const mounts: []const filesystem.Mount = p.fs.mounts.items;
+ try d.put([]const filesystem.Mount, &mounts);
+ var on_disk: OnDisk = @splat(false);
+ for (p.panes, &on_disk) |slot, *on| if (slot) |pane| {
+ on.* = onDisk(pane);
+ };
+ try d.put(OnDisk, &on_disk);
+ const theme: []const u8 = colors.themes[@min(p.settings.theme, colors.themes.len - 1)].name;
+ try d.put([]const u8, &theme);
+ const others = try views.dumped(p, p.gpa);
+ defer {
+ for (others) |o| p.gpa.free(o.panes);
+ p.gpa.free(others);
}
-};
+ const kept: []const views.Dumped = others;
+ try d.put([]const views.Dumped, &kept);
+ return d.finish();
+}
-/// Whether `bytes` are a dump a Restore could load, saying nothing: a
+/// Whether `bytes` are a dump a Restore could read, saying nothing: a
/// Restore asks before it warns about unsaved text or replaces anything.
-/// Whether `bytes` are a dump; a ZON failure's line and reason are left in
-/// `why`, ended by a 0.
+/// Why not is left in `why`, ended by a 0.
pub fn check(gpa: std.mem.Allocator, bytes: []const u8, why: []u8) !void {
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- const source = try arena.allocator().dupeSentinel(u8, bytes, 0);
- var diag: std.zon.parse.Diagnostics = undefined;
- const state = std.zon.parse.fromSlice(State, .{ .gpa = gpa, .arena = arena.allocator(), .source = source, .diagnostics = &diag }) catch |err| {
- const said = pardes.Messages.zonWhy(&diag, why[0 .. why.len - 1]);
- if (said.ptr != why.ptr) @memcpy(why[0..said.len], said);
+ var l = SessionLoad.init(gpa, bytes) catch |err| {
+ const said = std.fmt.bufPrint(why[0 .. why.len - 1], "{s}", .{switch (err) {
+ error.BadDump => "it does not begin as one",
+ error.EndOfDump => "it is cut short",
+ else => @errorName(err),
+ }}) catch "";
why[said.len] = 0;
return err;
};
- try validate(state);
+ l.deinit();
}
-pub fn readZon(gpa: std.mem.Allocator, bytes: []const u8, label: []const u8) !Parsed {
- var parsed: Parsed = .{ .value = undefined, .arena = .init(gpa) };
- errdefer parsed.deinit();
- const arena = parsed.arena.allocator();
- const source = try gpa.dupeSentinel(u8, bytes, 0);
- defer gpa.free(source);
-
- var diag: std.zon.parse.Diagnostics = undefined;
- parsed.value = std.zon.parse.fromSlice(State, .{ .gpa = gpa, .arena = arena, .source = source, .diagnostics = &diag }) catch |err| {
- if (err == error.ParseZon) log.err("{f}", .{diag.fmt(label)});
- return err;
- };
- try validate(parsed.value);
- return parsed;
-}
-
-pub fn encodeBytes(alloc: std.mem.Allocator, bytes: []const u8) ![]const u8 {
- const enc = std.base64.standard.Encoder;
- const out = try alloc.alloc(u8, enc.calcSize(bytes.len));
- return enc.encode(out, bytes);
+/// The core the dump `bytes` is, and nothing more: no shell started, no
+/// file watched, nothing asked of a host (`revive` does that). What another
+/// build's dump could not give is said in `notes` when given. `opts` are
+/// this process's (its allocators, paths and name), not the dump's.
+pub fn load(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*std.ArrayList(u8)) !*Pardes {
+ return loadKnowing(gpa, opts, bytes, notes, null);
}
-pub fn decodeBytes(alloc: std.mem.Allocator, b64: []const u8) ![]u8 {
- const dec = std.base64.standard.Decoder;
- const n = try dec.calcSizeForSlice(b64);
- const out = try alloc.alloc(u8, n);
- errdefer alloc.free(out);
- try dec.decode(out, b64);
- return out;
-}
-
-test "dump zon roundtrip" {
- const gpa = std.testing.allocator;
- const tty_b64 = try encodeBytes(gpa, "old\nhello\nworld");
- defer gpa.free(tty_b64);
- const file_b64 = try encodeBytes(gpa, "alpha\nbeta\n");
- defer gpa.free(file_b64);
- const panes = [_]Pane{
- .{
- .kind = .terminal,
- .tag = "nm /tmp Del",
- .body = "hello\nworld",
- .scroll = 1,
- .cols = 40,
- .rows = 10,
- .terminal = .{ .cwd = "/tmp", .stream = "old\nhello\nworld", .stream_b64 = tty_b64, .cursor = .{ .col = 3, .row = 2 } },
- },
- .{
- .kind = .file,
- .tag = "nm /tmp/a.txt Save Del",
- .body = " 1 alpha",
- .cols = 20,
- .rows = 5,
- .file = .{ .path = "/tmp/a.txt", .content = "alpha\nbeta\n", .content_b64 = file_b64, .dirty = true },
- },
- };
- const col_panes = [_]usize{ 0, 1 };
- const columns = [_]Column{.{ .weight = 1, .panes = &col_panes }};
- const state: State = .{
- .screen = .{ .cols = 80, .rows = 24 },
- .topbar = "Kill Newcol Dump",
- .theme = "dark",
- .columns = &columns,
- .panes = &panes,
+/// `load`, with which panes' files were on disk when it was dumped.
+fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*std.ArrayList(u8), on_disk: ?*OnDisk) !*Pardes {
+ const p = try Pardes.create(gpa, opts);
+ var l = SessionLoad.init(gpa, bytes) catch |err| {
+ p.deinit();
+ return err;
};
-
- var out: std.Io.Writer.Allocating = .init(gpa);
- defer out.deinit();
- try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);
- var result = try readZon(gpa, out.written(), "roundtrip");
- defer result.deinit();
- const parsed = result.value;
- try std.testing.expectEqual(@as(usize, 2), parsed.panes.len);
- try std.testing.expectEqualStrings("dark", parsed.theme);
- try std.testing.expectEqualStrings("old\nhello\nworld", parsed.panes[0].terminal.?.stream);
- try std.testing.expectEqualStrings("alpha\nbeta\n", parsed.panes[1].file.?.content);
- try std.testing.expect(parsed.panes[1].file.?.dirty);
- {
- const bytes = try decodeBytes(gpa, parsed.panes[0].terminal.?.stream_b64);
- defer gpa.free(bytes);
- try std.testing.expectEqualStrings("old\nhello\nworld", bytes);
+ defer l.deinit();
+ // A load that fails leaves nothing: what it read is freed, and the
+ // core with it, its fields never torn down one by one.
+ errdefer {
+ l.rollback();
+ p.fs.deinit(gpa);
+ gpa.destroy(p);
}
- {
- const bytes = try decodeBytes(gpa, parsed.panes[1].file.?.content_b64);
- defer gpa.free(bytes);
- try std.testing.expectEqualStrings("alpha\nbeta\n", bytes);
+ l.allocs = .{ .image = p.image_gpa, .pdf = p.pdf_gpa, .terminal = terminal_gpa };
+ try l.into(Pardes, p);
+ const read = l.shared.items.len;
+ const mounts = try l.get([]const filesystem.Mount);
+ defer {
+ for (mounts) |m| {
+ gpa.free(m.name);
+ gpa.free(m.dial);
+ }
+ gpa.free(mounts);
+ // Freed here: no rollback of them.
+ l.shared.shrinkRetainingCapacity(read);
}
-}
-
-test "omitted dump defaults roundtrip without borrowing input" {
- const gpa = std.testing.allocator;
- const fixture =
- \\.{
- \\ .screen = .{ .cols = 80, .rows = 24 },
- \\ .columns = .{.{ .panes = .{0, 1, 2} }},
- \\ .panes = .{
- \\ .{ .kind = .terminal, .tag = "terminal", .body = "", .terminal = .{} },
- \\ .{ .kind = .file, .tag = "file", .body = "", .file = .{ .path = "file.zig", .content = "const café = 1;" } },
- \\ .{ .kind = .image, .tag = "image", .body = "", .image = .{} },
- \\ },
- \\}
- ;
- const input = try gpa.dupe(u8, fixture);
- defer gpa.free(input);
- var parsed = try readZon(gpa, input, "omitted-defaults");
- defer parsed.deinit();
- @memset(input, 'x');
- const value = parsed.value;
- try std.testing.expectEqualStrings(magic, value.magic);
- try std.testing.expectEqualStrings("dark", value.theme);
- try std.testing.expectEqualStrings("", value.topbar);
- try std.testing.expectEqual(@as(usize, 0), value.mounts.len);
- try std.testing.expectEqual(@as(usize, 3), value.panes.len);
- try std.testing.expectEqualStrings("file.zig", value.panes[1].file.?.path);
- try std.testing.expectEqualStrings("const café = 1;", value.panes[1].file.?.content);
- try std.testing.expect(!value.panes[1].file.?.dirty);
- try std.testing.expect(value.panes[2].image.?.ascii);
-
- var encoded: std.Io.Writer.Allocating = .init(gpa);
- defer encoded.deinit();
- try std.zon.stringify.serialize(value, .{}, &encoded.writer);
- var again = try readZon(gpa, encoded.written(), "default-roundtrip");
- defer again.deinit();
- try std.testing.expectEqualDeep(value, again.value);
-}
-
-test "dump parser releases its arena at every allocation failure" {
- const Check = struct {
- fn run(gpa: std.mem.Allocator) !void {
- var parsed = try readZon(gpa,
- \\.{
- \\ .screen = .{ .cols = 80, .rows = 24 },
- \\ .columns = .{.{ .panes = .{0} }},
- \\ .panes = .{.{ .kind = .file, .tag = "file", .body = "", .file = .{ .content = "owned" } }},
- \\}
- , "allocation-cleanup");
- defer parsed.deinit();
- try std.testing.expectEqualStrings("owned", parsed.value.panes[0].file.?.content);
+ const was = try l.get(OnDisk);
+ if (on_disk) |out| out.* = was;
+ const theme = try l.get([]const u8);
+ defer gpa.free(theme);
+ // This build's place for that theme; one it has not, its first.
+ p.settings.theme = for (colors.themes, 0..) |t, i| {
+ if (std.mem.eql(u8, t.name, theme)) break i;
+ } else if (p.settings.theme < colors.themes.len) p.settings.theme else 0;
+ // A mount this process was started with stands; one of the same name
+ // to elsewhere is refused, never silently put over it.
+ for (mounts) |m| {
+ const existing = for (p.fs.mounts.items) |e| {
+ if (std.mem.eql(u8, e.name, m.name)) break e;
+ } else null;
+ if (existing) |e| {
+ if (!std.mem.eql(u8, e.dial, m.dial)) return error.MountConflict;
+ continue;
}
- };
- try std.testing.checkAllAllocationFailures(std.testing.allocator, Check.run, .{});
-}
-
-test "dump mount validation bounds names ownership inputs and duplicates" {
- const panes = [_]Pane{.{ .kind = .file, .tag = "", .body = "", .file = .{} }};
- const ids = [_]usize{0};
- const columns = [_]Column{.{ .panes = &ids }};
- var state: State = .{
- .screen = .{ .cols = 80, .rows = 24 },
- .columns = &columns,
- .panes = &panes,
- };
- try validate(state);
- for ([_]Mount{
- .{ .name = "peer", .dial = "/tmp/peer.sock" },
- .{ .name = "build-1.local", .dial = "tcp!127.0.0.1!5640" },
- }) |mount| {
- state.mounts = &.{mount};
- try validate(state);
+ p.fs.mount(gpa, m.name, m.dial) catch |err| l.note("mount {s}: {t}", .{ m.name, err });
}
- for ([_]Mount{
- .{ .name = "", .dial = "/tmp/peer.sock" },
- .{ .name = ".", .dial = "/tmp/peer.sock" },
- .{ .name = "..", .dial = "/tmp/peer.sock" },
- .{ .name = "os", .dial = "/tmp/peer.sock" },
- .{ .name = "self", .dial = "/tmp/peer.sock" },
- .{ .name = "two/parts", .dial = "/tmp/peer.sock" },
- .{ .name = "two parts", .dial = "/tmp/peer.sock" },
- .{ .name = "peer", .dial = "" },
- .{ .name = "peer", .dial = "unix!/tmp/peer\x00.sock" },
- }) |mount| {
- state.mounts = &.{mount};
- try std.testing.expectError(error.BadDumpMounts, validate(state));
+ if (l.notes.items.len > 0) {
+ // A pane another build could not give is left out: so is its
+ // place in the layout. One whose terminal it could not give is a
+ // terminal still.
+ dropMissing(p);
+ for (p.panes) |slot| if (slot) |pane| try ensureKind(p, pane);
+ if (notes) |n| try n.appendSlice(gpa, l.notes.items);
}
- const duplicate = Mount{ .name = "peer", .dial = "/tmp/peer.sock" };
- state.mounts = &.{ duplicate, duplicate };
- try std.testing.expectError(error.BadDumpMounts, validate(state));
- var name: [256]u8 = @splat('x');
- state.mounts = &.{.{ .name = name[0..255], .dial = "/tmp/peer.sock" }};
- try validate(state);
- state.mounts = &.{.{ .name = &name, .dial = "/tmp/peer.sock" }};
- try std.testing.expectError(error.BadDumpMounts, validate(state));
- const mounts = [_]Mount{
- .{ .name = "a", .dial = "/tmp/a" },
- .{ .name = "b", .dial = "/tmp/b" },
- .{ .name = "c", .dial = "/tmp/c" },
- .{ .name = "d", .dial = "/tmp/d" },
- .{ .name = "e", .dial = "/tmp/e" },
- .{ .name = "f", .dial = "/tmp/f" },
- .{ .name = "g", .dial = "/tmp/g" },
- .{ .name = "h", .dial = "/tmp/h" },
- .{ .name = "i", .dial = "/tmp/i" },
+ // The views not live, last: what it moves into the core is never
+ // rolled back from under it, nothing after it failing.
+ const at = l.shared.items.len;
+ const others = l.get([]const views.Dumped) catch |err| switch (err) {
+ // A dump made before views were in it.
+ error.EndOfDump => &.{},
+ else => return err,
};
- state.mounts = mounts[0..8];
- try validate(state);
- state.mounts = &mounts;
- try std.testing.expectError(error.BadDumpMounts, validate(state));
-}
-
-test "version-one image records default old fields and roundtrip new state" {
- const gpa = std.testing.allocator;
- const legacy =
- \\.{
- \\ .magic = "pardes-dump",
- \\ .version = 1,
- \\ .screen = .{ .cols = 80, .rows = 24 },
- \\ .active = 0,
- \\ .topbar = "",
- \\ .theme = "dark",
- \\ .columns = .{.{ .panes = .{0} }},
- \\ .panes = .{.{
- \\ .kind = .image,
- \\ .tag = "img /tmp/old.ppm New Del",
- \\ .body = "",
- \\ .image = .{ .path = "/tmp/old.ppm", .bytes_b64 = "" },
- \\ }},
- \\}
- ;
- var old = try readZon(gpa, legacy, "legacy-image");
- defer old.deinit();
- const old_image = old.value.panes[0].image.?;
- try std.testing.expect(!old_image.petscii);
- try std.testing.expectEqual(ImagePalette.commodore, old_image.palette);
- try std.testing.expect(old_image.ascii);
- try std.testing.expect(old.value.panes[0].tag_tail == null);
-
- const pane = Pane{
- .kind = .image,
- .tag = "img petscii:on palette:terminal ascii:off /tmp/new.ppm",
- .body = "",
- .tag_tail = "",
- .image = .{
- .path = "/tmp/new.ppm",
- .petscii = true,
- .palette = .terminal,
- .ascii = false,
- },
- };
- const ids = [_]usize{0};
- const columns = [_]Column{.{ .panes = &ids }};
- const panes = [_]Pane{pane};
- const state = State{
- .screen = .{ .cols = 80, .rows = 24 },
- .columns = &columns,
- .panes = &panes,
- };
- var out: std.Io.Writer.Allocating = .init(gpa);
- defer out.deinit();
- try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);
- var parsed = try readZon(gpa, out.written(), "new-image");
- defer parsed.deinit();
- const restored = parsed.value.panes[0].image.?;
- try std.testing.expect(restored.petscii);
- try std.testing.expectEqual(ImagePalette.terminal, restored.palette);
- try std.testing.expect(!restored.ascii);
- try std.testing.expect(parsed.value.panes[0].tag_tail != null);
- try std.testing.expectEqualStrings("", parsed.value.panes[0].tag_tail.?);
-}
-
-test "validation bounds pane restore state" {
- const ids = [_]usize{0};
- const columns = [_]Column{.{ .panes = &ids }};
- var panes = [_]Pane{.{
- .kind = .terminal,
- .tag = "term",
- .body = "",
- .terminal = .{},
- }};
- const state = State{
- .screen = .{ .cols = 80, .rows = 24 },
- .columns = &columns,
- .panes = &panes,
- };
- try validate(state);
-
- panes[0].vweight = 0;
- try std.testing.expectError(error.BadDumpPaneWeight, validate(state));
- panes[0].vweight = std.math.inf(f32);
- try std.testing.expectError(error.BadDumpPaneWeight, validate(state));
- panes[0].vweight = 1;
-
- panes[0].scroll = @as(usize, @intCast(std.math.maxInt(i32))) + 1;
- try std.testing.expectError(error.BadDumpPaneScroll, validate(state));
- panes[0].scroll = 0;
-
- var oversized_tail: [limits.max_tag_tail + 1]u8 = @splat('x');
- panes[0].tag_tail = &oversized_tail;
- try std.testing.expectError(error.BadDumpTagTail, validate(state));
- panes[0].tag_tail = oversized_tail[0..limits.max_tag_tail];
- try validate(state);
+ try views.undumped(p, others);
+ for (others) |o| gpa.free(o.panes);
+ gpa.free(others);
+ l.shared.shrinkRetainingCapacity(at);
+ return p;
}
-// ---- a whole editor to and from a dump (acme keeps this in rows.c) ----
-
-pub fn dumpState(p: *Pardes) !void {
- const bytes = try dumpBytes(p, null, null);
- if (p.dump_out) |d| p.gpa.free(d);
- p.dump_out = bytes;
- p.emit(.write_dump);
+/// A pane that is none of its kinds (a terminal kept slim, or one another
+/// build's dump could not give): a terminal, a new emulator for its shell.
+fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void {
+ if (pane.terminal != null or pane.file != null or pane.image != null or pane.hasPdf()) return;
+ const fresh = try pardes.panes.terminal.create(p.gpa, @max(1, pane.cols), @max(1, pane.rows));
+ pane.terminal = fresh.terminal;
+ fresh.terminal = null;
+ p.gpa.destroy(fresh);
}
-/// The dump of the panes `keep` marks (every pane for null), gpa-owned: a
-/// whole session's, or what a grip carries to another window (Handover.zig),
-/// `carried` saying which. Only the columns holding a kept pane are in it,
-/// and a carried pane's column tag is its old column's no longer.
-pub fn dumpBytes(p: *Pardes, keep: ?*const [MAX_PANES]bool, carried: ?Carried) ![]u8 {
- const arena = p.scratch.allocator();
- var slot_to_pane: [MAX_PANES]?usize = @splat(null);
- var dump_panes: [MAX_PANES]Pane = undefined;
- var panes_len: usize = 0;
- for (p.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- if (keep) |k| if (!k[id]) continue;
- slot_to_pane[id] = panes_len;
- dump_panes[panes_len] = try dumpPane(p, arena, pane);
- panes_len += 1;
- }
- // An attachment names its owner by its place in the dump: serials are
- // handed out again on a Restore.
- for (0..p.panes.len) |id| {
- const i = slot_to_pane[id] orelse continue;
- const owner = layout.ownerOf(p, id) orelse continue;
- // An attachment carried without its owner stands on its own.
- dump_panes[i].attached_to = slot_to_pane[owner];
- }
- // Zerox's twins: the text once, in the first; each other names it.
- for (p.panes, 0..) |slot, id| {
- const f = (slot orelse continue).file orelse continue;
- if (f.twin == 0) continue;
- const i = slot_to_pane[id] orelse continue;
- for (p.panes[0..id], 0..) |earlier, j_id| {
- const of = (earlier orelse continue).file orelse continue;
- if (of.twin != f.twin) continue;
- const j = slot_to_pane[j_id] orelse break;
- if (dump_panes[i].file) |*df| {
- df.twin_of = @intCast(j);
- df.content_b64 = "";
- }
- break;
- }
- }
-
- var columns: [MAX_COLS]Column = undefined;
- var columns_len: usize = 0;
- var column_ids: [MAX_COLS][MAX_PANES]usize = undefined;
+/// The panes a column lists that are not there (another build's dump left
+/// them out) taken out of it, and the keyboard on one that is.
+fn dropMissing(p: *Pardes) void {
for (0..p.ncol) |c| {
- var ids_len: usize = 0;
- for (0..p.col_n[c]) |k| if (slot_to_pane[p.col_panes[c][k]]) |compact| {
- column_ids[c][ids_len] = compact;
- ids_len += 1;
- };
- if (keep != null and ids_len == 0) continue;
- columns[columns_len] = .{
- .serial = layout.columnSerial(p, c),
- .tag = if (carried == .pane) null else p.col_tags[c].own,
- .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)),
- .panes = column_ids[c][0..ids_len],
+ var n: usize = 0;
+ for (p.col_panes[c][0..p.col_n[c]]) |id| if (id < MAX_PANES and p.panes[id] != null) {
+ p.col_panes[c][n] = id;
+ n += 1;
};
- columns_len += 1;
- }
-
- var mounts: [filesystem.max_mounts]Mount = undefined;
- for (p.fs.mounts.items, 0..) |mount, i| mounts[i] = .{ .name = mount.name, .dial = mount.dial };
- const state: State = .{
- .screen = .{ .cols = p.screen_w, .rows = p.screen_h },
- .active = slot_to_pane[p.active] orelse 0,
- .topbar = config.topbar_str,
- .topbar_custom = p.global_tag.own,
- .theme = p.theme().name,
- .locations_config = p.locations_config,
- .tree_context_tag_style = p.settings.tree_context_tag_style,
- .columns = columns[0..columns_len],
- .panes = dump_panes[0..panes_len],
- .mounts = mounts[0..p.fs.mounts.items.len],
- .settings = try changedSettings(p, arena),
- .incl = p.incl.items,
- .carried = carried,
- };
- try validate(state);
- var out: std.Io.Writer.Allocating = .init(p.gpa);
- errdefer out.deinit();
- try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);
- return out.toOwnedSlice();
-}
-
-/// One pane as a dump keeps it, its strings in `arena`: a Restore's, and a
-/// closed pane's in the store (Store.zig), which Panes brings back.
-pub fn dumpPane(p: *Pardes, arena: std.mem.Allocator, pane: *pardes.panes.Pane) !Pane {
- const tag = try tagline.tagText(p, arena, pane);
- const body = try body_layer.bodyText(p, arena, pane);
- const scroll: usize = @intCast(@max(0, pane.scroll()));
- var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane(
- p,
- arena,
- pane,
- f,
- tag,
- body,
- scroll,
- if (f.output) |o| pardes.panes.Output.word(o.from) else "",
- if (f.output) |*o| o.arg() else "",
- ) else if (pane.hasPdf()) blk: {
- if (comptime !pdf_enabled) unreachable;
- const pv = &pane.pdf.?;
- break :blk try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{});
- } else if (pane.image) |iv|
- try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw)
- else
- try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll);
- dp.tag_tail = pane.tag.own;
- if (dp.file) |*df| {
- const dot = ctlfs.pane.dotOf(pane);
- df.dot = .{ dot.q0, dot.q1 };
- }
- dp.serial = pane.serial;
- return dp;
-}
-
-/// The setting lines that differ from a fresh session's, as the root ctl
-/// reads them, less the ones a dump keeps apart.
-fn changedSettings(p: *Pardes, arena: std.mem.Allocator) ![]const []const u8 {
- var now: std.Io.Writer.Allocating = .init(arena);
- var fresh: std.Io.Writer.Allocating = .init(arena);
- const defaults: config.Runtime = .{};
- try pardes.ctlfs.ctl.writeSettingsOf(p, &p.settings, &now.writer);
- try pardes.ctlfs.ctl.writeSettingsOf(p, &defaults, &fresh.writer);
- var out: std.ArrayList([]const u8) = .empty;
- var lines = std.mem.splitScalar(u8, now.written(), '\n');
- while (lines.next()) |line| {
- if (line.len == 0) continue;
- const word = line[0 .. std.mem.indexOfScalar(u8, line, ' ') orelse line.len];
- if (std.mem.eql(u8, word, "Theme") or std.mem.eql(u8, word, "Font")) continue;
- var same = std.mem.splitScalar(u8, fresh.written(), '\n');
- while (same.next()) |other| {
- if (std.mem.eql(u8, other, line)) break;
- } else try out.append(arena, line);
- }
- return out.items;
-}
-
-/// Applies a dump's setting lines, each as the root ctl would.
-fn applySettings(p: *Pardes, lines: []const []const u8) void {
- for (lines) |line| {
- const sp = std.mem.indexOfScalar(u8, line, ' ');
- // A ThemeFile is a request the host answers by reading the file, as
- // a /ctl write of it is: asked again here, not dropped.
- if (std.mem.eql(u8, line[0 .. sp orelse line.len], "ThemeFile")) {
- if (sp) |s| colors.requestThemeFile(p, 0, line[s + 1 ..]);
- continue;
- }
- const setting = config.Runtime.find(line[0 .. sp orelse line.len]) orelse continue;
- _ = p.settings.apply(setting, if (sp) |s| line[s + 1 ..] else null);
- if (setting.action == .tab) config.tab_now = p.settings.tab;
+ p.col_n[c] = n;
}
+ if (p.active >= MAX_PANES or p.panes[p.active] == null) p.active = for (p.panes, 0..) |slot, i| {
+ if (slot != null) break i;
+ } else 0;
}
/// The replacement core for a Restore of the dump at `from`, whose log says
/// so after its panes' `new`s, for a client that reconnects to read.
-pub fn restore(p: *Pardes, zon_bytes: []const u8, from: []const u8) !*Pardes {
+pub fn restore(p: *Pardes, bytes: []const u8, from: []const u8) !*Pardes {
+ const taped = pardes.tape.enter(p, .{ .restore = .{ .bytes = bytes, .from = from } });
+ defer pardes.tape.leave(p, taped);
var opts = p.opts;
opts.cols = p.screen_w;
opts.rows = p.screen_h;
- var old: OldSerials = .{};
- const replacement = try initDump(p.gpa, opts, zon_bytes, p, &old);
+ const replacement = try loadAndRevive(p.gpa, opts, bytes, p, null);
replacement.pointRestoreAt(from);
+ // The tape follows the replacement from here (it is the session).
+ pardes.tape.adopt(replacement);
pardes.ctlfs.events.notePath(replacement, "restore", from);
- // Which serial each pane and column had, for a script that held them.
- for (replacement.panes, old.panes) |slot, was| if (slot) |pane| if (was != 0) {
- var rec: [32]u8 = undefined;
- pardes.ctlfs.events.notePath(replacement, "restored", std.fmt.bufPrint(&rec, "{d} {d}", .{ was, pane.serial }) catch continue);
- };
- for (old.cols[0..replacement.ncol], 0..) |was, c| if (was != 0) {
- var rec: [32]u8 = undefined;
- pardes.ctlfs.events.notePath(replacement, "restoredcol", std.fmt.bufPrint(&rec, "{d} {d}", .{ was, layout.columnSerial(replacement, c) }) catch continue);
- };
return replacement;
}
-pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8) !*Pardes {
- return initDump(gpa, opts, zon_bytes, null, null);
+pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8) !*Pardes {
+ pardes.tape.startFromEnv();
+ const taped = pardes.tape.enter(null, .{ .init_from_dump = .{ .opts = opts, .bytes = bytes } });
+ const p = (if (std.mem.startsWith(u8, bytes, Handover.carried_magic)) carriedWindow(gpa, opts, bytes) else loadAndRevive(gpa, opts, bytes, null, null)) catch |err| {
+ pardes.tape.leave(null, taped);
+ return err;
+ };
+ pardes.tape.leave(p, taped);
+ return p;
}
-/// The serials a dump's panes and columns had, read as it is restored.
-const OldSerials = struct {
- panes: [MAX_PANES]u32 = @splat(0),
- cols: [MAX_COLS]u32 = @splat(0),
-};
-
-fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previous: ?*const Pardes, old_serials: ?*OldSerials) !*Pardes {
+/// A window of its own for panes a grip carried out of another (Handover):
+/// those panes and nothing else, its settings this process's.
+fn carriedWindow(gpa: std.mem.Allocator, opts: Options, bytes: []const u8) !*Pardes {
const p = try Pardes.create(gpa, opts);
errdefer p.deinit();
+ _ = try Handover.adopt(p, bytes);
+ try reviveSession(p, null, false);
+ return p;
+}
+
+/// An upgraded session's dump, loaded as the session it was (upgrade.zig):
+/// every view kept, its settings the dump's (the startup config is not run
+/// again), and the terminals whose shells run on (`kept`) not revived: the
+/// host gives each its pty back. Untaped: a recording ends at an upgrade.
+pub fn resumeFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, kept: *const [MAX_PANES]bool) !*Pardes {
+ return loadAndRevive(gpa, opts, bytes, null, kept);
+}
+
+/// Where an upgrade leaves its dump: the DumpDir (a relative Restore finds
+/// it there by name), as `pardes-upgrade-<pid>.dump`; never $PARDES_DUMP,
+/// which is a Dump's.
+pub fn upgradePath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 {
+ var dir_buf: [900]u8 = undefined;
+ const dir = directory(&dir_buf, dir_setting) orelse return null;
+ _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {};
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes-upgrade-{d}.dump", .{ dir, std.c.getpid() }, 0) catch null;
+}
+
+fn loadAndRevive(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, previous: ?*const Pardes, kept: ?*const [MAX_PANES]bool) !*Pardes {
+ var notes: std.ArrayList(u8) = .empty;
+ defer notes.deinit(gpa);
+ var on_disk: OnDisk = @splat(false);
+ const p = try loadKnowing(gpa, opts, bytes, &notes, &on_disk);
+ errdefer p.deinit();
+ for (p.panes, on_disk, 0..) |slot, was_on_disk, i| if (slot) |pane| {
+ if (kept) |k| if (k[i] and pane.terminal != null) continue;
+ revivePane(p, i, pane, was_on_disk);
+ };
+ try reviveSession(p, previous, kept != null);
+ // What another build's dump could not give, said where the user looks
+ // (stderr is a tty session's screen).
+ if (notes.items.len > 0) {
+ const first = notes.items[0 .. std.mem.indexOfScalar(u8, notes.items, '\n') orelse notes.items.len];
+ var buf: [320]u8 = undefined;
+ p.setMessage(p.active, std.fmt.bufPrint(&buf, "a dump of another build: {s}", .{first}) catch "a dump of another build: not all of it was read");
+ }
+ return p;
+}
+
+/// A loaded core given to this host (with `revivePane` for each of its
+/// panes): the store and Recent read (a Restore's carried from the session
+/// it replaces) and its ThemeFile asked for again. An upgrade's (`resumed`)
+/// keeps its views, whose clients come back with it, and its settings.
+fn reviveSession(p: *Pardes, previous: ?*const Pardes, resumed: bool) !void {
+ // ponytail: one client loads it, so it is one view, the live one's; a
+ // replica joining (phase 5) takes `load`'s, every view.
+ if (!resumed) views.only(p);
if (previous) |old| {
- p.next_serial = old.next_serial;
- // Columns as panes: a restored one takes a fresh serial, never one
- // a column of the old session had, living or deleted.
- p.next_column_serial = old.next_column_serial;
- p.lsp_seq = old.lsp_seq;
- p.pipe.seq = old.pipe.seq;
+ // Never a serial or a request number the old session gave out.
+ p.next_serial = @max(p.next_serial, old.next_serial);
+ p.next_column_serial = @max(p.next_column_serial, old.next_column_serial);
+ p.lsp_seq = @max(p.lsp_seq, old.lsp_seq);
+ p.pipe.seq = @max(p.pipe.seq, old.pipe.seq);
+ // The host's facts, as this host told them.
p.cell_pixels = old.cell_pixels;
p.row_metrics = old.row_metrics;
p.native_images = old.native_images;
- // The workspace tag's Restore word names the dump it came from.
- if (old.last_dump) |d| p.last_dump = try gpa.dupe(u8, d);
- // Recent goes on across a Restore, the old session's own list.
p.recent = old.recent.clone(p.recentGpa());
- // The same session: its closed panes go on being its own.
p.store = old.store.clone(p.recentGpa());
} else p.loadRecent();
- var parsed = try readZon(gpa, zon_bytes, "load");
- defer parsed.deinit();
- const st = parsed.value;
- p.locations_config = st.locations_config;
- p.settings.tree_context_tag_style = st.tree_context_tag_style;
- applySettings(p, st.settings);
- if (st.incl) |dirs| {
- for (p.incl.items) |dir| p.gpa.free(dir);
- p.incl.clearRetainingCapacity();
- for (dirs) |dir| if (dir.len > 0 and dir[0] == '/' and std.mem.indexOfScalar(u8, dir, 0) == null) {
- const copy = p.gpa.dupe(u8, dir) catch continue;
- p.incl.append(p.gpa, copy) catch p.gpa.free(copy);
- };
+ config.tab_now = p.settings.tab;
+ // A ThemeFile is a request the host answers by reading the file again;
+ // until it has (and for good if it fails) the theme the dump had shows.
+ if (p.theme_file_path.get().len > 0) {
+ var path: [limits.host_path_cap]u8 = undefined;
+ const name = p.theme_file_path.get();
+ @memcpy(path[0..name.len], name);
+ colors.requestThemeFile(p, 0, path[0..name.len]);
}
- // A dump naming a ThemeFile asks the host to load it again: until it
- // has, and for good if it fails, the theme this session showed goes on
- // (a failed ThemeFile changes nothing, a Restore's included), unless
- // the dump names a Theme of its own.
- if (previous) |old| if (p.theme_file_path.get().len > 0) {
- const names_theme = for (st.settings) |line| {
- if (std.mem.startsWith(u8, line, "Theme ")) break true;
- } else false;
- try colors.carryTheme(p, old, !names_theme);
+ for (p.panes) |slot| if (slot) |pane| {
+ pane.fs.unannounced = true;
};
- for (st.mounts) |mount| {
- var already_mounted = false;
- for (p.fs.mounts.items) |existing| {
- if (!std.mem.eql(u8, mount.name, existing.name)) continue;
- if (!std.mem.eql(u8, mount.dial, existing.dial)) return error.MountConflict;
- already_mounted = true;
- break;
- }
- if (!already_mounted) try p.fs.mount(gpa, mount.name, mount.dial);
- }
-
- for (themes, 0..) |t, i| {
- if (std.mem.eql(u8, t.name, st.theme)) p.settings.theme = @intCast(i);
- }
- for (st.panes, 0..) |src, i| {
- if (i >= MAX_PANES) break;
- if (old_serials) |o| o.panes[i] = src.serial;
- const pane = try restorePane(p, i, src);
- pane.vweight = src.vweight;
- pane.collapsed = src.collapsed;
- }
- p.ncol = @min(st.columns.len, MAX_COLS);
- p.col_serial = @splat(0);
- if (st.topbar_custom) |bar| p.global_tag.own = try p.gpa.dupe(u8, bar);
- for (st.columns[0..p.ncol], 0..) |col, c| {
- if (old_serials) |o| o.cols[c] = col.serial;
- if (col.tag) |bar| p.col_tags[c].own = try p.gpa.dupe(u8, bar);
- const scaled = @as(f64, @floatCast(col.weight)) * @as(f64, @floatFromInt(column_weight_unit));
- const bounded = @min(scaled, @as(f64, @floatFromInt(max_column_weight)));
- p.col_weight[c] = @max(1, @as(u64, @intFromFloat(@round(bounded))));
- p.col_n[c] = @min(col.panes.len, MAX_PANES);
- for (col.panes[0..p.col_n[c]], 0..) |pid, k| p.col_panes[c][k] = pid;
- }
- // A dump's pane i is restored into slot i: its owner's serial now.
- for (st.panes[0..@min(st.panes.len, MAX_PANES)], 0..) |src, i| {
- const owner = src.attached_to orelse continue;
- if (owner >= MAX_PANES or owner == i) continue;
- const pane = p.panes[i] orelse continue;
- pane.attached_to = (p.panes[owner] orelse continue).serial;
- }
- p.active = @min(st.active, MAX_PANES - 1);
+ // The dump's screen until this host says its own (a resize): two
+ // reflows would lose where a terminal's view was.
p.sync();
- exec.applyStartupConfig(p);
+ if (!resumed) exec.applyStartupConfig(p);
colors.finishThemeInitialization(p);
p.sync();
p.presentation.enabled = true;
_ = p.takeHaptic(); // see init: a restored session is not a gesture
try p.fs.log.buf.ensureTotalCapacityPrecise(p.gpa, p.fs.log.cap);
ctlfs.events.announce(p);
- return p;
}
-/// Dump pane `src` made a pane again in slot `i`, installed (a fresh
-/// serial) and not yet placed: a Restore's, and a closed pane Panes brings
-/// back (Store.zig).
-pub fn restorePane(p: *Pardes, i: usize, src: Pane) !*pardes.panes.Pane {
- const gpa = p.gpa;
- const pane: *pardes.panes.Pane = switch (src.kind) {
- .terminal => terminal: {
- const t = src.terminal.?;
- // A host that runs shells gets them back: the old history
- // above a new shell in the directory it was in. The web
- // shell and an isolated build only ever replay it.
- // A command pane comes back finished, showing what it said
- // and how it ended: its command is not run again.
- const live = comptime (terminal_panes and platform != .web and !isolated);
- const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0;
- const restored = try pardes.panes.terminal.restore(p, src, revive);
- p.installPane(i, restored);
- try restored.setOwnedCwd(t.cwd);
- if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell);
- if (t.command.len > 0) {
- restored.command = try gpa.dupe(u8, t.command);
- restored.command_done = true;
- restored.command_status = t.status;
- }
- if (revive) p.emitSpawn(i, restored.serial, t.cwd);
- if (t.petscii and pardes.panes.terminal.petscii(restored) == false) pardes.panes.terminal.togglePetscii(restored);
- break :terminal restored;
- },
- .file => file: {
- const restored = try pardes.panes.File.restore(p, i, src);
- // A twin: on the earlier pane's buffer again.
- if (src.file.?.twin_of) |j| if (j < i) pardes.panes.File.relink(p, j, i, src.file.?.dot);
- break :file restored;
- },
- .image => restore_image: {
- const im = src.image.?;
- if (pardes.panes.Pdf.isPath(im.path)) {
- var raw: []u8 = if (im.bytes_b64.len > 0)
- try decodeBytes(gpa, im.bytes_b64)
- else
- &.{};
- errdefer if (raw.len > 0) gpa.free(raw);
- if (comptime pdf_enabled) {
- if (pardes.panes.Pdf.openPane(p, i, im.path, src.scroll + 1, .last) catch null) |restored| {
- if (raw.len > 0) gpa.free(raw);
- raw = &.{};
- // Its fit and tint as they were (PdfFit, PdfTint).
- const pv = &restored.pdf.?;
- if (std.meta.stringToEnum(@TypeOf(pv.fit), im.pdf_fit)) |fit| if (fit != pv.fit) pardes.panes.Pdf.toggleFit(restored);
- if (std.meta.stringToEnum(@TypeOf(pv.tint), im.pdf_tint)) |tint| while (pv.tint != tint) pardes.panes.Pdf.toggleTint(restored);
- restored.cols = @max(1, src.cols);
- restored.rows = @max(1, src.rows);
- break :restore_image restored;
- }
- }
- // If the source path is unavailable, retain its bytes
- // as an ordinary file rather than dropping the pane.
- const path = try gpa.dupe(u8, im.path);
- errdefer gpa.free(path);
- const content = if (raw.len > 0) raw else try gpa.dupe(u8, "");
- raw = &.{};
- errdefer if (content.len > 0) gpa.free(content);
- const history = try pardes.panes.File.History.create(gpa);
- errdefer gpa.destroy(history);
- const restored = try p.newDocPane(i);
- restored.file = .{ .path = path, .content = content, .history = history };
- restored.body.cur_pinned = true;
- restored.cols = @max(1, src.cols);
- restored.rows = @max(1, src.rows);
- p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true, .mode = .baseline_disk } });
- break :restore_image restored;
- }
- break :restore_image try pardes.panes.Image.restore(p, i, src);
- },
+/// A loaded pane given to this host: a terminal a new shell in its old
+/// one's directory under its history, a file watched again (one changed on
+/// disk since comes back as it is now, one unsaved is marked changed), a
+/// PDF opened again.
+fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool) void {
+ if (pane.terminal != null) {
+ // A command pane comes back finished, showing what it said: its
+ // command is not run again. A host that runs shells starts one
+ // under the history in the old one's directory; the web shell and
+ // an isolated build only show it.
+ if (pane.command != null) {
+ pane.command_done = true;
+ return;
+ }
+ if (comptime !(terminal_panes and platform != .web and !isolated)) return;
+ if (pane.cwdSlice().len > effect_path_cap) return;
+ pardes.panes.terminal.reviveShell(pane);
+ p.emitSpawn(id, pane.serial, pane.cwdSlice());
+ return;
+ }
+ if (comptime pdf_enabled) if (pane.pdf != null) {
+ pardes.panes.Pdf.reopen(p, pane) catch |err| {
+ p.reportError(id, "Restore", err);
+ p.removePane(id, null) catch {};
+ };
+ return;
};
- tagline.restoreDumpTail(p, pane, src);
+ const f = if (pane.file) |*file| file else return;
+ if (f.output != null or filesystem.localPath(f.path) == null) return;
+ p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
+ // Its file gone from disk since the dump: its text is nowhere else, so
+ // it is said deleted, and Del, Exit and Restore ask first. One never on
+ // disk (a name not yet saved) comes back as it was.
+ // (A host with no disk of its own, the web's, asks nothing.)
+ if (comptime pardes.hosted) if (was_on_disk and !onDisk(pane)) pardes.panes.File.deleted(p, @intCast(id));
+}
+
+// ---- one pane to and from a dump: the store's, a handover's ----
+
+/// Pane `pane` alone as a dump (`gpa`'s): what it shares with another
+/// pane is its own in it (a directory it follows), and nothing says where
+/// it was. `slim`: without a terminal's history, a file's undo, or a clean
+/// file's text, which is read from its file again (a store's record past
+/// its bound).
+pub fn savePane(gpa: std.mem.Allocator, pane: *pardes.panes.Pane, slim: bool) ![]u8 {
+ // The fields it changes put back after, not the whole pane (88 KB) kept
+ // aside: a store record is made at every close.
+ const cwd = pane.cwd;
+ const attached_to = pane.attached_to;
+ const terminal = pane.terminal;
+ defer {
+ pane.cwd = cwd;
+ pane.attached_to = attached_to;
+ pane.terminal = terminal;
+ }
+ if (cwd == .inherited) {
+ // Read before the union is written (its tag is set first).
+ const dir = pane.cwdSlice();
+ pane.cwd = .{ .owned = @constCast(dir) };
+ }
+ pane.attached_to = null;
+ if (!slim) return walk.save(pardes.panes.Pane, gpa, pane);
+ pane.terminal = null;
+ const f = if (pane.file) |*file| file else return walk.save(pardes.panes.Pane, gpa, pane);
+ const history = f.history;
+ const content = f.content;
+ defer {
+ f.history = history;
+ f.content = content;
+ }
+ var empty: pardes.panes.File.History = .{};
+ f.history = &empty;
+ if (f.output == null and f.revision == f.saved_revision and filesystem.localPath(f.path) != null) f.content = &.{};
+ return walk.save(pardes.panes.Pane, gpa, pane);
+}
+
+/// A pane `savePane` made, installed in free slot `id` with a serial of
+/// this session's and not yet placed, and given to the host as a loaded
+/// session's are (`revive`).
+pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane {
+ var l = try walk.Load(&.{pardes.panes.Pane}).init(p.gpa, bytes);
+ defer l.deinit();
+ l.allocs = .{ .image = p.image_gpa, .pdf = p.pdf_gpa, .terminal = pardes.panes.terminal.emulatorGpa(p.gpa) };
+ const pane = try p.gpa.create(pardes.panes.Pane);
+ errdefer {
+ l.rollback();
+ p.gpa.destroy(pane);
+ }
+ pane.* = try l.get(pardes.panes.Pane);
+ // The slots and serials of the session it was in name nothing here.
+ pane.search_pane = null;
+ pane.search_row = null;
+ pane.command_from = 0;
+ pane.places.from = 0;
+ pane.collapsed = false;
+ pane.prompt_view = p.view;
+ if (pane.file) |*f| if (f.content.len == 0 and (f.saved_len orelse 0) > 0) {
+ // A clean file kept slim: its text is its file's.
+ if (filesystem.read(p, f.path)) |text| {
+ f.content = text;
+ } else |_| {}
+ };
+ try ensureKind(p, pane);
+ p.installPane(id, pane);
+ revivePane(p, id, pane, false);
return pane;
}
-test "a dump keeps the settings that differ from a fresh session's, and a restore applies them" {
+test "a dump keeps the session's settings, and a restore applies them" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
@@ -1092,10 +573,6 @@ test "a dump keeps the settings that differ from a fresh session's, and a restor
try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose off"));
try std.testing.expect(p.executeBuiltinLine(p.active, "JumpScope all"));
try dumpState(p);
- try std.testing.expect(std.mem.indexOf(u8, p.dump_out.?, "\"Placement pardes\"") != null);
- try std.testing.expect(std.mem.indexOf(u8, p.dump_out.?, "\"JumpScope all\"") != null);
- // What is left at its default is not written.
- try std.testing.expect(std.mem.indexOf(u8, p.dump_out.?, "\"BootShell keep\"") == null);
const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?);
defer restored.deinit();
try std.testing.expectEqual(config.Runtime.Placement.pardes, restored.settings.placement);
@@ -1186,3 +663,73 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and
try std.testing.expect(!restored.quit and restored.panes[id] != null);
}
}
+
+test "a loaded terminal's history stays above its banner, the cursor where it was" {
+ if (comptime !pardes.panes.terminal.enabled or isolated) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const term = pardes.panes.terminal;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ term.feedOutput(p, p.panes[0].?, "one\r\ntwo\r\n$ ");
+ const before = term.gridCursor(p.panes[0].?);
+ try dumpState(p);
+ const loaded = try load(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?, null);
+ defer loaded.deinit();
+ try std.testing.expectEqual(before, term.gridCursor(loaded.panes[0].?));
+ const q = try initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?);
+ defer q.deinit();
+ const text = try term.screenTextAlloc(q.panes[0].?, gpa);
+ defer gpa.free(text);
+ try std.testing.expect(std.mem.indexOf(u8, text, "one\ntwo\n") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "two") .? < std.mem.indexOf(u8, text, "restored history").?);
+}
+
+test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" {
+ if (comptime !pardes.panes.terminal.enabled or isolated) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const term = pardes.panes.terminal;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" });
+ defer p.deinit();
+ while (p.nextEffect()) |_| {}
+ term.feedOutput(p, p.panes[0].?, "one\r\n\x1b[?1049h$ vim");
+ try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose on"));
+ _ = p.openView().?;
+ const bytes = try dumpBytes(p);
+ defer gpa.free(bytes);
+ var kept: [MAX_PANES]bool = @splat(false);
+ kept[0] = true;
+ const q = try resumeFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" }, bytes, &kept);
+ defer q.deinit();
+ try std.testing.expectEqual(@as(usize, 2), views.count(q));
+ try std.testing.expect(q.settings.verbose);
+ // The program's own screen, no banner, and no shell asked for.
+ try std.testing.expectEqual(term.gridCursor(p.panes[0].?), term.gridCursor(q.panes[0].?));
+ try std.testing.expect(q.panes[0].?.terminal.?.vt.screens.active_key == .alternate);
+ while (q.nextEffect()) |e| try std.testing.expect(e != .spawn);
+ // Not kept, the same terminal is a new shell's under its history.
+ kept[0] = false;
+ const r = try resumeFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, bytes, &kept);
+ defer r.deinit();
+ try std.testing.expect(r.panes[0].?.terminal.?.vt.screens.active_key == .primary);
+}
+
+test "a session read by name, field by field as another build reads it, is the same session" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("one\ntwo\n");
+ _ = ctlfs.pane.spliceBody(p, pane, 0, 0, "unsaved ").?;
+ try std.testing.expect(p.executeBuiltinLine(p.active, "Zerox"));
+ const bytes = try dumpBytes(p);
+ defer gpa.free(bytes);
+ const q = try Pardes.create(gpa, p.opts);
+ defer q.deinit();
+ var l = try SessionLoad.init(gpa, bytes);
+ defer l.deinit();
+ try std.testing.expect(l.same);
+ l.same = false;
+ try l.into(Pardes, q);
+ try std.testing.expectEqualStrings("", l.notes.items);
+ try std.testing.expectEqual(walk.digest(Pardes, p), walk.digest(Pardes, q));
+}