diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/dump.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip | |
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/dump.zig')
| -rw-r--r-- | core/dump.zig | 1255 |
1 files changed, 1255 insertions, 0 deletions
diff --git a/core/dump.zig b/core/dump.zig new file mode 100644 index 00000000..a4fc0f8d --- /dev/null +++ b/core/dump.zig @@ -0,0 +1,1255 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const limits = @import("memory.zig").limits; +const pardes = @import("root.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 colors = @import("colors.zig"); +const config = @import("config.zig"); +const platform = pardes.platform; +const isolated = pardes.isolated; +const MAX_PANES = pardes.MAX_PANES; +const MAX_COLS = pardes.MAX_COLS; +const effect_path_cap = pardes.effect_path_cap; +const Options = pardes.Options; +const Pardes = pardes.Pardes; +const views = pardes.views; +const Kind = @import("Kind.zig"); + +/// A Dump's label in the state file (Db.zig): `pardes-<date>-<time>`, UTC +/// (another in the same second is `-2` and on there), in `buf`. +pub fn label(buf: []u8) []const u8 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.REALTIME, &ts); + const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; + const yd = es.getEpochDay().calculateYearDay(); + const md = yd.calculateMonthDay(); + const ds = es.getDaySeconds(); + return std.fmt.bufPrint(buf, "pardes-{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{ + yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, + ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), + }) catch "pardes-dump"; +} + +/// The host's environment. +fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { + return std.c.getenv(name); +} + +/// Where the state file is (Db.zig) and relative Restore names are looked +/// up: the `DumpDir` setting when set (a leading `~/` is the home +/// directory), else the default. +pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { + if (dir_setting.len == 0) return defaultDirectory(buf); + var joined: [4096]u8 = undefined; + // `~/x`, else a relative one from the directory pardes started in: the + // same place however it was written, and shown so. + const raw = pardes.filesystem.expandHome(dir_setting, &joined); + var fba_buf: [4096]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&fba_buf); + var cwd_buf: [1024]u8 = undefined; + const cwd: []const u8 = if (std.Io.Dir.path.isAbsolute(raw)) "/" else if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]const u8, @ptrCast(c))) else "/"; + const resolved = std.Io.Dir.path.resolvePosix(fba.allocator(), &.{ cwd, raw }) catch return null; + return std.fmt.bufPrint(buf, "{s}", .{resolved}) catch null; +} + +/// The standard dump directory, without creating it or generating a filename. +pub fn defaultDirectory(buf: []u8) ?[]const u8 { + if (hostEnv("XDG_DATA_HOME")) |x| + return std.fmt.bufPrint(buf, "{s}/pardes", .{std.mem.span(x)}) catch null; + if (hostEnv("HOME")) |h| + return std.fmt.bufPrint(buf, "{s}/.local/share/pardes", .{std.mem.span(h)}) catch null; + return null; +} + +/// 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 (core/replica.zig). +pub var terminal_gpa: ?std.mem.Allocator = null; + +// ---- a whole session to and from a dump (acme keeps this in rows.c) ---- +// +// A dump 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 (the emulator's snapshot), registers, +// places, tags, layout and settings. It crosses builds: its fields are +// matched by name. It is an image (Db.zig): a database in memory the walk +// writes by name (walk.Put), which the state file keeps under a label, +// `Dump export` and a handover write as a file, and `-l` and Restore read. +// The byte dump before it (walk.Dump) is still a replica's join, a closed +// pane's, and for one release (0.24) what an old `.dump` file is read as. +// +// 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, kinds' panes opened. + +/// 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, core/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 panes' shares of the views not live +/// (views.zig: the panes hold the live one's). +const Session = walk.Dump(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8, []const views.Shares }); +const SessionLoad = walk.Load(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8, []const views.Shares }); +const OnDisk = [MAX_PANES]bool; + +fn onDisk(pane: *const pardes.panes.Pane) bool { + 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 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); +} + +/// A session's end leaves what it was in the state file under the usual +/// label (Pardes.endSession): its panes with their files, directories and +/// places, slim: not a clean file's text (its file's), an undo history or +/// a terminal's screen (the session's), so History brings a day's panes +/// back by name. A session of shells alone leaves nothing. +pub fn dumpExit(p: *Pardes) !void { + var worth = false; + for (p.panes) |slot| if (slot) |pane| { + if (pane.addon != null or (pane.file != null and pane.file.?.output == null)) worth = true; + }; + if (!worth) return; + // The state file's, whatever the last `Dump export` named. + if (p.dump_export) |old| p.gpa.free(old); + p.dump_export = null; + slim_terminals = true; + defer slim_terminals = false; + var slims: [MAX_PANES]Slim = undefined; + var n: usize = 0; + defer for (slims[0..n]) |*s| s.put(); + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| { + slims[n] = Slim.take(f); + n += 1; + }; + try dumpState(p); +} + +/// A file kept slim in a dump (`dumpExit`, a closed pane's past its bound, +/// Store.zig): without its undo, and a clean file on disk without its +/// text, which `revivePane` reads from its file again. +const Slim = struct { + f: *pardes.panes.File.State, + history: *pardes.panes.File.History, + content: []u8, + + var empty: pardes.panes.File.History = .{}; + + fn take(f: *pardes.panes.File.State) Slim { + const s: Slim = .{ .f = f, .history = f.history, .content = f.content }; + f.history = ∅ + if (f.output == null and f.revision == f.saved_revision and filesystem.localPath(f.path) != null) f.content = &.{}; + return s; + } + + fn put(s: *Slim) void { + s.f.history = s.history; + s.f.content = s.content; + } +}; + +/// A Dump: into the state file, or (`Dump export`) a file of its own at +/// `to` (`~` the home directory). +pub fn dumpTo(p: *Pardes, to: ?[]const u8) !void { + if (p.dump_export) |old| p.gpa.free(old); + p.dump_export = null; + if (to) |path| { + var home_buf: [4096]u8 = undefined; + p.dump_export = try p.gpa.dupe(u8, filesystem.expandHome(path, &home_buf)); + } + try dumpState(p); +} + +/// The file a Restore of `name` reads, its whole path in `out`: one named +/// with a `/` or `~/` (as it resolves, else as typed: the read says why), +/// or a bare word that names a file in the DumpDir or the directory pardes +/// runs in; null for one that names none: a label of the state file's. +pub fn restoreFile(name: []const u8, dir_setting: []const u8, out: *[4096]u8) ?[]const u8 { + const path = filesystem.restorePath(name, dir_setting, out); + if (std.mem.indexOfScalar(u8, name, '/') != null or std.mem.startsWith(u8, name, "~")) return path; + return if (std.Io.Dir.path.isAbsolute(path)) path else null; +} + +/// What a Restore of `name` reads, `gpa`'s: the file it names (an image, +/// or an old byte dump), else the state file's dump of that label. +pub fn restoreBytes(p: *Pardes, gpa: std.mem.Allocator, name: []const u8) ![]u8 { + var buf: [4096]u8 = undefined; + if (restoreFile(name, p.settings.dump_dir.get(), &buf)) |path| return filesystem.readFile(gpa, path); + const got = p.db.getDump(p, gpa, name) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump; + return got orelse error.FileNotFound; +} + +/// The session as a dump's image, gpa-owned (the host puts it in the state +/// file under a label of its own). +pub fn dumpBytes(p: *Pardes) ![]u8 { + return image(p, "dump"); +} + +/// The session as a byte dump (walk.Dump), gpa-owned: what a replica's join +/// streams, its blobs in place. +pub fn byteDump(p: *Pardes) ![]u8 { + return dumpWith(p, null); +} + +/// The session as the image of one dump labelled `name` (Db.zig), its +/// roots by name: the core, its 9P mounts, which of its panes' files were +/// on disk, its theme's name and the views not live (see `Session`). +pub fn image(p: *Pardes, name: []const u8) ![]u8 { + const gpa = p.gpa; + var buf: std.Io.Writer.Allocating = .init(gpa); + defer buf.deinit(); + var db = try walk.Mem.init(std.Io.failing, .{ .buffer = &buf, .file_id = 0 }); + var w: walk.Put = .{ .gpa = gpa }; + defer w.deinit(); + const mounts: []const filesystem.Mount = p.fs.mounts.items; + var on_disk: OnDisk = @splat(false); + var panes: u64 = 0; + // What the panes show, a word each (History's row): a file's or a + // kind's path, a terminal's directory. + var names: std.Io.Writer.Allocating = .init(gpa); + defer names.deinit(); + for (p.panes, &on_disk) |slot, *on| if (slot) |pane| { + on.* = onDisk(pane); + panes += 1; + const shown: []const u8 = if (pane.addon) |k| k.path else if (pane.file) |f| (if (f.output == null) f.path else "") else pane.cwdSlice(); + if (shown.len == 0 or names.written().len + shown.len > 4096) continue; + if (names.written().len > 0) try names.writer.writeByte(' '); + try names.writer.writeAll(shown); + }; + const theme: []const u8 = colors.themes[@min(p.settings.theme, colors.themes.len - 1)].name; + const others = try views.dumped(p, gpa); + defer { + for (others) |o| gpa.free(o.panes); + gpa.free(others); + } + const kept: []const views.Shares = others; + try db.runContext(struct { + w: *walk.Put, + p: *Pardes, + mounts: *const []const filesystem.Mount, + on_disk: *const OnDisk, + theme: *const []const u8, + others: *const []const views.Shares, + pub fn run(ctx: @This(), cursor: *walk.Mem.Cursor(.read_write)) !void { + const root = try walk.Mem.HashMap(.read_write).init(cursor.*); + try ctx.w.member(root, "core", Pardes, ctx.p); + try ctx.w.member(root, "mounts", []const filesystem.Mount, ctx.mounts); + try ctx.w.member(root, "on_disk", OnDisk, ctx.on_disk); + try ctx.w.member(root, "theme", []const u8, ctx.theme); + try ctx.w.member(root, "shares", []const views.Shares, ctx.others); + } + }{ .w = &w, .p = p, .mounts = &mounts, .on_disk = &on_disk, .theme = &theme, .others = &kept }); + return pardes.Db.image(gpa, name, buf.written(), w.blobs.items, panes, names.written()); +} + +/// A dump for a screen-state replica's join (core/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; + join_files = true; + defer join_files = false; + return dumpWith(p, deferred); +} + +/// `dumpJoin`'s and `dumpExit`'s: a terminal dumps its size, not its emulator. +pub var slim_terminals = false; +/// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file). +var join_files = false; + +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.Shares = others; + try d.put([]const views.Shares, &kept); + return d.finish(); +} + +/// Whether `bytes` are a dump a Restore could read, saying nothing: a +/// Restore asks before it warns about unsaved text or replaces anything. +/// Why not is left in `why`, ended by a 0. +pub fn check(gpa: std.mem.Allocator, bytes: []const u8, why: *[256]u8) !void { + if (pardes.Db.isImage(bytes)) { + const r = pardes.Db.Read.open(gpa, bytes, null) catch |err| { + const said = std.fmt.bufPrint(why[0 .. why.len - 1], "{s}", .{switch (err) { + error.NoDump => "it holds no dump", + error.OutOfMemory => "out of memory", + else => "it is no dump of pardes's", + }}) catch why[0 .. why.len - 1]; // cut at 255 + why[said.len] = 0; + return err; + }; + r.close(); + return; + } + 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[0 .. why.len - 1]; // cut at 255 + why[said.len] = 0; + return err; + }; + l.deinit(); +} + +/// 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); +} + +/// `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 { + if (pardes.Db.isImage(bytes)) return loadImage(gpa, opts, bytes, notes, on_disk); + const p = try Pardes.create(gpa, opts); + var l = SessionLoad.init(gpa, bytes) catch |err| { + p.deinit(); + return err; + }; + 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); + } + l.allocs = .{ .image = p.image_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); + } + 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; + } + p.fs.mount(gpa, m.name, m.dial) catch |err| l.note("mount {s}: {t}", .{ m.name, err }); + } + 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); + } + // 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.Shares) catch |err| switch (err) { + // A dump made before views were in it. + error.EndOfDump => &.{}, + else => return err, + }; + views.undumped(p, others); + for (others) |o| gpa.free(o.panes); + gpa.free(others); + l.shared.shrinkRetainingCapacity(at); + return p; +} + +/// `loadKnowing` of an image (Db.zig): its roots read by name (walk.Get), +/// as the byte dump's are read in order. +fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*std.ArrayList(u8), on_disk: ?*OnDisk) !*Pardes { + const r = pardes.Db.Read.open(gpa, bytes, null) catch |err| return if (err == error.OutOfMemory) err else error.BadDump; + defer r.close(); + const root = r.root(); + const core_at = (try walk.Get.member(root, "core")) orelse return error.BadDump; + const p = try Pardes.create(gpa, opts); + var l: walk.Get = .init(gpa); + defer l.deinit(); + l.blobs = r.blobs() catch null; + // 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); + } + l.allocs = .{ .image = p.image_gpa, .terminal = terminal_gpa }; + try l.into(Pardes, core_at, p); + if (try walk.Get.member(core_at, "views") == null) { + // From before `Pardes.views`: the live view's share is the core's + // own fields, by the same names, and its index `view`. + var old: struct { view: u8 = 0 } = .{}; + try l.into(@TypeOf(old), core_at, &old); + p.live = if (old.view < views.max) old.view else 0; + if (p.live != 0) std.mem.swap(?Pardes.View, &p.views[0], &p.views[p.live]); + try l.into(Pardes.View, core_at, p.view()); + } + const read = l.made.items.len; + const mounts: []const filesystem.Mount = if (try walk.Get.member(root, "mounts")) |c| try l.get([]const filesystem.Mount, c) else &.{}; + defer { + for (mounts) |m| { + gpa.free(m.name); + gpa.free(m.dial); + } + gpa.free(mounts); + // Freed here: no rollback of them. + l.made.shrinkRetainingCapacity(read); + } + const was: OnDisk = if (try walk.Get.member(root, "on_disk")) |c| try l.get(OnDisk, c) else @splat(false); + if (on_disk) |out| out.* = was; + const theme: []const u8 = if (try walk.Get.member(root, "theme")) |c| try l.get([]const u8, c) else ""; + defer gpa.free(theme); + 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; + 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; + } + p.fs.mount(gpa, m.name, m.dial) catch |err| l.note("mount {s}: {t}", .{ m.name, err }); + } + if (l.notes.items.len > 0) { + dropMissing(p); + for (p.panes) |slot| if (slot) |pane| try ensureKind(p, pane); + if (notes) |n| try n.appendSlice(gpa, l.notes.items); + } + // 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.made.items.len; + if (try walk.Get.member(root, "shares")) |c| { + const others = try l.get([]const views.Shares, c); + views.undumped(p, others); + for (others) |o| gpa.free(o.panes); + gpa.free(others); + } else { + // A dump from before `Pardes.views`: the live view's share was + // the core's own fields, each other view's in `views`. + const others: []const views.OldDumped = if (try walk.Get.member(root, "views")) |c| try l.get([]const views.OldDumped, c) else &.{}; + defer { + for (others) |o| gpa.free(o.panes); + gpa.free(others); + } + try views.undumpedOld(p, others, gpa); + } + l.made.shrinkRetainingCapacity(at); + return p; +} + +/// 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.addon != null or pane.pdf != null) return; + if (pardes.tape.authorityOnly("open a terminal")) return error.OutOfMemory; + pane.terminal = try pardes.Term.open(pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); +} + +/// 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 { + const v = p.view(); + for (0..p.view().ncol) |c| { + var n: usize = 0; + for (v.cols[c].panes[0..p.view().cols[c].n]) |id| if (id < MAX_PANES and p.panes[id] != null) { + v.cols[c].panes[n] = id; + n += 1; + }; + v.cols[c].n = n; + } + if (v.active >= MAX_PANES or p.panes[v.active] == null) v.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, 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.view().screen_w; + opts.rows = p.view().screen_h; + 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); + return replacement; +} + +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 (Handover.carries(gpa, bytes)) 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; +} + +/// 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); +} + +fn loadAndRevive(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, previous: ?*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, ¬es, &on_disk); + errdefer p.deinit(); + // Its kinds are this process's, not the dump's: the session's it + // replaces, or what the scan found (a dump of another session's). + p.kinds = if (previous) |old| old.kinds else .started(opts.addons); + 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 tui 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.view().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, with its state file) 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: ?*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| { + // 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_ask.seq = @max(p.lsp_ask.seq, old.lsp_ask.seq); + p.pipe.seq = @max(p.pipe.seq, old.pipe.seq); + // The host's facts, as this host told them. + p.view().cell_pixels = old.view().cell_pixels; + p.view().row_metrics = old.view().row_metrics; + p.view().frontend.native_images = old.view().frontend.native_images; + // Its panes close here, each noted where it was, as at its end. + for (old.panes) |slot| if (slot) |pane| old.noteClosed(pane); + p.recent = old.recent.clone(p.recentGpa()); + p.store = old.store.clone(p.recentGpa()); + p.db = old.db; + old.db = .{}; + } + 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]); + } + // So is a Font: the face is the host's, and a new process (an Upgrade's, + // a start from a dump) has only its built-in one until it is asked. + if (p.settings.font.requested_path.get().len > 0) { + p.settings.font.pending = true; + p.font_request_taken = false; + } + for (p.panes) |slot| if (slot) |pane| { + pane.fs.unannounced = true; + }; + // The dump's screen until this host says its own (a resize): two + // reflows would lose where a terminal's view was. + p.sync(); + if (!resumed) exec.applyStartupConfig(p); + // After the startup config, whose DumpDir says where the state file is. + if (previous == null) p.loadRecent(); + colors.finishThemeInitialization(p); + p.sync(); + _ = 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); +} + +/// 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 +/// kind's pane opened again (a PDF a build before the pdf addon dumped, as +/// the addon's). +fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool) void { + if (pane.addon) |slot| { + if (slot.path.len > 0 and filesystem.localPath(slot.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + return reviveSlot(p, id, slot); + } + 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; an isolated build + // only shows it. + if (pane.command != null) { + pane.command_done = true; + return; + } + if (comptime isolated) return; + if (pane.cwdSlice().len > effect_path_cap) return; + // Its shell not there, made ready for a new one: what the old + // shell was, ran and said is gone with it (the REPL it ran, the + // Term+ word naming it), and the pane waits for the new one like + // any new terminal (a line queued for the old one goes to it). + pardes.Term.revive(pane.terminal.?); + 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; + p.emitSpawn(id, pane.serial, pane.cwdSlice()); + return; + } + if (pane.pdf) |old| return revivePdf(p, id, pane, old); + const f = if (pane.file) |*file| file else return; + if (f.output != null or filesystem.localPath(f.path) == null) return; + // A clean file kept slim (`Slim`): its text is its file's. One gone + // since is said deleted below, its text nowhere now. + if (f.content.len == 0 and (f.saved_len orelse 0) > 0) { + if (filesystem.read(p, f.path)) |text| { + f.content = text; + } else |_| {} + } + 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. + 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 closed pane's dump +/// past its bound, Store.zig). +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); + var slimmed = Slim.take(f); + defer slimmed.put(); + 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, .terminal = pardes.panes.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.live; + try ensureKind(p, pane); + p.installPane(id, pane); + revivePane(p, id, pane, false); + return pane; +} + +// ---- a pane of a kind (Kind.Slot) ---- + +/// What a dump keeps of a pane of a kind: the kind, its path, its place, +/// the art bytes, its words' last values, whether its kind was here, and +/// the kind's own record when it has one. +const SlotRecord = struct { + name: []const u8 = "", + version: u32 = 0, + gen: u32 = 0, + path: []const u8 = "", + where: []const u8 = "", + art: @import("surface.zig").Placement.Art = .{}, + record: ?[]const u8 = null, + values: []const u8 = "", + live: bool = false, + /// What decides its next calls (Kind.step): a replica joining keeps + /// them, its pane of a kind with no code there calling where the + /// authority's kind does. + next_tick: u64 = 0, + views: [views.max]u64 = @splat(0), + focused: bool = false, + /// The jobs whose answers it dropped (api.cancel): a replica's drop them too. + cancelled: [4]u32 = @splat(0), + /// Its last job's token (Kind.Slot.tokens): a client's next is the session's. + tokens: u32 = 0, + /// Its tick's prefix: a replica's tag laid out as the session's. + prefix: []const u8 = "", + /// A placeholder's why (its file not here). + refused: []const u8 = "", + /// What a step reads of it that its kind's open made (Kind.reopen) or + /// a call set: its tag's default words and what it has selected. A + /// replica's load opens no kind; without them its tag wrapped another + /// way and its yank took nothing. + tail: []const u8 = "", + selection: []const u8 = "", + /// A plain kind's block's hash (Kind.Slot.state). + state: u64 = 0, + /// A client's join (`dumpJoin`): a plain kind's file, as the disk has + /// it now, which the client opens the pane from (plainHere). + file: ?[]const u8 = null, +}; + +pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { + var place: [32]u8 = undefined; + var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .gen = s.gen, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live, .next_tick = s.next_tick, .views = s.views, .focused = s.focused, .cancelled = s.cancelled, .tokens = s.tokens, .prefix = s.prefix.slice(), .refused = s.refused.slice(), .tail = s.tail.slice(), .selection = s.selection, .state = s.state }; + var owned: ?[]u8 = null; + defer if (owned) |o| s.gpa.free(o); + if (s.ops != null) { + r.where = Kind.where(@constCast(s), &place); + // A plain kind's record is its block, as it is (Kind.Slot.plain). + owned = if (s.plain) |b| (if (b.len > 0) try s.gpa.dupe(u8, b) else null) else try slotRecord(@constCast(s)); + r.record = owned; + } + // Paid only at a client's join: the session keeps no file's bytes. + var file: ?[]u8 = null; + defer if (file) |f| s.gpa.free(f); + if (join_files and s.plain != null and s.ops != null) if (filesystem.localPath(s.path)) |path| { + const z = try s.gpa.dupeSentinel(u8, path, 0); + defer s.gpa.free(z); + file = filesystem.readHost(s.gpa, z, pardes.memory.limits.max_file_bytes) catch null; + r.file = file; + }; + const bytes = try walk.save(SlotRecord, gpa, &r); + defer gpa.free(bytes); + try w.writeAll(bytes); +} + +/// The kind's record of a slot's state (`s.gpa`'s), or null for none: at +/// most PA_RECORD_MAX bytes. +pub fn slotRecord(s: *Kind.Slot) !?[]u8 { + const f = (s.ops orelse return null).dump orelse return null; + const buf = try s.gpa.alloc(u8, Kind.c.PA_RECORD_MAX); + const n = Kind.dumpCall(s, f, buf); + if (n == 0 or n > buf.len) { + s.gpa.free(buf); + return null; + } + return s.gpa.realloc(buf, n) catch buf[0..n]; +} + +/// The pane back from its record, a placeholder holding it until its +/// kind opens it (`revivePane`; a replica's core with no code for it keeps +/// it so). +pub fn slotRead(out: *Kind.Slot, gpa: std.mem.Allocator, bytes: []const u8) !void { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const r = try walk.load(SlotRecord, arena.allocator(), bytes, null); + out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .gen = r.gen, .art = r.art, .live = r.live, .next_tick = r.next_tick, .views = r.views, .focused = r.focused, .cancelled = r.cancelled, .tokens = r.tokens, .state = r.state }; + errdefer out.free(); + @memcpy(out.name[0..@min(15, r.name.len)], r.name[0..@min(15, r.name.len)]); + out.path = try gpa.dupe(u8, r.path); + out.where_text.set(r.where); + out.prefix.set(r.prefix); + out.refused.set(r.refused); + out.tail.set(r.tail); + out.values.set(r.values); + out.selection = try gpa.dupe(u8, r.selection); + if (r.record) |rec| out.record = try gpa.dupe(u8, rec); + if (r.file) |f| out.file = try gpa.dupe(u8, f); +} + +pub fn slotFree(s: *Kind.Slot, gpa: std.mem.Allocator) void { + _ = gpa; + s.free(); +} + +/// A loaded pane of a kind opened by its kind from its file as a Look +/// reads it, then given its record, if this core has the kind; else, or +/// refused (its file not here, its record not taken), a placeholder saying +/// what it waits for, its record kept. One with no record reopens at its +/// place with its words. A placeholder comes back at the next Look or +/// watch of its path, or the load of its kind. +pub fn reviveSlot(p: *Pardes, id: usize, s: *Kind.Slot) void { + const k = p.kinds.byName(s.nameOf()) orelse { + s.live = false; + return; + }; + s.ops = p.kinds.ops[k]; + s.gen = p.kinds.kinds[k].gen; + // A replica has no code to read it for: the authority's outcome is taped. + // The authority's code may not be loaded yet: its open loads it. + const bytes: ?[]u8 = if ((s.ops != null or !pardes.tape.replaying()) and s.path.len > 0) filesystem.read(p, s.path) catch null else null; + defer if (bytes) |b| p.gpa.free(b); + const kept = .{ s.next_tick, s.views, s.focused }; + if (!Kind.reopen(p, id, s, bytes)) { + s.ops = null; + s.live = false; + } else { + s.version = p.kinds.kinds[k].version; + if (s.ops == null) { + // A replica's pane of a kind with no code there is the + // authority's as it is: it ticks when that one does, not + // because it was loaded (a kind opened here ticks to lay + // itself out). + s.next_tick, s.views, s.focused = kept; + } + } +} + +/// A replica client's pane of a plain kind it has the code of (`ops`), +/// loaded as the session dumped it: a slot of its core's own memory (the +/// rollback epoch), opened here, its block the record's bytes, its state +/// the session's. The loaded one (the C heap's) is freed. +pub fn plainHere(p: *Pardes, id: usize, old: *Kind.Slot, ops: *const Kind.Ops) !*Kind.Slot { + const s = try p.gpa.create(Kind.Slot); + s.* = .{ .ops = ops, .live = true, .gpa = p.gpa, .arena = .init(p.gpa), .name = old.name, .version = old.version, .gen = old.gen, .art = old.art, .where_text = old.where_text, .values = old.values, .prefix = old.prefix, .tail = old.tail, .opened = old.opened, .cancelled = old.cancelled, .tokens = old.tokens }; + errdefer { + s.free(); + p.gpa.destroy(s); + } + s.path = try p.gpa.dupe(u8, old.path); + s.selection = try p.gpa.dupe(u8, old.selection); + // (and its place: the open's own `where` is of a block not yet the session's) + const kept = .{ old.next_tick, old.views, old.focused, old.state, old.where_text }; + if (!Kind.reopen(p, id, s, old.file)) return error.KindRefused; + // Its block the session's, byte for byte (its record), never through + // the kind's load, which may tidy it. + const block = s.plain orelse return error.KindRefused; + const record = old.record orelse return error.KindRefused; + if (block.len != record.len) return error.KindRefused; + @memcpy(block, record); + s.next_tick, s.views, s.focused, s.state, s.where_text = kept; + const gpa = old.gpa; + old.free(); + gpa.destroy(old); + return s; +} + +/// A PDF pane of a dump from before the pdf addon: a pane of the addon's +/// kind `pdf` on its file, at its page, its fit and tint given again as +/// its words; a placeholder until the addon is loaded. +fn revivePdf(p: *Pardes, id: usize, pane: *pardes.panes.Pane, old: *pardes.panes.Pane.LegacyPdf) void { + defer { + p.image_gpa.free(old.path); + p.image_gpa.destroy(old); + pane.pdf = null; + } + const s = p.image_gpa.create(Kind.Slot) catch return; + s.* = .{ .gpa = p.image_gpa, .arena = .init(p.image_gpa), .version = 1, .live = true }; + @memcpy(s.name[0..3], "pdf"); + s.path = p.image_gpa.dupe(u8, old.path) catch { + s.free(); + return p.image_gpa.destroy(s); + }; + _ = s.where_text.print("{d}", .{old.page + 1}); + _ = s.values.print("PdfFit {t}\nPdfTint {t}\n", .{ old.fit, old.tint }); + pane.addon = s; + reviveSlot(p, id, s); +} + +test "a DumpDir reads back absolute, however it was written" { + var buf: [4096]u8 = undefined; + try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp/dumps/").?); + try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp//x/../dumps").?); + const rel = directory(&buf, "rel/"); + try std.testing.expect(std.Io.Dir.path.isAbsolute(rel.?) and std.mem.endsWith(u8, rel.?, "/rel")); +} + +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(); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Verbose off")); + try std.testing.expect(p.executeBuiltinLine(p.view().active, "Wrap off")); + try dumpState(p); + const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + try std.testing.expect(!restored.settings.verbose); + try std.testing.expect(!restored.settings.wrap); +} + +test "a session with every column it may hold dumps and restores them all" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 1200, .rows = 24 }); + defer p.deinit(); + while (p.view().ncol < MAX_COLS) { + layout.compute(p); + var widest: usize = 0; + for (0..p.view().ncol) |c| if (p.view().col_w[c] > p.view().col_w[widest]) { + widest = c; + }; + _ = layout.insertColumn(p, widest, false) orelse return error.NoColumn; + } + try dumpState(p); + const restored = try initFromDump(gpa, .{ .tty_only = true, .cols = 1200, .rows = 24 }, p.dump_out.?); + defer restored.deinit(); + try std.testing.expectEqual(@as(usize, MAX_COLS), restored.view().ncol); +} + +test "a restored session's column and workspace tags take more than one selection, and its 9P files have a time" { + const th = @import("ninep/testing.zig"); + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + try dumpState(p); + const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + try std.testing.expect(restored.view().col_tags[0].reserveSels()); + try std.testing.expect(restored.global_tag.reserveSels()); + try std.testing.expect(restored.fs.started != 0); + const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @backingInt(pardes.ctlfs.TopFile.index) }); + try std.testing.expect(stat.reply.attr.mtime != 0); +} + +test "a restored pane keeps its dot, as acme's dump keeps a window's" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("one two three\nfour\n"); + ctlfs.pane.setDot(pane, .{ .q0 = 4, .q1 = 7 }); + try dumpState(p); + const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + const again = for (restored.panes) |slot| { + if (slot) |candidate| if (candidate.file != null) break candidate; + } else return error.FileLost; + const dot = ctlfs.pane.dotOf(again); + try std.testing.expectEqual(@as(u32, 4), dot.q0); + try std.testing.expectEqual(@as(u32, 7), dot.q1); +} + +test "a pane restored with unsaved text is asked about by Exit, Restore, Del and get" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + _ = ctlfs.pane.spliceBody(p, pane, 0, 0, "unsaved ").?; + try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); + try dumpState(p); + // Restore reads its dump before it warns: one it can read. + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "d.zon", .data = p.dump_out.? }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var restore_line: [4200]u8 = undefined; + for ([_]enum { Exit, Restore, Del, get }{ .Exit, .Restore, .Del, .get }) |word| { + const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + const id = for (restored.panes, 0..) |slot, i| { + if (slot) |candidate| if (candidate.file != null and candidate.file.?.output == null) break i; + } else return error.FileLost; + const th = @import("ninep/testing.zig"); + const node = if (word == .Del or word == .get) + ctlfs.Node.of(restored.panes[id].?.serial, .ctl) + else + @backingInt(ctlfs.TopFile.ctl); + const line = switch (word) { + .Restore => try std.fmt.bufPrint(&restore_line, "Restore {s}/d.zon\n", .{dir}), + inline else => |w| @tagName(w) ++ "\n", + }; + const answer = th.wr(restored, node, line); + try std.testing.expectEqual(ctlfs.Status.err, answer.reply.status); + try std.testing.expect(std.mem.indexOf(u8, answer.reply.ename, "Modified") != null); + 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 (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator + if (comptime 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()) |_| {} + p.panes[0].?.feedOutput(p, "one\r\ntwo\r\n$ "); + const before = pardes.Term.grid(p.panes[0].?.terminal); + try dumpState(p); + const loaded = try load(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?, null); + defer loaded.deinit(); + const after = pardes.Term.grid(loaded.panes[0].?.terminal); + try std.testing.expectEqual([2]u16{ before.cursor_x, before.cursor_y }, [2]u16{ after.cursor_x, after.cursor_y }); + const q = try initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + defer q.deinit(); + const text = try pardes.Term.scrollback(q.panes[0].?.terminal, 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 (pardes.Term.ops == null) return error.SkipZigTest; // a shell, dumped and loaded + if (comptime isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + p.panes[0].?.feedOutput(p, "one\r\n\x1b[?1049h$ vim"); + try std.testing.expect(p.executeBuiltinLine(p.view().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. + const was = pardes.Term.grid(p.panes[0].?.terminal); + const is = pardes.Term.grid(q.panes[0].?.terminal); + try std.testing.expectEqual([2]u16{ was.cursor_x, was.cursor_y }, [2]u16{ is.cursor_x, is.cursor_y }); + try std.testing.expect(pardes.Term.modes(q.panes[0].?.terminal).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(!pardes.Term.modes(r.panes[0].?.terminal).alternate); +} + +test "a loaded session asks its host for its font again: a new process has only its built-in face" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + // The startup config's Font, taken and loaded by the window it ran in. + try std.testing.expect(p.settings.requestFont("/fonts/Go-Mono.ttf", "Go-Mono", 1800)); + try std.testing.expectEqualStrings("/fonts/Go-Mono.ttf", p.takeFontRequest().?); + try std.testing.expect(p.acknowledgeFont("GoMono", 1800, .pixels)); + try std.testing.expect(p.takeFontRequest() == null); + const bytes = try dumpBytes(p); + defer gpa.free(bytes); + // An Upgrade's process, which runs no startup config, and a start from + // the dump: each asks for the face again, at the size the request had. + var kept: [MAX_PANES]bool = @splat(false); + const q = try resumeFromDump(gpa, .{ .tty_only = true }, bytes, &kept); + defer q.deinit(); + try std.testing.expectEqualStrings("/fonts/Go-Mono.ttf", q.takeFontRequest().?); + try std.testing.expectEqual(@as(u16, 1800), q.settings.font.requested_size_hundredths); + const r = try initFromDump(gpa, .{ .tty_only = true }, bytes); + defer r.deinit(); + try std.testing.expectEqualStrings("/fonts/Go-Mono.ttf", r.takeFontRequest().?); +} + +test "a session's image, read by name as every load reads it, is the same session, and dumps to the same bytes again" { + 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.view().active, "Zerox")); + const bytes = try dumpBytes(p); + defer gpa.free(bytes); + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(gpa); + const q = try load(gpa, p.opts, bytes, ¬es); + defer q.deinit(); + try std.testing.expectEqualStrings("", notes.items); + try std.testing.expectEqual(walk.digest(Pardes, p), walk.digest(Pardes, q)); + const again = try dumpBytes(q); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, bytes, again); +} + +test "a session's byte dump 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.view().active, "Zerox")); + const bytes = try byteDump(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)); +} + +test "an old dump's file, a byte dump, is read by -l and by a Restore of its path, for one release" { + const gpa = std.testing.allocator; + const th = @import("ninep/testing.zig"); + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("kept in a .dump\n"); + const bytes = try byteDump(p); + defer gpa.free(bytes); + try std.testing.expect(std.mem.startsWith(u8, bytes, "pardes-dump")); + // -l: the file read whole, and loaded. + const q = try initFromDump(gpa, .{ .tty_only = true }, bytes); + defer q.deinit(); + const text = for (q.panes) |slot| { + if (slot) |pane| if (pane.file) |f| if (f.output == null) break f.content; + } else return error.FileLost; + try std.testing.expectEqualStrings("kept in a .dump\n", text); + // Restore of its path, as a word in a tag or a script gives it. + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "old.dump", .data = bytes }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var line: [4200]u8 = undefined; + const answer = th.wr(q, @backingInt(ctlfs.TopFile.ctl), try std.fmt.bufPrint(&line, "Restore {s}/old.dump\n", .{dir})); + try std.testing.expectEqual(ctlfs.Status.ok, answer.reply.status); + const name = q.takeRestore().?; + const again = try restoreBytes(q, gpa, name); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, bytes, again); +} + +test "restored syntax context caches are rebuilt rather than loaded with the core allocator" { + const gpa = std.testing.allocator; + var syntax_gpa: std.heap.DebugAllocator(.{}) = .init; + defer std.testing.expect(syntax_gpa.deinit() == .ok) catch @panic("syntax allocator leaked"); + const opts: Pardes.Options = .{ .tty_only = true, .tree_sitter_allocator = syntax_gpa.allocator() }; + const p = try Pardes.init(gpa, opts); + defer p.deinit(); + const pane = try p.setTestFile("fn example() void {}\n"); + const f = &pane.file.?; + const declarations = try p.tree_sitter_gpa.alloc(pardes.syntax.ContextDeclaration, 1); + @memset(std.mem.sliceAsBytes(declarations), 0); + f.context.replace(p.tree_sitter_gpa, declarations, f.revision); + // Older builds persisted these two fields; the schema reader must skip them too. + const OldFile = struct { + path: []const u8, + content: []const u8, + history: *pardes.panes.File.History, + context_declarations: []pardes.syntax.ContextDeclaration, + context_revision: ?u32, + }; + const old_bytes = try walk.save(OldFile, gpa, &.{ + .path = f.path, + .content = f.content, + .history = f.history, + .context_declarations = f.context.declarations, + .context_revision = f.context.revision, + }); + defer gpa.free(old_bytes); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const old = try walk.load(pardes.panes.File.State, arena.allocator(), old_bytes, null); + try std.testing.expectEqual(@as(usize, 0), old.context.declarations.len); + try std.testing.expectEqual(@as(?u32, null), old.context.revision); + const bytes = try dumpBytes(p); + defer gpa.free(bytes); + const q = try load(gpa, opts, bytes, null); + defer q.deinit(); + for (q.panes) |slot| if (slot) |restored| if (restored.file) |file| { + try std.testing.expectEqual(@as(usize, 0), file.context.declarations.len); + try std.testing.expectEqual(@as(?u32, null), file.context.revision); + }; +} + +test "optional GPU addon reload generation survives a replica dump" { + const gpa = std.testing.allocator; + var original: Kind.Slot = .{ .gpa = gpa, .arena = .init(gpa), .gen = 7, .live = true }; + defer original.free(); + var bytes: std.Io.Writer.Allocating = .init(gpa); + defer bytes.deinit(); + try slotWrite(&original, gpa, &bytes.writer); + var restored: Kind.Slot = undefined; + try slotRead(&restored, gpa, bytes.written()); + defer restored.free(); + try std.testing.expectEqual(original.gen, restored.gen); + try std.testing.expectEqual(walk.digest(Kind.Slot, &original), walk.digest(Kind.Slot, &restored)); +} |
