const std = @import("std"); const builtin = @import("builtin"); const limits = @import("memory.zig").limits; const pardes = @import("pardes.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 pdf_enabled = pardes.pdf_enabled; const platform = pardes.platform; const isolated = pardes.isolated; const terminal_panes = pardes.terminal_panes; 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; /// 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-.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 { if (std.c.getenv("PARDES_DUMP")) |p| return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; 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 {}; 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(); var stamp: [32]u8 = undefined; const base = std.fmt.bufPrint(&stamp, "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 return null; return uniqueIn(buf, dir, base); } /// `/.dump`, or `-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}.dump", .{ dir, base }, 0) else 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; } return null; } test "two dumps in one second get names of their own" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var dir_buf: [900]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; 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.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. fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { if (builtin.os.tag == .freestanding) return null; return std.c.getenv(name); } /// Where dumps go 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; // No libc on the web or the board: there a relative one is from `/`. const cwd: []const u8 = if (comptime !pardes.hosted) "/" else if (std.fs.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.fs.path.resolvePosix(fba.allocator(), &.{ cwd, raw }) catch return null; return std.fmt.bufPrint(buf, "{s}", .{resolved}) catch null; } test "a dump makes every directory missing on the way to its DumpDir" { if (std.c.getenv("PARDES_DUMP") != null) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var at: [4096]u8 = undefined; const base = at[0..try tmp.dir.realPath(std.testing.io, &at)]; var setting: [4200]u8 = undefined; const dir = try std.fmt.bufPrint(&setting, "{s}/fresh/.local/share/pardes", .{base}); var out: [1024:0]u8 = undefined; const path = outPath(&out, dir).?; try std.testing.expect(std.mem.startsWith(u8, path, dir)); var made = try tmp.dir.openDir(std.testing.io, "fresh/.local/share/pardes", .{}); made.close(std.testing.io); } 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.fs.path.isAbsolute(rel.?) and std.mem.endsWith(u8, rel.?, "/rel")); } /// 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 (src/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 (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. /// 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; 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 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); } /// The session as a dump, gpa-owned. pub fn dumpBytes(p: *Pardes) ![]u8 { return dumpWith(p, null); } /// 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); } /// `dumpJoin`'s: a terminal dumps its size, not its emulator. pub var slim_terminals = 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.Dumped = others; try d.put([]const views.Dumped, &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: []u8) !void { 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; }; 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 { 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, .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); } 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.Dumped) catch |err| switch (err) { // A dump made before views were in it. error.EndOfDump => &.{}, else => return err, }; try views.undumped(p, others); for (others) |o| gpa.free(o.panes); gpa.free(others); l.shared.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.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 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 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; }; 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, 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; 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 (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; } /// 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-.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, ¬es, &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| { // 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; p.recent = old.recent.clone(p.recentGpa()); p.store = old.store.clone(p.recentGpa()); } else p.loadRecent(); 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]); } 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); 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); } /// 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; }; 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 = ∅ 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 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.active, "Placement pardes")); try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose off")); try std.testing.expect(p.executeBuiltinLine(p.active, "JumpScope all")); try dumpState(p); 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); try std.testing.expect(!restored.settings.verbose); try std.testing.expectEqual(config.Runtime.JumpScope.all, restored.settings.jump_scope); } 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.ncol < MAX_COLS) { layout.compute(p); var widest: usize = 0; for (0..p.ncol) |c| if (p.col_w[c] > p.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.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.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 ([_][]const u8{ "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 (std.mem.eql(u8, word, "Del") or std.mem.eql(u8, word, "get")) ctlfs.Node.of(restored.panes[id].?.serial, .ctl) else @backingInt(ctlfs.TopFile.ctl); const line = if (std.mem.eql(u8, word, "Restore")) try std.fmt.bufPrint(&restore_line, "Restore {s}/d.zon\n", .{dir}) else if (std.mem.eql(u8, word, "Exit")) "Exit\n" else if (std.mem.eql(u8, word, "Del")) "Del\n" else "get\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 (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)); }