diff options
108 files changed, 2514 insertions, 703 deletions
diff --git a/abi/pardes.h b/abi/pardes.h index 65ca5c60..ca65b8f3 100644 --- a/abi/pardes.h +++ b/abi/pardes.h @@ -191,7 +191,7 @@ typedef enum { PARDES_HAPTIC_LOOK = 2, } pardes_haptic_e; -// ---------------------------------------------------------------- runtime +// ---------------------------------------------------------------- callbacks // What the host lends the core. Three callbacks, because everything else the // core wants done it already does itself: it owns the ptys, and it opens URLs @@ -214,7 +214,7 @@ typedef struct { // pardes_paste, which may be synchronous inside this call. Main thread, // inside pardes_tick. void (*read_clipboard)(void *userdata); -} pardes_runtime_s; +} pardes_callbacks_s; // ---------------------------------------------------------------- lifecycle @@ -223,7 +223,7 @@ typedef struct { // core defers each shell's greeting until it has seen one), and the first // forkpty takes its winsize straight off the core — boot at 80x24 and the // shell draws its first prompt to a width the window never had. -int pardes_init(const pardes_runtime_s *runtime, uint16_t cols, uint16_t rows); +int pardes_init(const pardes_callbacks_s *runtime, uint16_t cols, uint16_t rows); void pardes_deinit(void); // Drain pty output into the core and perform the effects it queued. Call after diff --git a/abi/term.zig b/abi/term.zig index c437f62f..37519309 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -231,6 +231,9 @@ pub const ImagesAt = struct { now_ms: u64, cell_w: u32, cell_h: u32, + /// Its images as glyph art even where pixels could be drawn (the + /// pane's Petscii). + petscii: bool = false, }; /// What a predicted echo reads of a cell: its codepoint, whether the shell @@ -286,8 +289,6 @@ pub const Applied = struct { seq: u32, extra: []const u8 }; pub const Parts = struct { reply: []const u8 = "", reply_dropped: u32 = 0, - mouse_cell: ?Coordinate = null, - petscii: bool = false, /// The view's top row, counted from the top of the history. view: usize = 0, phase: Prompt.Phase = .none, @@ -343,6 +344,11 @@ pub const Ops = struct { snapshot: *const fn (s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) anyerror!void, /// `snapshot`'s bytes and `parts` back into a new terminal. load: *const fn (gpa: std.mem.Allocator, snapshot: []const u8, parts: *const Parts) anyerror!*State, + /// Its emulator made again from its own snapshot where it is (a join: + /// every side does it); the snapshot's hash. + reload: *const fn (s: *State) anyerror!u64, + /// Its program's kitty images by direct data alone (a replica's). + direct: *const fn (s: *State) void, // ---- output and view ---- /// One read of its program's output (`Told` says where the tracked @@ -360,8 +366,8 @@ pub const Ops = struct { // ---- input ---- key: *const fn (s: *State, k: plain.Key, out: *std.Io.Writer) error{WriteFailed}!void, - mouse: *const fn (s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, - wheel: *const fn (s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, + mouse: *const fn (s: *State, last: *?Parts.Coordinate, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, + wheel: *const fn (s: *State, last: *?Parts.Coordinate, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, paste: *const fn (s: ?*const State, text: []u8) [3][]const u8, modes: *const fn (s: ?*const State) Modes, promptMoves: *const fn (s: *State, row: i32, col: i32) ?Moves, @@ -403,8 +409,6 @@ pub const Ops = struct { /// what it keeps to draw them is its own allocator's), and their /// placeholder cells blanked in `frame` (`frame_cols` wide). images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void, - petscii: *const fn (s: ?*const State) ?bool, - togglePetscii: *const fn (s: *State) void, hasImages: *const fn (s: ?*const State) bool, // ---- its replicas ---- diff --git a/abi/wire.zig b/abi/wire.zig index b2d32033..1f7d02d2 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -7,7 +7,8 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("core"); -const config = @import("pardes_config"); +const config = @import("pardes_options"); +const build_info = @import("build_info"); /// 23: a pane of a kind's frame names its rasters by key, their pixels /// crossing before it as strips of 4 MiB at most over the rows it shows @@ -61,18 +62,21 @@ const family = switch (config.platform) { /// their options and dependencies; -Dstamp-commit stamps one. pub const semantics: u64 = blk: { @setEvalBranchQuota(1_000_000); + // The grammar set as the four words it was hashed as when it was four + // options (highlighting, zig, minimal, full), so the hash stays. + const g = config.grammars; // The two long ones (the dependencies, 2.5 KB, and the tape's shape, // 11 KB) joined on, not formatted: formatting them at comptime was 5 % // of a compile of the core. break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n", .{ - version, config.version, config.commit orelse "unstamped", - family, config.syntax_highlighting, config.syntax_zig_grammar, - config.syntax_minimal_grammars, config.syntax_full_grammars, config.workspace_tag, - config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), + version, build_info.version, build_info.commit orelse "unstamped", + family, g != .disabled, g != .disabled, + g == .minimal or g == .full, g == .full, config.workspace_tag, + config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), }, - ) ++ config.deps ++ "\n" ++ pardes.tape.shape); + ) ++ build_info.deps ++ "\n" ++ pardes.tape.shape); }; /// EndOfStream: the message ends early; WriteFailed: no room for it. @@ -142,9 +142,8 @@ pub fn build(b: *std.Build) void { const shell_cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, - .tracy = tracy != null, + .tracy = tracy, .workspace_tag = workspace_tag, - .prebuilt_shaders = prebuilt_shaders, .embed_sources = embed_sources, .commit = if (stamp_commit) core.gitCommit(b) else null, .change = if (stamp_commit) core.jjChange(b) else null, @@ -156,8 +155,6 @@ pub fn build(b: *std.Build) void { .target = target, .optimize = optimize, .c_optimize = c_optimize, - .tree_sitter_grammars = tree_sitter_grammars, - .tracy = tracy, .shell_cfg = shell_cfg, .platform = platform, .also_gui = also_gui, @@ -169,7 +166,6 @@ pub fn build(b: *std.Build) void { .pdf_scroll_bench_step = pdf_scroll_bench_step, }); const parts = a.parts; - const opts = a.opts; // Off Linux, whose memfd Addon.zig's loader needs, every core has the // addons compiled in. const compiled_in = target.result.os.tag != .linux; @@ -177,28 +173,28 @@ pub fn build(b: *std.Build) void { // its own flat C ABI instead of runtime/main.zig. Tracy's client and BSD // libutil go to the shell (and Tracy's to the core) alone, as before // core.module. - const root_set = core.module(b, parts, .{ .root = if (platform == .macos) "runtime/macos.zig" else "runtime/main.zig", .config = opts, .builtin_addons = compiled_in, .tracy = true, .util = true }); + const root_set = core.module(b, parts, .{ .root = if (platform == .macos) "runtime/macos.zig" else "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true, .util = true }); const root_mod = root_set.root; // hxdiff's headless core and pardes-isolate are the primary shell's // configuration compiled two more ways, not two more frontends. - const core_cfg: core.Core = .{ .root = "core/root.zig", .config = opts, .builtin_addons = compiled_in, .tracy = true }; + const core_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true }; const core_set = core.module(b, parts, core_cfg); const core_module = core_set.root; // The core without the terminal module (docs/next-terminal.md, Phase 1): // what core-test is compiled from. No ghostty-vt, wuffs, zstbi or C++; // a shell boot is a scratch pane, a test that needs a terminal skips, // and shell-test runs them all with one. - const lean_cfg: core.Core = .{ .root = "core/root.zig", .config = opts, .builtin_addons = compiled_in, .terminal = false }; + const lean_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .terminal = false }; const core_lean = core.module(b, parts, lean_cfg); - const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "runtime/main.zig", .config = opts, .builtin_addons = compiled_in, .isolated = true }).root else null; + const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .isolated = true }).root else null; // `zig build static`'s: the addons compiled in (Addon.zig). Linked // statically on musl alone, as glibc links only dynamically; the gui's // is dynamic (SDL and the GPU need the display's libraries) with the // addons in it all the same. const static_linkage: ?std.builtin.LinkMode = if (target.result.isMuslLibC()) .static else null; - const static_set: ?core.Modules = if ((platform == .tui and static_linkage != null) or platform == .gui) core.module(b, parts, .{ .root = "runtime/main.zig", .config = opts, .builtin_addons = true }) else null; + const static_set: ?core.Modules = if ((platform == .tui and static_linkage != null) or platform == .gui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = platform, .builtin_addons = true }) else null; const static_mod: ?*std.Build.Module = if (static_set) |s| s.root else null; - const gui_set: ?core.Modules = if (also_gui) core.module(b, parts, .{ .root = "runtime/main.zig", .config = a.gui_opts.?, .builtin_addons = compiled_in }) else null; + const gui_set: ?core.Modules = if (also_gui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = .gui, .builtin_addons = compiled_in }) else null; const gui_mod: ?*std.Build.Module = if (gui_set) |s| s.root else null; if (a.pdf.lib) |lib| tools.pdfBenches(b, target, optimize, core_module, lib, pdf_pointer_bench_step, pdf_scroll_bench_step); @@ -320,8 +316,6 @@ pub fn build(b: *std.Build) void { .shell_cfg = shell_cfg, .target = target, .test_filters = test_filters, - .tracy = tracy, - .tree_sitter_grammars = tree_sitter_grammars, .unit_profile = unit_profile, }); tests.add(b, .{ diff --git a/build/core.zig b/build/core.zig index 974d5c7e..4e4a748b 100644 --- a/build/core.zig +++ b/build/core.zig @@ -5,7 +5,7 @@ const grammar_manifest = @import("../core/grammar_manifest.zig"); const addons = @import("addons.zig"); const patches = @import("patches.zig"); /// The package manifest, imported UNTYPED on purpose — see the `version` -/// option in `shellOptions` for why that word is load-bearing. +/// option in `buildInfo` for why that word is load-bearing. const zon = @import("../build.zig.zon"); /// Releases are numbered 0.N; the zon holds "0.N.0" because it must be semver, /// and what a user sees drops that ".0". @@ -60,11 +60,11 @@ pub fn command(b: *std.Build, argv: []const []const u8) ?[]const u8 { pub const ShellConfig = struct { tree_sitter_grammars: TreeSitterGrammars, - tracy: bool = false, + /// -Dtracy's checkout, whose client a core that asks compiles in. + tracy: ?[]const u8 = null, /// null = "the platform's own default": the macOS shell hands the row to /// its native menu bar, every other shell keeps the acme topbar. workspace_tag: ?bool = null, - prebuilt_shaders: bool = false, embed_sources: bool = false, commit: ?[]const u8 = null, /// The jj change git HEAD is in, and when this configure ran: the @@ -76,24 +76,34 @@ pub const ShellConfig = struct { lib: bool = false, }; -pub fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options { +/// `pardes_options`: what a module set varies at compile time, one module +/// a configuration, which `module` makes and the set's modules share. +pub fn options(b: *std.Build, cfg: ShellConfig, c: Core, pdf: bool) *std.Build.Step.Options { const o = b.addOptions(); - o.addOption(Platform, "platform", platform); - o.addOption(bool, "syntax_highlighting", cfg.tree_sitter_grammars != .disabled); - o.addOption(bool, "syntax_zig_grammar", cfg.tree_sitter_grammars != .disabled); - o.addOption(bool, "syntax_minimal_grammars", cfg.tree_sitter_grammars == .minimal or cfg.tree_sitter_grammars == .full); - o.addOption(bool, "syntax_full_grammars", cfg.tree_sitter_grammars == .full); - o.addOption(bool, "enable_tracy", cfg.tracy); - o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); + o.addOption(Platform, "platform", c.platform); + o.addOption(TreeSitterGrammars, "grammars", cfg.tree_sitter_grammars); + o.addOption(bool, "terminal", c.terminal); + o.addOption(bool, "isolated", c.isolated); + o.addOption(bool, "builtin_addons", c.builtin_addons); + // ...the pdf one only when it is built (-Dpdf=false leaves it out). + o.addOption(bool, "builtin_pdf", c.builtin_addons and pdf); + o.addOption(bool, "enable_tracy", cfg.tracy != null); + o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (c.platform != .macos)); o.addOption(bool, "embed_sources", cfg.embed_sources); + o.addOption(bool, "lib", cfg.lib); + return o; +} + +/// `build_info`: the version, and the commit, change and time a stamped +/// build was made from (see `stamp_commit`, read at configure time), and +/// every dependency's hash. +pub fn buildInfo(b: *std.Build, cfg: ShellConfig) *std.Build.Step.Options { + const o = b.addOptions(); o.addOption([]const u8, "version", display_version); - // ...and the commit it was built from, when there is one and the build - // is stamped at all (see `stamp_commit`). Read at configure time. o.addOption(?[]const u8, "commit", cfg.commit); o.addOption(?[]const u8, "change", cfg.change); o.addOption(?[]const u8, "built", cfg.built); o.addOption([]const u8, "deps", deps_text); - o.addOption(bool, "lib", cfg.lib); return o; } @@ -240,16 +250,16 @@ pub fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.Resolved /// cell's width for j and k's goal column. vaxis: *std.Build.Module, }) *std.Build.Module { - const options: std.Build.Module.CreateOptions = .{ + const create: std.Build.Module.CreateOptions = .{ .target = target, .optimize = optimize, .root_source_file = b.path("core/lib_editor.zig"), .link_libc = true, }; - const m = if (name) |n| b.addModule(n, options) else b.createModule(options); + const m = if (name) |n| b.addModule(n, create) else b.createModule(create); var lib_cfg = cfg; lib_cfg.lib = true; - m.addOptions("pardes_config", shellOptions(b, lib_cfg, .tui)); + m.addOptions("pardes_options", options(b, lib_cfg, .{ .root = "core/lib_editor.zig", .platform = .tui, .terminal = false }, false)); m.addImport("plain", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("abi/plain.zig") })); m.addImport("generated_themes", d.themes); d.ts.wire(m); @@ -265,8 +275,10 @@ pub const Parts = struct { target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, cloud9: *std.Build.Module, - /// -Dtracy's checkout, whose client a core that asks compiles in. - tracy: ?[]const u8, + /// The build's options (-Dtracy's checkout, -Dembed-sources...). + cfg: ShellConfig, + /// `build_info`, the same for every set. + info: *std.Build.Step.Options, zstd: *std.Build.Step.Compile, /// The addons, for a core that has them compiled in (Addon.zig); the /// pdf one only when it is built (-Dpdf=false leaves it out). @@ -284,16 +296,6 @@ pub const Parts = struct { uucode: *std.Build.Module, xitdb: *std.Build.Module, doc_typ: *std.Build.Step.Options, - /// -Dembed-sources: the core embeds its sources for /src. - embed_sources: bool, - /// One options module for each value of `terminal`, `isolated` and - /// `on`, shared by every core. - term_on: *std.Build.Step.Options, - term_off: *std.Build.Step.Options, - iso_on: *std.Build.Step.Options, - iso_off: *std.Build.Step.Options, - builtin_on: *std.Build.Step.Options, - builtin_off: *std.Build.Step.Options, }; /// Which core: its root and the few ways the products differ. @@ -302,9 +304,8 @@ pub const Core = struct { /// library), core/root.zig for the core, runtime/root.zig for the /// runtime, or a core file whose tests run on the core's imports. root: []const u8, - /// The shell's options (`pardes_config`): this build's, or the window's - /// in the bare build. - config: *std.Build.Step.Options, + /// This build's, or the window's in the bare build. + platform: Platform, /// The terminal module; without it (core-test) a shell boot is a scratch pane. terminal: bool = true, /// pardes-isolate's: no host but the terminal. @@ -339,7 +340,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { // forkpty: in libc proper on glibc>=2.34 and darwin; the BSDs keep it in libutil if (c.util and (p.target.result.os.tag == .freebsd or p.target.result.os.tag == .netbsd or p.target.result.os.tag == .openbsd)) m.linkSystemLibrary("util", .{}); - if (c.tracy) if (p.tracy) |tracy_path| { + if (c.tracy) if (p.cfg.tracy) |tracy_path| { m.addIncludePath(.{ .cwd_relative = tracy_path }); m.addCSourceFile(.{ .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) }, @@ -359,7 +360,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { for (p.ts.libs.items) |lib| m.linkLibrary(lib); // The /src tree's files that live outside the core's directory // (fs.zig embeds them under the names they had there). - if (p.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig", "dev/host_io.zig" }) |f| + if (p.cfg.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig", "dev/host_io.zig" }) |f| m.addAnonymousImport(f, .{ .root_source_file = b.path(f) }); const runtime = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("runtime/root.zig"), .link_libc = true }); const dev = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("dev/root.zig"), .link_libc = true }); @@ -367,18 +368,15 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { const root = if (!in_runtime) m else if (std.mem.eql(u8, c.root, "runtime/root.zig")) runtime else b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true }); // Each options module once, so that the modules share it: a file is in // one module of a compilation. - const term_options = (if (c.terminal) p.term_on else p.term_off).createModule(); const ts_queries = if (p.ts.queries) |q| q.createModule() else null; const doc_typ = p.doc_typ.createModule(); - const pardes_config = c.config.createModule(); - const pardes_isolation = (if (c.isolated) p.iso_on else p.iso_off).createModule(); - const builtin_addons = (if (c.builtin_addons) p.builtin_on else p.builtin_off).createModule(); + const pardes_options = options(b, p.cfg, c, p.pdf != null).createModule(); + const build_info = p.info.createModule(); for ([_]*std.Build.Module{ m, dev, runtime, wire, root }) |x| { x.addImport("cloud9", p.cloud9); if (c.builtin_addons) if (p.pdf) |pdf| x.addImport("pdf_addon", pdf); if (c.builtin_addons) x.addImport("image_addon", p.image); if (c.terminal) x.addImport("term", p.term); - x.addImport("term_options", term_options); x.addImport("plain", p.plain); x.addImport("pardes_addon", p.kind); x.addImport("generated_themes", p.themes); @@ -391,9 +389,8 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { x.addImport("xitdb", p.xitdb); // config.zig's test checks the words and keys docs/typ names exist. x.addImport("doc_typ", doc_typ); - x.addImport("pardes_config", pardes_config); - x.addImport("pardes_isolation", pardes_isolation); - x.addImport("builtin_addons", builtin_addons); + x.addImport("pardes_options", pardes_options); + x.addImport("build_info", build_info); x.addImport("core", m); x.addImport("dev", dev); x.addImport("runtime", runtime); @@ -402,13 +399,9 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { return .{ .root = root, .core = m, .dev = dev, .runtime = runtime, .wire = wire }; } -/// What `assemble` makes besides the parts: the shells' options, the -/// addons, and the terminal's pieces the tests and harnesses name. +/// What `assemble` makes besides the parts: the addons, and the terminal's pieces the tests and harnesses name. pub const Assembly = struct { parts: Parts, - /// The shell's options (`pardes_config`), and the window's in the bare build. - opts: *std.Build.Step.Options, - gui_opts: ?*std.Build.Step.Options, /// What an addon in Zig imports (abi/addon.zig). addon_mod: *std.Build.Module, pdf: addons.Pdf, @@ -421,16 +414,14 @@ pub const Assembly = struct { ghostty_simd: bool, }; -/// Every core's parts, the shells' options and the addons, made once and -/// in this order (the configuration numbers what it generates by it): the -/// one-round lazy fetch, tree-sitter and the themes, the patched packages, -/// zstd, the terminal, and the options modules the cores choose between. +/// Every core's parts and the addons, made once and in this order (the +/// configuration numbers what it generates by it): the one-round lazy +/// fetch, tree-sitter and the themes, the patched packages, zstd, the +/// terminal. pub fn assemble(b: *std.Build, c: struct { target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, c_optimize: std.lang.Optimize, - tree_sitter_grammars: TreeSitterGrammars, - tracy: ?[]const u8, shell_cfg: ShellConfig, platform: Platform, also_gui: bool, @@ -455,7 +446,7 @@ pub fn assemble(b: *std.Build, c: struct { // nothing else. pardes takes these whatever it builds: the missing ones // are asked for here in one round, the grammars with them, where each // `b.dependency` below would end the configure to fetch its own alone. - const ts = treeSitter(b, io, target, c_optimize, c.tree_sitter_grammars); + const ts = treeSitter(b, io, target, c_optimize, c.shell_cfg.tree_sitter_grammars); inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| { // A dependency by path (none of these today) has no hash and is always there. const dep = @field(zon.dependencies, name); @@ -468,9 +459,6 @@ pub fn assemble(b: *std.Build, c: struct { const themes_mod = generatedThemes(b, io, target, optimize); - const opts = shellOptions(b, c.shell_cfg, c.platform); - const gui_opts: ?*std.Build.Step.Options = if (c.also_gui) shellOptions(b, c.shell_cfg, .gui) else null; - const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize }); const zstbi_mod = zstbi_dep.module("root"); // vaxis, ghostty, mvzr and zstbi are patched as they are fetched @@ -602,28 +590,13 @@ pub fn assemble(b: *std.Build, c: struct { if (ghostty_vt_for_tests) |x| term_mod.addImport("ghostty-vt", x); if (wuffs_mod) |x| term_mod.addImport("wuffs", x); term_mod.addImport("zstbi", zstbi_mod); - - // One options module for each value a core chooses (`module`). - const term_on = b.addOptions(); - term_on.addOption(bool, "terminal", true); - const term_off = b.addOptions(); - term_off.addOption(bool, "terminal", false); - const iso_off = b.addOptions(); - iso_off.addOption(bool, "isolated", false); - const iso_on = b.addOptions(); - iso_on.addOption(bool, "isolated", true); - const builtin_off = b.addOptions(); - builtin_off.addOption(bool, "on", false); - const builtin_on = b.addOptions(); - builtin_on.addOption(bool, "on", true); - // ...the pdf one only when it is built (-Dpdf=false leaves it out). - builtin_on.addOption(bool, "pdf", pdf_built.lib != null); return .{ .parts = .{ .target = target, .optimize = optimize, .cloud9 = cloud9, - .tracy = c.tracy, + .cfg = c.shell_cfg, + .info = buildInfo(b, c.shell_cfg), .zstd = zstd, .image = image_addon.root_module, .pdf = pdf_built.module, @@ -638,16 +611,7 @@ pub fn assemble(b: *std.Build, c: struct { .uucode = uucode_mod, .xitdb = xitdb_mod, .doc_typ = c.doc_typ, - .embed_sources = c.shell_cfg.embed_sources, - .term_on = term_on, - .term_off = term_off, - .iso_on = iso_on, - .iso_off = iso_off, - .builtin_on = builtin_on, - .builtin_off = builtin_off, }, - .opts = opts, - .gui_opts = gui_opts, .addon_mod = addon_mod, .pdf = pdf_built, .image_addon = image_addon, diff --git a/build/library.zig b/build/library.zig index ebfd8596..8a23debc 100644 --- a/build/library.zig +++ b/build/library.zig @@ -24,7 +24,7 @@ pub fn build(b: *std.Build) void { }); // A library's options: its grammars, nothing stamped, no window. const cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars }; - mod.addOptions("pardes_config", core.shellOptions(b, cfg, .tui)); + mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false)); const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars); const themes = core.generatedThemes(b, io, target, optimize); mod.addImport("generated_themes", themes); diff --git a/build/patches.zig b/build/patches.zig index d5ac7372..3d956d26 100644 --- a/build/patches.zig +++ b/build/patches.zig @@ -175,8 +175,14 @@ pub fn vaxis(b: *std.Build, patch: *std.Build.Step.Compile, vaxis_dep: *std.Buil /// zstbi with stb_image and its writer cut out: of it only its resize is /// left, for a terminal PNG's downscale (build/core.zig, "One PNG /// decoder"). zstbi.deinit still resets the reader's and the writer's flip -/// flags, and Image.deinit frees the resize's output. +/// flags, and Image.deinit frees the resize's output. And no fused +/// multiply-add in the resize: clang contracts `a * b + c` where the CPU +/// has one (aarch64 always does), which rounds once, so a PNG downscaled +/// on an Apple silicon Mac came out pixels apart from Linux's, and the same +/// bytes must give the same terminal on every machine a client runs on +/// (docs/zstbi-fp-contract.md). const zstbi_cut = [_]Edit{ + .{ .old = "#include <stdlib.h>\n", .new = "#include <stdlib.h>\n#pragma STDC FP_CONTRACT OFF\n" }, .{ .old = "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", .new = "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" }, .{ .old = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", .new = "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" }, }; @@ -245,11 +251,41 @@ const ghostty_kitty = [_]Edit{ }, }; +/// ghostty's terminal page (src/terminal/page.zig): a page's size is +/// rounded to 4 KiB on every target, not to the OS page (4 KiB on Linux +/// and FreeBSD, 16 KiB on an Apple aarch64 Mac). The same bytes must give +/// the same emulator on every machine a client runs on, and the rounding +/// decides how many rows a page holds and how much room its style and link +/// tables grow to, so how many history rows the 16 MiB scrollback keeps: +/// a Mac had fewer than Linux once it was full, which the digest saw +/// (docs/ghostty-page-size.md). On Linux and FreeBSD this changes nothing; +/// a Mac maps whole 16 KiB pages under a length that is not one, up to +/// 12 KiB a page left unused, and ghostty's assertions that a page's +/// length is a whole number of OS pages (page.zig, mem.zig) ask for 4 KiB. +const ghostty_page = [_]Edit{ + .{ + .old = " const total_size = alignForward(usize, meta_end, std.heap.page_size_min);\n", + .new = " const total_size = alignForward(usize, meta_end, 4 << 10); // pardes (build/patches.zig)\n", + }, + .{ + .old = " assert(l.total_size % std.heap.page_size_min == 0);\n", + .new = " assert(l.total_size % (4 << 10) == 0); // pardes (build/patches.zig)\n", + }, +}; +const ghostty_mem = [_]Edit{.{ + .old = " assert(memory.len % std.heap.page_size_min == 0);\n", + .new = " assert(memory.len % (4 << 10) == 0); // pardes (build/patches.zig): a page's size\n", + .count = 2, +}}; + pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, vt: *std.Build.Module) void { const files = b.addWriteFiles(); // The rest of src as it is; fonts are the app's, not the library's. - _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", ".ttf", ".otf" } }); + // ("terminal/page.zig" leaves terminal/snapshot/page.zig in.) + _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", "terminal/page.zig", "terminal/mem.zig", ".ttf", ".otf" } }); _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/kitty/graphics_image.zig", &ghostty_kitty, "ghostty_kitty.zig"), "terminal/kitty/graphics_image.zig"); + _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/page.zig", &ghostty_page, null), "terminal/page.zig"); + _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/mem.zig", &ghostty_mem, null), "terminal/mem.zig"); vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig"); } diff --git a/build/tests.zig b/build/tests.zig index 50d3dd02..741eb24a 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -84,7 +84,7 @@ pub fn add(b: *std.Build, c: struct { if (c.ghostty_vt_for_tests) |x| pane_tests.root_module.addImport("ghostty-vt", x); // The core's own options module, not another over the same file: // a file is in one module of a compilation. - pane_tests.root_module.addImport("pardes_config", c.core_module.import_table.get("pardes_config").?); + pane_tests.root_module.addImport("pardes_options", c.core_module.import_table.get("pardes_options").?); const test_addons = b.addOptions(); test_addons.addOptionPath("image", c.image_addon.getEmittedBin()); test_addons.addOption(bool, "has_pdf", c.pdf_addon != null); @@ -129,7 +129,7 @@ pub fn add(b: *std.Build, c: struct { session_module.addOptions("session_options", session_options); // The build's options alone (platform), never the core: a test of a // window's word knows which build it runs in. - const behaviour_tests = units.root(b, "test/behaviour.zig", true, &.{ .{ .name = "session", .module = session_module }, .{ .name = "pardes_config", .module = c.core_module.import_table.get("pardes_config").? } }); + const behaviour_tests = units.root(b, "test/behaviour.zig", true, &.{ .{ .name = "session", .module = session_module }, .{ .name = "pardes_options", .module = c.core_module.import_table.get("pardes_options").? } }); const behaviour_test_step = b.step("behaviour-test", "run the behavioural tests, through the 9P tree alone (test/behaviour/), and the T1 runner (-- [--seed N]... | --monkey <seeds> | --replay)"); _ = units.add(b, behaviour_tests, behaviour_test_step); // An addon's own test: `--addon-test` over the fake (the template) diff --git a/build/tools.zig b/build/tools.zig index 1343fef9..62e9817a 100644 --- a/build/tools.zig +++ b/build/tools.zig @@ -2,7 +2,6 @@ const std = @import("std"); const builtin = @import("builtin"); const Platform = @import("../build.zig").Platform; const PerfBuild = @import("../build.zig").PerfBuild; -const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars; const core = @import("core.zig"); const testMatch = @import("tests.zig").testMatch; @@ -42,8 +41,6 @@ pub fn add(b: *std.Build, c: struct { shell_cfg: core.ShellConfig, target: std.Build.ResolvedTarget, test_filters: []const []const u8, - tracy: ?[]const u8, - tree_sitter_grammars: TreeSitterGrammars, unit_profile: *std.Build.Step.Compile, }) Tools { const image_harness = program(b, "pardes-image-harness", "test/image_harness.zig", c.target, c.optimize, &.{}); @@ -191,10 +188,10 @@ pub fn add(b: *std.Build, c: struct { .c_optimize = @tagName(c.c_optimize), .terminal_optimize = @tagName(c.ghostty_optimize), .platform = @tagName(c.platform), - .grammars = @tagName(c.tree_sitter_grammars), + .grammars = @tagName(c.shell_cfg.tree_sitter_grammars), .mupdf = c.pdf_addon != null, .jpx = c.enable_jpx, - .tracy = c.tracy != null, + .tracy = c.shell_cfg.tracy != null, .terminal_simd = c.ghostty_simd, .prebuilt_shaders = c.platform == .gui and c.prebuilt_shaders, }); diff --git a/core/Addon.zig b/core/Addon.zig index ec2f796a..c60f2430 100644 --- a/core/Addon.zig +++ b/core/Addon.zig @@ -236,9 +236,9 @@ fn fileOf(fd: c_int) ?[5]i64 { /// library exports. A static binary cannot dlopen, and the loader below /// is Linux's (a memfd): this is how either has image and PDF panes. /// A build with -Dpdf=false has the image addon alone. -const compiled_in: []const *const Kind.Ops = if (!@import("builtin_addons").on) +const compiled_in: []const *const Kind.Ops = if (!@import("pardes_options").builtin_addons) &.{} -else if (@import("builtin_addons").pdf) +else if (@import("pardes_options").builtin_pdf) &.{ &@import("image_addon").pardes_addon, &@import("pdf_addon").pardes_addon } else &.{&@import("image_addon").pardes_addon}; @@ -911,7 +911,7 @@ test "addon reload gives migration the old record version and saves the new vers return if (version == 1 and n == 1 and bytes[0] == 7) Kind.c.PA_OK else 1; } }; - const p = try @import("ninep/testing.zig").withFile(std.testing.allocator, "x\n"); + const p = try @import("ninep/harness.zig").withFile(std.testing.allocator, "x\n"); defer p.deinit(); var old = std.mem.zeroInit(Kind.Ops, .{ .head = std.mem.zeroInit(Kind.c.pa_head, .{ .size = @sizeOf(Kind.c.pa_head), .abi = Kind.abi, .version = 1 }), .open = Fake.open, .paint = Fake.paint, .dump = Fake.save, .load = Fake.load }); @memcpy(old.head.name[0..7], "migrate"); diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index 1b28267e..9b551e9b 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -2,6 +2,66 @@ ## Unreleased +- On a client, and so on a far one, what changes only the editor is + applied at once and only what touches the session's machine waits for + it (a save, a shell's keys, a file read from disk, a program run, a + kind whose state is the session's). Collapse, Newcol, Joincol, a window + resized and a pane's grip dragged beside a shell, Del and Zerox of a + file's pane, a yank to the clipboard, ClipPaste, a Theme after a + ThemeFile and a key that starts an addon's job each waited a round + trip and no longer do; nor does a click into or out of a shell whose + program asked for focus events, which hears of the focus a round trip + after it shows. + +- A client's yank to the system clipboard (`"+y`, ClipYank) fills the + clipboard of the machine the client runs on, ClipPaste pastes that + clipboard, and a link a client looks at opens there; all three went to + the session's machine. + +- `n` and `N` in a kind's pane (+Search, references, errors) step to the + places its rows hold, at once, and no longer stop on a bare word of a + command's output that names a file. + +- On a client, `~`, the default shell, a word run in the session's + directory, `Font`, `Fonts` and DumpDir's check of its directory are the + session's machine's, where a client's own step read its own machine and + could part from the session. + +- An idle client and its session stay idle: a client's quiet check, once + answered, asked again 300 ms later for ever, waking both processes + three times a second. + +- A pardes that starts while another, still running, loads an addon no + longer takes that load for a crash: a client starting while its session + loaded the same game listed it `skipped: it crashed its last load`, and + every key into the game waited for the session, until `Addon load`. + +- A search pattern that stops inside a count or an escape (typing + `a{2}` or `fn main() {`, `a{1,`, `\x`) no longer takes a safe build + down, nor in a fast one finds what the bytes after it made of it: it + is a pattern that does not compile, found as the characters it is. A + class escape holding a lone non-ASCII byte no longer loops without end, + and a half-typed pattern that does not compile (`(`, `[`) no longer + leaks. + +- A client no longer diverges and joins again after a press on a + notice's chip, or a click in a big markdown text's table, in a view + whose frame it had not drawn; a big text's tables are read whole when + it opens (18 ms for 2.7 MB of tables), where they were read 4096 lines + first, then 4 ms a frame. + +- A client no longer crashes when another's input rolls back its own Del + of a pane whose kind's state is not plain, nor drawing a closed + terminal with a kitty image it brought back (`Look @pN`) under a + rollback. A kind's picture drawn for a pane closed meanwhile is let go, + where it was kept for the session's life; `pardes help` with no session + running no longer crashes now and then, freeing its own core while + still answering it. + +- The tag word `Unattach` is `Undock`: a +Search docked under the pane it + answers for leaves it with `Undock`, and stays where it is, a pane of its + own. *Attach* is a client joining a session now; `Unattach` is an + unknown word, with no alias. - The row after a file's last newline, where the cursor can sit and no line is yet, shows `~` in the gutter where its line number was, as helix's does. @@ -21,7 +81,7 @@ `zig build builtins-json -Dplatform=tui`, and a test says when it is stale. -- The text pane is a library too, `pardes-editor` (`src/lib_editor.zig`, +- The text pane is a library too, `pardes-editor` (`core/lib_editor.zig`, docs/next-editor.md): helix's keys on a text kept in memory, for a program that draws it itself (a sketch with a language of its own). It is a value of plain data, every capacity in its type, copied anywhere @@ -42,10 +102,10 @@ where its grammar has an indent query (a `Language`'s `indents`), as a file's does from its own, so a language whose lines end in `)` is not pushed a level in at every line. -- The terminal is a module of its own (`src/term/`: the emulator, its +- The terminal is a module of its own (`core/term/`: the emulator, its screen state for replicas, kitty images, the pager's parse), which never imports the core and is reached through one table of plain-data - entries, `src/Term.zig` the core's side (docs/next-terminal.md). Editing + entries, `core/Term.zig` the core's side (docs/next-terminal.md). Editing a terminal's text is the core's, on a copy of its rows, as before, and predicted echo stays the core's; nothing a session does changes, and a session dumped before loads after. `zig build core-test` builds the core @@ -73,7 +133,7 @@ directory), and only what no rule set takes is Look's own. The default rules keep every look as it was: the browser for a URL, a bare `.diff` or `.patch` stacked in a +Diff, `git show` of a commit hash in a git - work tree are now rules of `src/plumbing`, no longer written into + work tree are now rules of `core/plumbing`, no longer written into Look. `Diff` takes a file or a revision (`Diff fix.patch`, `Diff 3f2a9c1`), and a rule's Diff that cannot declines, so the look goes on. `Plumb` opens your plumbing file (`<config>/plumbing`, `include @@ -94,7 +154,7 @@ takes a message and sends it where they say, to a port pardes reads (`edit`, `web`, a loaded kind) or to a word or command started, with Plan 9's words when it cannot. A session starts with `include basic`, - pardes's rules (`src/plumbing`). Kept in a dump. `$1`-`$9` are refused, + pardes's rules (`core/plumbing`). Kept in a dump. `$1`-`$9` are refused, the regular expressions having no submatches. - A query pane's row looked at on its address (its gutter) opens the @@ -148,7 +208,7 @@ for Zig 0.17 was deleted, and a fresh checkout could not fetch it. - pardes's syntax is a library: a Zig package that depends on pardes is - given the `pardes-syntax` module (`src/lib_syntax.zig`), with the + given the `pardes-syntax` module (`core/lib_syntax.zig`), with the grammars, highlighting, declarations, syntax tree and themes as the editor has them, for a program that draws source text itself. Every dependency but tree-sitter's runtime is lazy in the manifest, so such a @@ -216,12 +276,12 @@ saying so until a Look or a watch of it. A picture's or a PDF's tag has its art words from the first frame. A Debug pardes says a kind's call over 16 ms; `--addon-test` fails on it, and has `view N on|off`. - `src/kinds/addon.zig` wraps the whole header. + `abi/addon.zig` wraps the whole header. - `zig build static -Dplatform=tui -Dtarget=x86_64-linux-musl`: one statically linked `pardes` with the image and PDF addons compiled in (`/addons` lists them `builtin`; `Addon reload` refuses them). It replaces `-Dstatic`, which glibc refused (it links only dynamically). -- Addons in Zig: `src/kinds/addon.zig` (over the same header, nothing of +- Addons in Zig: `abi/addon.zig` (over the same header, nothing of the core) makes a kind's `pa_ops` from a struct of its functions, with the pane's arena as an Allocator, typed keys, a window to `put` text in, a deadline for `tick`, a struct's bytes as its record and its own `zig @@ -246,7 +306,7 @@ installed beside the binaries and loaded at start; a pardes without it shows image files as text. -- Addons speak ABI 2 (src/kinds/pardes_addon.h): `tick` is told +- Addons speak ABI 2 (abi/pardes_addon.h): `tick` is told `PA_FOCUSED` and called again after anything happens to its pane, so a game stands still unfocused asking for nothing; one `paint` a frame; jobs on the host's workers, dropped across a reload; each session its @@ -366,7 +426,7 @@ session kernel-mounted through Linux v9fs, a one-off), with their tests; a kernel mount made by hand still works, as the build notes say. - The terminal frontend is the tui: `zig build -Dplatform=tui`, its code - in `src/tui/` (the binary is still `pardes`, and `--tty` still starts + in `dev/tui/` (the binary is still `pardes`, and `--tty` still starts one shell pane in tty mode). The builtin that opens a terminal pane, `Tty`, is `Term` (`SPC n t`); `Tty` still runs it, as acme's words run theirs. diff --git a/core/Core.zig b/core/Core.zig index d5a990e2..9a542940 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -72,7 +72,6 @@ const lsp = pardes.lsp; const memory = pardes.memory; const modal = pardes.modal; const mouse = pardes.mouse; -const newer_build_words = pardes.newer_build_words; const platform = pardes.platform; const recent_files = @import("recent.zig"); const sel_slot = pardes.sel_slot; @@ -288,7 +287,7 @@ session_home: [limits.host_path_cap]u8 = undefined, session_home_len: ?u16 = null, session_shell: [limits.host_path_cap]u8 = undefined, session_shell_len: u16 = 0, -settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, +settings: config.Settings = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations.Config = .{}, locations_cache: locations.Cache = .{}, tty_filter_palette: pardes.Term.FilterPalette = .{}, @@ -296,10 +295,10 @@ font_request_taken: bool = false, custom_theme: ?Theme = null, /// bodyChrome's: the theme it was worked out for, and it. body_chrome: ?struct { theme: Theme, chrome: ChromeTheme } = null, -theme_file_path: config.Runtime.Text(limits.host_path_cap) = .{}, +theme_file_path: config.Settings.Text(limits.host_path_cap) = .{}, /// The ThemeFile last loaded whole: what /ctl and DumpConfig name, and /// what a failed ThemeFile goes back to (colors.revertThemeFile). -theme_file_loaded: config.Runtime.Text(limits.host_path_cap) = .{}, +theme_file_loaded: config.Settings.Text(limits.host_path_cap) = .{}, theme_file_generation: u32 = 0, theme_file_pane: u8 = 0, chrome: colors.ChromeTheme = colors.initial_chrome, @@ -1102,7 +1101,7 @@ fn observeFontInner( p: *Pardes, effective_name: []const u8, effective_size_hundredths: u16, - unit: config.Runtime.FontSizeUnit, + unit: config.Settings.FontSizeUnit, ) bool { if (!p.settings.font.effective_name.set(effective_name)) return false; p.settings.font.effective_size_hundredths = effective_size_hundredths; @@ -1117,7 +1116,7 @@ fn acknowledgeFontInner( p: *Pardes, effective_name: []const u8, effective_size_hundredths: u16, - unit: config.Runtime.FontSizeUnit, + unit: config.Settings.FontSizeUnit, ) bool { if (!p.settings.font.pending or !p.font_request_taken) return false; const changed = !std.mem.eql( @@ -1175,6 +1174,7 @@ fn openViewInner(p: *Pardes) ?View.Id { // tape does it here: a join dumps the session next, and a core // loaded from a dump has no queue (Replica.initDump). p.settle(); + pardes.panes.reloadTerminals(p); p.needs_frame = true; return .at(Views.open(p) orelse return null); } @@ -1217,6 +1217,7 @@ fn rejoinViewInner(p: *Pardes, k: View.Id) bool { if (!Views.isAway(p, k.index())) return false; p.views_away &= ~(@as(u8, 1) << @intCast(k.index())); p.settle(); + pardes.panes.reloadTerminals(p); p.needs_frame = true; return true; } @@ -1704,10 +1705,7 @@ fn updateInner(p: *Pardes, ev: Event) void { edit.applyPaste(p, bytes) catch |err| p.reportError(.at(v.active), "paste", err); }, .command => |line| _ = p.executeBuiltinLine(v.active, line), - .focus => |focused| { - v.window_focused = focused; - if (focused) if (p.host.vtable.newer_build) |f| if (f(p.host.ctx)) p.setMessage(.at(v.active), newer_build_words); - }, + .focus => |focused| v.window_focused = focused, .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), .addon => |a| pardes.Addon.landed(p, a.op, a.pane.index(), a.kind.*), .job => |j| pardes.Kind.jobDone(p, j.pane.index(), j.serial, j.token, j.gen, j.bytes), @@ -2945,7 +2943,7 @@ test "a REPL bound for a language takes the exec made on a body in it; tags, Exe // A body's click written back to event is done as the click: sent. A // line written to exec came back as F and runs as the command it was. { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const event = ctlfs.Node.of(file.serial, .event); const h = th.call(p, .{ .tag = 1, .op = .open, .node = event }).reply.handle; defer _ = th.call(p, .{ .tag = 2, .op = .release, .node = event, .handle = h }); @@ -3039,7 +3037,7 @@ test "a REPL bound for a language takes the exec made on a body in it; tags, Exe try std.testing.expect(Sent.len[1] == 0 and file.prompt == .none); // The question is in the log, and a script answers it on the ctl. { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); _ = exec.executeFrom(p, 0, "print(5)", true); var want: [32]u8 = undefined; try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "ask {d} repl a b\n", .{file.serial}))); @@ -3423,7 +3421,7 @@ test "Font keeps requested and acknowledged faces as separate plain state" { try std.testing.expect(!p.settings.font.pending); try std.testing.expectEqualStrings(installed[0].name, p.settings.font.effective_name.get()); try std.testing.expectEqual(@as(u16, 1375), p.settings.font.effective_size_hundredths); - try std.testing.expectEqual(config.Runtime.FontSizeUnit.pixels, p.settings.font.effective_size_unit); + try std.testing.expectEqual(config.Settings.FontSizeUnit.pixels, p.settings.font.effective_size_unit); try std.testing.expect(!p.acknowledgeFont("Duplicate Ack", 1400, .pixels)); try std.testing.expect(p.executeBuiltinLine(p.view().active, cmd)); @@ -3541,7 +3539,7 @@ test "Tab N draws every pane's tab N cells wide and clicks count past it; bare T try std.testing.expect(p.executeBuiltinLine(0, "Tab 0")); try std.testing.expectEqual(@as(u16, 8), p.settings.tab); // The ctl read's tab column, and a Dump's settings. - const ctl_text = @import("ninep/testing.zig").rd(p, ctlfs.Node.of(pane.serial, .ctl), 0, 4096).bytes; + const ctl_text = @import("ninep/harness.zig").rd(p, ctlfs.Node.of(pane.serial, .ctl), 0, 4096).bytes; try std.testing.expect(std.mem.indexOf(u8, ctl_text, " 8 ") != null); try dump.dumpState(p); const restored = try dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); diff --git a/core/Dir.zig b/core/Dir.zig index a82887fb..29c5cdc8 100644 --- a/core/Dir.zig +++ b/core/Dir.zig @@ -430,7 +430,7 @@ test "an exec in a directory pane runs in its directory, and its +Errors goes th } test "over 9P a directory pane is a text pane whose name ends in /, its body the listing, ctl's isdir 1, and get reads it again" { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const tree = @import("ninep/tree.zig"); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); diff --git a/core/Editor.zig b/core/Editor.zig index 9781d857..aaf6ab05 100644 --- a/core/Editor.zig +++ b/core/Editor.zig @@ -10,7 +10,7 @@ const Registers = @import("Registers.zig"); /// The library's build (build.zig `library`): a text with no pane and no /// core, its characters its own. Where an edit reaches a pane it branches /// on this at compile time, so the library never compiles the core. -pub const lib = @import("pardes_config").lib; +pub const lib = @import("pardes_options").lib; const Pardes = if (lib) void else @import("Core.zig"); const Syntax = if (lib) @import("lib_editor.zig").Syntax else void; const modal = @import("modal.zig"); diff --git a/core/Effect.zig b/core/Effect.zig index 7166294f..5e821065 100644 --- a/core/Effect.zig +++ b/core/Effect.zig @@ -218,7 +218,7 @@ fn performInner(p: *Pardes, e: Effect) void { else p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), // No workers here (a test, a board): it runs on the loop. - .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen), + .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen, false), // No windows here (a test, the tty): it stays. .hand_over => |h| if (v.hand_over) |f| { if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes); @@ -681,7 +681,7 @@ test "a save path that names no file is refused before anything is rewritten" { } test "a Save the host could not do logs no save record" { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const p = try th.withFile(std.testing.allocator, "x\n"); defer p.deinit(); const Failing = struct { diff --git a/core/File.zig b/core/File.zig index 020985da..75d8049b 100644 --- a/core/File.zig +++ b/core/File.zig @@ -59,8 +59,13 @@ pub const History = struct { } }; -/// Owned syntax results. Excluded from dumps as State.context is derived. +/// Owned syntax results: a text's declarations at a revision. pub const ContextCache = struct { + /// Its revision is dumped and digested: a worker's parse is an input, + /// which a client joined since never saw, and a step reads what it + /// left (Query.ownerDecls). The declarations are made again from the + /// text at a load (`reload`), with the allocator that made them. + pub const replica = .{ .local = .{"allocator"}, .derived = .{"declarations"} }; allocator: ?std.mem.Allocator = null, declarations: []syntax.ContextDeclaration = &.{}, revision: ?u32 = null, @@ -70,6 +75,15 @@ pub const ContextCache = struct { self.* = .{}; } + /// A loaded text's (its revision the dump's): its declarations parsed + /// again where they are of the text it has. + pub fn reload(self: *ContextCache, gpa: std.mem.Allocator, path: []const u8, content: []const u8, revision: u32) void { + const at = self.revision orelse return; + if (at != revision) return; + const declarations = syntax.contextDeclarations(gpa, path, content) catch return; + self.replace(gpa, declarations, at); + } + /// Takes ownership of declarations allocated by gpa. pub fn replace(self: *ContextCache, gpa: std.mem.Allocator, declarations: []syntax.ContextDeclaration, revision: u32) void { self.deinit(); @@ -83,7 +97,7 @@ pub const State = struct { /// from the text whenever it is wanted. // Syntax caches must not load through the dump loader's core allocator. pub const replica = .{ - .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "context", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, + .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" }, // Big texts, dumped and sent by their hash (core/walk.zig). The // text is written in place by `replace`, but never while a join // sends it (memory.zig `pin`): then an edit puts a new buffer in diff --git a/core/Handover.zig b/core/Handover.zig index bcf42c31..dde31f8b 100644 --- a/core/Handover.zig +++ b/core/Handover.zig @@ -165,7 +165,7 @@ pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]co const pane = p.panes[id].?; if (pane.file == null or pane.file.?.revision != revision) { // Out of its group, or the owner's close would take it along. - pane.attached_to = null; + pane.docked_to = null; kept += 1; continue; } @@ -277,7 +277,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize { for (st.owners, 0..) |owner, k| { const at = owner orelse continue; if (at >= n) continue; - p.panes[slots[k]].?.attached_to = p.panes[slots[at]].?.serial; + p.panes[slots[k]].?.docked_to = p.panes[slots[at]].?.serial; } const tc = layout.targetColumn(p, x); var heights: [MAX_PANES]u16 = @splat(0); diff --git a/core/Kind.zig b/core/Kind.zig index 7641c2d1..81997afb 100644 --- a/core/Kind.zig +++ b/core/Kind.zig @@ -136,7 +136,7 @@ pub const Slot = struct { // jobs' inputs, its file's hash, a placeholder's record), and what // a frame makes (the thumb, the pointer, whether one was drawn: a // view's, never a step's). - .local = .{ "ops", "st", "gpa", "arena", "plain", "file", "opened", "reloads", "jobs", "record", "thumb_at", "thumb_span", "pointer", "painted", "over", "used", "draws" }, + .local = .{ "ops", "st", "gpa", "arena", "plain", "file", "opened", "reloads", "jobs", "record", "thumb_at", "thumb_span", "pointer", "painted", "over", "used" }, }; /// Its kind's code here; null in a placeholder (`live` false: its kind /// not in the registry, its record kept for the day it comes) or a @@ -198,11 +198,6 @@ pub const Slot = struct { /// whether a frame was painted since its last tick. pointer: u8 = 0, painted: bool = false, - /// The last of its draws' tokens (api.draw), each its own process's: a - /// draw is a frame's, and how many frames each process paints differs, - /// so it is in no digest; the copy holds it with the slot. A kind - /// keeping one in its state (PA_PLAIN) is caught at that call's digest. - draws: u32 = 0, /// Each view's facts (a hash of its pa_view) as `view` was last told /// them, 0 for none: a change tells it again. views: [views.max]u64 = @splat(0), @@ -1220,8 +1215,8 @@ pub const api: c.pa_api = .{ heap.free(copy); return 0; }; - cl.slot.draws = (cl.slot.draws +% 1) & ~c.PA_DRAWN; - const token = c.PA_DRAWN | cl.slot.draws; + drawn = (drawn +% 1) & ~c.PA_DRAWN; + const token = c.PA_DRAWN | drawn; j.* = .{ .gpa = heap, .pane = @intCast(cl.id), .serial = pane.serial, .token = token, .gen = cl.slot.gen, .ops = ops, .in = copy, .arena = .init(heap), .draw = p }; Addon.holdJob(ops, true); if (drawer) |d| if (d.go(d.ctx, j)) return token; @@ -1250,6 +1245,12 @@ pub const api: c.pa_api = .{ pub var drawer: ?struct { ctx: ?*anyopaque, go: *const fn (ctx: ?*anyopaque, j: *host_io.KindJob) bool } = null; /// Draws done, each kept for its pane's next paint (the loop's alone). var ready: std.ArrayListUnmanaged(*host_io.KindJob) = .empty; +/// The last token a draw was given: a draw is a frame's, this process's, in +/// no digest and no copy (a kind keeping one in its PA_PLAIN state is +/// caught at that call's digest). A rollback takes a slot back, never this, +/// so no draw is given the token a discarded speculation's frame was, whose +/// answer may come after. +var drawn: u32 = 0; /// A draw done on a worker, back on the loop: kept for its pane's next /// paint, a frame owed. One of another core's (a client joined again diff --git a/core/Messages.zig b/core/Messages.zig index 1fb232c7..46dab136 100644 --- a/core/Messages.zig +++ b/core/Messages.zig @@ -76,7 +76,8 @@ pub const Message = struct { extern "c" fn localtime_r(timep: *const libc.time_t, result: *Tm) ?*Tm; /// PARDES_NOTIME set (the tests, a snapshot run): every clock reads - /// `--:--:--`. + /// `--:--:--`. A host's (`stamp`, dev/lsp): no step reads it, the text + /// it stamps crossing as a setMessage's. pub fn noTime() bool { const v = libc.getenv("PARDES_NOTIME") orelse return false; return std.mem.span(v).len != 0; diff --git a/core/Output.zig b/core/Output.zig index 3ac9f521..759bada9 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -9,7 +9,8 @@ const Pardes = pardes.Pardes; const modal = @import("modal.zig"); const limits = @import("memory.zig").limits; const builtins = @import("builtins.zig"); -const build_options = @import("pardes_config"); +const build_options = @import("pardes_options"); +const build_info = @import("build_info"); const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); @@ -705,7 +706,7 @@ pub fn openThemes(p: *Pardes, id: usize) !void { for (pardes.themes, 0..) |t, i| { if (pardes.colors.groupAt(i)) |title| try out.writer.print("{s}# {s}\n", .{ if (i == 0) "" else "\n", title }); - try out.writer.print(comptime config.Runtime.findAction(.theme).?.word ++ " {s}\n", .{t.name}); + try out.writer.print(comptime config.Settings.findAction(.theme).?.word ++ " {s}\n", .{t.name}); } const content = try out.toOwnedSlice(); try openStepped(p, id, .{ .cmd = .Themes }, content); @@ -716,7 +717,7 @@ pub fn isWalkRow(file: *const File.State, row: usize, line: []const u8) bool { if (usesLocationsConfig(state.from) or std.meta.eql(state.from, Origin{ .query = .callstack })) return isResultRow(file, row); if (!std.meta.eql(state.from, Origin{ .cmd = .Themes })) return true; // Section labels are for reading, not stops in the command walk. - return std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), comptime config.Runtime.findAction(.theme).?.word ++ " "); + return std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), comptime config.Settings.findAction(.theme).?.word ++ " "); } pub fn openFonts(p: *Pardes, id: usize) !void { @@ -733,7 +734,7 @@ fn fontsListed(gpa: std.mem.Allocator, arena: std.mem.Allocator) anyerror![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); for (fonts.list(arena, null)) |f| - try out.writer.print(comptime config.Runtime.findAction(.font).?.word ++ " {s}\n", .{f.name}); + try out.writer.print(comptime config.Settings.findAction(.font).?.word ++ " {s}\n", .{f.name}); return out.toOwnedSlice(); } @@ -852,7 +853,7 @@ pub fn openConfig(p: *Pardes, id: usize) !void { var located: std.Io.Writer.Allocating = .init(p.gpa); defer located.deinit(); try p.locations_config.write(&located.writer); - try config.Runtime.writeReport(&out.writer, .{ + try config.Settings.writeReport(&out.writer, .{ .locations = located.written(), .default_dump_dir = p.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}), .startup_config_path = p.startupPath(), @@ -896,9 +897,9 @@ pub fn openBuild(p: *Pardes, id: usize) !void { const w = &out.writer; try w.print("{s}\n", .{@import("runtime").upgrade.version_line}); try w.print("commit {s}\nchange {s}\nbuilt {s}\n", .{ - build_options.commit orelse "not stamped (a Debug build with -Dplatform or --prefix)", - build_options.change orelse "not stamped", - build_options.built orelse "not stamped", + build_info.commit orelse "not stamped (a Debug build with -Dplatform or --prefix)", + build_info.change orelse "not stamped", + build_info.built orelse "not stamped", }); try w.print("zig {s}\nmode {s}\ntarget {s}-{s}-{s}\nplatform {s}\n", .{ builtin.zig_version_string, @tagName(builtin.mode), @@ -906,10 +907,10 @@ pub fn openBuild(p: *Pardes, id: usize) !void { @tagName(builtin.abi), @tagName(build_options.platform), }); try w.print("grammars {s}\naddons {s}\nsemantics {x:0>16}\n\ndependencies\n{s}", .{ - if (build_options.syntax_full_grammars) "full" else if (build_options.syntax_minimal_grammars) "minimal" else "none", - if (@import("builtin_addons").on) "compiled in" else "loaded from <prefix>/lib/pardes/addons", + if (build_options.grammars == .full) "full" else if (build_options.grammars == .minimal) "minimal" else "none", + if (build_options.builtin_addons) "compiled in" else "loaded from <prefix>/lib/pardes/addons", @import("wire").semantics, - build_options.deps, + build_info.deps, }); const content = try out.toOwnedSlice(); return openRead(p, id, .{ .cmd = .Build }, "", content); @@ -918,7 +919,7 @@ pub fn openBuild(p: *Pardes, id: usize) !void { pub fn openChangelog(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); - try out.writer.print("pardes {s}\n\n", .{build_options.version}); + try out.writer.print("pardes {s}\n\n", .{build_info.version}); try out.writer.writeAll(@embedFile("CHANGELOG.md")); const content = try out.toOwnedSlice(); return openRead(p, id, .{ .cmd = .Changelog }, "", content); diff --git a/core/Places.zig b/core/Places.zig index 1416dbd3..9ffbff88 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -890,5 +890,8 @@ test "a session's places loaded from its dump find what an edit makes as the ses pn.places.fill(p, pn, 0, frame_steps); try std.testing.expectEqual(@as(usize, 3), pn.places.hits.items.len); } + // An edit stamps the text with the wall clock's second (File.edit's + // mtime): the two cores' edits, a moment apart, can fall in two. + b.panes[b.view().active].?.file.?.mtime = a.panes[a.view().active].?.file.?.mtime; try std.testing.expectEqual(pardes.walk.digest(Pardes, a), pardes.walk.digest(Pardes, b)); } diff --git a/core/Query.zig b/core/Query.zig index dacc11a1..704206e6 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -200,16 +200,16 @@ fn freeSaved(gpa: std.mem.Allocator, s: Saved) void { gpa.free(s.items); } -/// The owner's query pane (attached to it, or left where it was by -/// Unattach): the one a later search from it reuses. +/// The owner's query pane (docked to it, or left where it was by +/// Undock): the one a later search from it reuses. pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize { var found: ?usize = null; for (p.panes, 0..) |slot, i| { const pane = slot orelse continue; const q = pane.query orelse continue; if (q.owner != owner_serial) continue; - // the attached one first: an unattached one is a kept result - if (pane.attached_to == owner_serial) return i; + // the docked one first: an undocked one is a kept result + if (pane.docked_to == owner_serial) return i; found = found orelse i; } return found; @@ -754,7 +754,7 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz const oid = owner_id orelse return; const owner = p.panes[oid].?; const f = if (owner.file) |*file| file else return; - const decls = ownerDecls(p, f, false) orelse { + const decls = ownerDecls(f) orelse { // Parsed on the worker; listed when it is done (declsArrived). Stream.parseFor(p, oid); return; @@ -782,31 +782,15 @@ fn recentRows(p: *Pardes, out: *std.Io.Writer.Allocating) []const u8 { return out.written(); } -/// The owner's declarations, from a parse that already exists: its sticky -/// headers' (TreeContext) at this revision, or the locations cache's. None -/// is made here, on the loop, unless `small` and the text is small: a -/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build. -/// ponytail: no grouping for a big file until the disk engine's worker -/// parses it (phase 4). -fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { +/// The owner's declarations, from its parse at this revision (its context: +/// sticky headers' (TreeContext), a worker's answer, a dump's load), or +/// none: never the locations cache's (a Diff's), which a client joined +/// since has not, nor a parse made here (Stream.parseFor asks one). +fn ownerDecls(f: *const File.State) ?[]const syntax.ContextDeclaration { if (f.context.revision) |rev| if (rev == f.revision and f.context.declarations.len > 0) return f.context.declarations; - const cache = &p.locations_cache; - for (cache.entries[0..cache.len]) |entry| { - if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; - } - if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null; - var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null; - if (got.owned) { - got.deinit(p.tree_sitter_gpa); - return null; - } - return got.analysis.declarations; + return null; } -/// A text this small is parsed on the loop for its declarations when a -/// Symbols query asks (about 40 ms in a Debug build). -const small_parse_bytes = 64 << 10; - /// The rows as `note` says, and nothing else: no hits. fn noteRows(p: *Pardes, id: usize, note: []const u8) void { const rp = p.panes[id].?; @@ -1043,7 +1027,7 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar const rel = lookPath(&relbuf, path, dir); const width = addressWidth(rel, index.len); var sh: Shades = .{}; - const decls = ownerDecls(p, f, false) orelse &.{}; + const decls = ownerDecls(f) orelse &.{}; var decl_now: ?usize = null; var i: usize = @min(from, hits.len); // the line of the first, found in the index @@ -1107,7 +1091,7 @@ fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { var rows: std.ArrayList(locations.Row) = .empty; var budget: usize = if (full) max_rows else live_rows; // Grouped once a parse of the text exists: asked of the worker now. - if (ownerDecls(p, &owner.file.?, false) == null) Stream.parseFor(p, oid); + if (ownerDecls(&owner.file.?) == null) Stream.parseFor(p, oid); const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); // While typed, a window of rows from just before the current place, so // it sits under line 1. @@ -1754,7 +1738,7 @@ fn promote(p: *Pardes, qid: usize, id: usize) void { // Its text was read from that file to preview it (displayPreview). f.on_disk = filesystem.localPath(f.path) != null; f.syntax_dirty = true; - pane.attached_to = null; + pane.docked_to = null; if (f.on_disk) p.recent.opened(p.recentGpa(), f.path); if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = .at(id), .on = true } }); pardes.ctlfs.events.noteLog(p, .rename, pane); @@ -1887,7 +1871,7 @@ pub fn cancel(p: *Pardes, id: usize) void { // A preview made for the query Esc took back has no use: its rows // go to the text whose rows they were. if (previewOf(p, id)) |pid| { - p.panes[pid].?.attached_to = null; + p.panes[pid].?.docked_to = null; p.removePane(pid, owner_id) catch |err| p.reportError(.at(id), "query", err); q.preview = 0; } @@ -2354,7 +2338,7 @@ test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing try std.testing.expectEqual(pv, p.view().active); try std.testing.expectEqual(serial, p.panes[pv].?.serial); try std.testing.expect(p.panes[pv].?.file.?.output == null); - try std.testing.expect(p.panes[pv].?.attached_to == null); + try std.testing.expect(p.panes[pv].?.docked_to == null); layout.compute(p); try std.testing.expectEqualDeep(rect, p.view().rects[pv]); try std.testing.expect(q.frozen); @@ -2754,6 +2738,6 @@ test "a query row's address reaches every way a look arrives: an empty look writ // the whole row written to the pane's look: the place a.body.cur_row = 0; const tree = @import("ninep/tree.zig"); - try std.testing.expectEqual(tree.Status.ok, @import("ninep/testing.zig").wr(p, tree.Node.of(qp.serial, .look), line).reply.status); + try std.testing.expectEqual(tree.Status.ok, @import("ninep/harness.zig").wr(p, tree.Node.of(qp.serial, .look), line).reply.status); try std.testing.expectEqual(@as(i32, 3), a.body.cur_row); } diff --git a/core/Stream.zig b/core/Stream.zig index 74c8128a..5960d249 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -559,7 +559,7 @@ pub fn step(p: *Pardes) void { s.state = .searching; // A script's write (whose answer says whether it found anything) and a // host with no workers: done before this returns. - if (p.host.vtable.search != null and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen); + if (p.host.vtable.search != null and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen, false); } /// When the core next needs a tick for the stream: the end of the pause. @@ -576,12 +576,8 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*an if (gen & paint_bit != 0) { for ([_]*?TextTask{ &s.paint, &s.rows_paint }) |slot| if (slot.*) |*t| if (t.job.gen == gen and t.future == null) { t.job.out = gpa; - t.future = io.concurrent(paintWork, .{ io, t.job, ctx, sink }) catch { - const job = t.job; - slot.* = null; - job.deinit(); - return; - }; + // No worker to be had: let go as runHere does, by an input. + t.future = io.concurrent(paintWork, .{ io, t.job, ctx, sink }) catch return runHere(p, gen, true); t.io = io; }; return; @@ -589,12 +585,9 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*an // A parse's generation: its own task. if (s.parse) |*t| if (gen == s.parse_gen and t.job.gen == gen and t.future == null) { t.job.out = gpa; - t.future = io.concurrent(parseWork, .{ io, t.job, ctx, sink }) catch { - const job = t.job; - s.parse = null; - job.deinit(); - return; - }; + // No worker to be had: let go by an input, a parse that found none. + t.future = io.concurrent(parseWork, .{ io, t.job, ctx, sink }) catch + return p.update(.{ .search = .{ .gen = gen, .parsed = .{ .serial = t.job.serial, .revision = t.job.revision } } }); t.io = io; return; }; @@ -607,7 +600,7 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*an const future = io.concurrent(work, .{ io, job, ctx, sink }) catch { // No worker to be had: it runs here, on the loop. job.deinit(); - return runHere(p, gen); + return runHere(p, gen, true); }; s.task = .{ .job = job, .future = future, .io = io }; } @@ -625,13 +618,18 @@ fn makeJob(gpa: std.mem.Allocator, s: *const Stream) !*Job { /// A host with no workers (a test's, the fallback when none can be had): /// the whole search on the loop, the turn out for it, its batches taken in -/// as a worker's would be. Its cap is a hard stop. -pub fn runHere(p: *Pardes, gen: u32) void { +/// as a worker's would be. Its cap is a hard stop. `in_call`: run in the +/// host's `search` entry, where what it wrote into the core would be in no +/// record: each batch handed in as a worker's is, an input the tape records +/// and every replica takes. +pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { // A paint with no worker to run it (a shell not threaded yet): let go, - // never left to hold its slot; the rows or the view ask again. + // never left to hold its slot; the rows or the view ask again. In a + // host's call, by an input: a worker's answer of nothing. if (gen & paint_bit != 0) { const s = &p.stream; for ([_]*?TextTask{ &s.paint, &s.rows_paint }) |slot| if (slot.*) |t| if (t.job.gen == gen and t.future == null) { + if (in_call) return p.update(.{ .search = .{ .gen = gen, .end = .done, .painted = .{ .serial = t.job.serial, .revision = t.job.revision, .start = t.job.start } } }); slot.* = null; t.job.deinit(); }; @@ -655,7 +653,7 @@ pub fn runHere(p: *Pardes, gen: u32) void { const batches = p.tape.site(.search, p.gpa, searchHere, .{ p.gpa, job }); defer p.gpa.free(batches); for (batches) |*b| { - receive(p, b); + if (in_call) p.update(.{ .search = b.* }) else receive(p, b); b.deinit(p.gpa); } } diff --git a/core/Term.zig b/core/Term.zig index fde36420..89773f77 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -14,8 +14,17 @@ const dump = @import("dump.zig"); const File = @import("File.zig"); const iface = plain.term; +/// Writes into this process's emulators (a read fed, a grid reflowed, a +/// view moved, one opened, closed, loaded or made again): whether a unit's +/// replay made one, the replica engine's one rule (core/replica.zig +/// `confirm`) reads across that replay, on its one thread. +pub var writes: u32 = 0; +/// The reloads this process made (a join's, on every side) and their time, +/// for the soak's join line (test/replicas.zig `--bytes`). +pub var reloads: struct { n: u32 = 0, ns: u64 = 0, worst_ns: u64 = 0 } = .{}; + /// The terminal module's entries; null in a core built without it. -pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null; +pub const ops: ?*const iface.Ops = if (@import("pardes_options").terminal) &@import("term").ops else null; /// What a core without a terminal says, once, where one would have been. pub const none = "no terminal in this build"; @@ -30,6 +39,8 @@ pub const Moves = iface.Moves; pub const MouseMods = iface.MouseMods; pub const MouseButton = iface.MouseButton; pub const MouseAction = iface.MouseAction; +/// A grid cell (the one a program last heard the mouse at: Pane.term_mouse). +pub const Coordinate = iface.Parts.Coordinate; pub const Page = iface.Page; pub const Span = iface.Span; pub const Ink = iface.Ink; @@ -92,6 +103,9 @@ pub const State = struct { defer arena.deinit(); const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; + writes +%= 1; + // A replica's (a join's, a closed terminal brought back in a step). + if (tape.replaying() or dump.terminal_gpa != null) o.direct(out.impl); } }; @@ -112,6 +126,10 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { const s = try gpa.create(State); errdefer gpa.destroy(s); s.* = .{ .impl = try o.open(gpa, cols, rows) }; + writes +%= 1; + // A replica's emulator loads its program's images by direct data alone + // (P32): what is read off the session's machine is the session's. + if (tape.replaying()) o.direct(s.impl); return s; } @@ -119,10 +137,27 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { /// one it was opened with): the allocator a caller hands is not used. pub fn close(s: *State, _: std.mem.Allocator) void { const own = the().gpa(s.impl); + writes +%= 1; the().close(s.impl); own.destroy(s); } +/// Its emulator made again from its own snapshot, where it is: at a join +/// every side does it, so that all hold the same pages (ghostty prunes its +/// history a page at a time, and a snapshot does not say how its rows were +/// cut into pages). The snapshot's hash, which every side compares. +pub fn reload(s: *State) !u64 { + writes +%= 1; + const t0 = @import("FrameStats.zig").nowNs(); + defer { + reloads.n += 1; + const dt = @import("FrameStats.zig").nowNs() -| t0; + reloads.ns += dt; + reloads.worst_ns = @max(reloads.worst_ns, dt); + } + return the().reload(s.impl); +} + /// When its next kitty animation frame is due (ms on the core's clock), as /// its last drawn frame left it; null when nothing plays. pub fn due(s: *const State) ?u64 { @@ -132,6 +167,7 @@ pub fn due(s: *const State) ?u64 { /// Loaded from a dump without its shell: its program's modes reset, its /// history marked off from what the next shell prints. pub fn revive(s: *State) void { + writes +%= 1; the().revive(s.impl); } @@ -150,6 +186,7 @@ pub fn stop() void { /// One read of its program's output (`Told` says where the tracked rows /// went). pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { + writes +%= 1; return the().feed(s.impl, bytes, tracked, rows, erased); } @@ -161,25 +198,30 @@ pub fn grid(s: ?*const State) Grid { /// Its view to a row of its history, or onto its output (null). pub fn viewTo(s: *State, at: ?usize) void { + writes +%= 1; the().viewTo(s.impl, at); } /// Its view moved by a number of rows (negative scrolls back). pub fn scroll(s: *State, delta: i32) void { + writes +%= 1; the().scroll(s.impl, delta); } /// Its view back onto its output. pub fn follow(s: *State) void { + writes +%= 1; the().follow(s.impl); } /// Its grid reflowed, now or when `resizeDeferred` makes it. pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { + writes +%= 1; the().resize(s.impl, cols, rows, later); } pub fn resizeDeferred(s: *State) bool { + writes +%= 1; return the().resizeDeferred(s.impl); } @@ -204,13 +246,13 @@ pub fn key(s: *State, k: plain.Key, out: *std.Io.Writer) !void { /// One mouse event for its program, as the mode and format it set ask for /// it; empty when the program does not hear of it. -pub fn mouse(s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { - return the().mouse(s.impl, buf, action, button, mods, col, row, any_pressed); +pub fn mouse(s: *State, last: *?Coordinate, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { + return the().mouse(s.impl, last, buf, action, button, mods, col, row, any_pressed); } /// A wheel turn for its program; null when the wheel is not the program's. -pub fn wheel(s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { - return the().wheel(s.impl, buf, turn, col, row, mods); +pub fn wheel(s: *State, last: *?Coordinate, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { + return the().wheel(s.impl, last, buf, turn, col, row, mods); } /// A paste as xterm makes one: three parts, the text between the brackets @@ -354,17 +396,6 @@ pub fn images(s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayLi the().images(s.impl, gpa, at, out, frame, frame_cols); } -/// The Petscii builtin on it: its kitty graphics as glyph art, or back to -/// pixels; null for none. -pub fn petscii(s: ?*const State) ?bool { - const o = ops orelse return null; - return o.petscii(if (s) |state| state.impl else null); -} - -pub fn togglePetscii(s: *State) void { - the().togglePetscii(s.impl); -} - /// Whether the screen showing holds any kitty graphics image. pub fn hasImages(s: ?*const State) bool { const o = ops orelse return false; diff --git a/core/Text.zig b/core/Text.zig index 51d660cf..1b3e6273 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -113,7 +113,7 @@ refused: bool = false, pub inline fn pane(t: *Text) ?*Pane { // the library's text has none (lib_editor.zig): known at compile time, // so what an edit does with a pane is not compiled there - if (comptime @import("pardes_config").lib) return null; + if (comptime @import("pardes_options").lib) return null; return switch (t.what) { .body => @alignCast(@fieldParentPtr("body", t)), .tag => @alignCast(@fieldParentPtr("tag", t)), diff --git a/core/ansi.zig b/core/ansi.zig index 6c23fee6..5f522536 100644 --- a/core/ansi.zig +++ b/core/ansi.zig @@ -228,6 +228,7 @@ pub fn images(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, .cols = @min(tw, pane.cols), .rows_of = rows_of[0..vp_rows], .tty_mode = pane.body.mode == .tty, + .petscii = pane.term_petscii, .now_ms = p.clock.stepped_ns / std.time.ns_per_ms, .cell_w = @max(1, p.view().cell_pixels.w), .cell_h = @max(1, p.view().cell_pixels.h), diff --git a/core/builtins.zig b/core/builtins.zig index 6f37e86d..1a0b4ce7 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -18,7 +18,7 @@ const keys = @import("keys.zig"); const Jump = @import("Jump.zig"); /// What this build's own frontend draws and its host does: the render's. -pub const frontend: config.Runtime.Capabilities = .{ +pub const frontend: config.Settings.Capabilities = .{ .font_picker = pardes.font_picker, // The tty's font belongs to its emulator. .tagline_font_size = pardes.platform != .tui, @@ -32,15 +32,15 @@ pub const frontend: config.Runtime.Capabilities = .{ /// its own frontend does (`viewCapabilities`), so a terminal's replica of a /// window's session steps as the window's own does, and back. pub const desktop = pardes.platform == .tui or pardes.platform == .gui; -const window_capabilities: config.Runtime.Capabilities = .{ .font_picker = true, .tagline_font_size = true, .window_opacity = true, .pixels = true }; -const terminal_capabilities: config.Runtime.Capabilities = .{ .font_picker = false, .tagline_font_size = false, .window_opacity = false, .pixels = false }; +const window_capabilities: config.Settings.Capabilities = .{ .font_picker = true, .tagline_font_size = true, .window_opacity = true, .pixels = true }; +const terminal_capabilities: config.Settings.Capabilities = .{ .font_picker = false, .tagline_font_size = false, .window_opacity = false, .pixels = false }; /// The words this build has: a desktop build's are the window's. -pub const capabilities: config.Runtime.Capabilities = if (desktop) window_capabilities else frontend; +pub const capabilities: config.Settings.Capabilities = if (desktop) window_capabilities else frontend; /// What the live view's frontend takes: a window's, or a terminal's /// (`Pardes.frontend`, which its client says, Event.frontend). -pub fn viewCapabilities(p: *const Pardes) config.Runtime.Capabilities { +pub fn viewCapabilities(p: *const Pardes) config.Settings.Capabilities { if (comptime !desktop) return frontend; return if (p.view().frontend.windowed) window_capabilities else terminal_capabilities; } @@ -136,10 +136,10 @@ fn manualBuiltinList() []const type { } } -fn settingList() []const config.Runtime.Setting { +fn settingList() []const config.Settings.Setting { comptime { - var list: []const config.Runtime.Setting = &.{}; - for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { + var list: []const config.Settings.Setting = &.{}; + for (config.Settings.settings) |setting| if (setting.enabled(capabilities)) { list = list ++ .{setting}; }; return list; @@ -175,7 +175,7 @@ pub const registry = struct { } /// `here` for a frontend of these capabilities, windowed or not. - pub fn hereFor(b: Builtin(), caps: config.Runtime.Capabilities, windowed: bool) bool { + pub fn hereFor(b: Builtin(), caps: config.Settings.Capabilities, windowed: bool) bool { inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return !@hasDecl(T, "in_window") or windowed; inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return setting.enabled(caps); unreachable; @@ -749,13 +749,13 @@ pub const Petscii = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { // `on|off` sets it, as the tag's `petscii:on` reads; none flips it. - const now = if (c.pane.addon) |k| k.art.glyph else panes.Term.petscii(c.pane.terminal) orelse false; + const now = if (c.pane.addon) |k| k.art.glyph else c.pane.terminal != null and c.pane.term_petscii; if (c.arg != null) { const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return; if ((want == .on) == now) return; } if (c.pane.addon) |k| k.art.glyph = !k.art.glyph; - if (c.pane.terminal) |state| panes.Term.togglePetscii(state); + if (c.pane.terminal != null) c.pane.term_petscii = !c.pane.term_petscii; } }; @@ -1131,13 +1131,13 @@ pub const Collapse = struct { } }; -/// Unattach a pane from the pane it answers for: it stays where it is, a +/// Undock a pane from the pane it answers for: it stays where it is, a /// pane of its own, and the next search from that pane opens another /// under it. -pub const Unattach = struct { +pub const Undock = struct { pub fn run(c: Ctx) void { - if (c.pane.attached_to == null) return c.p.reportFailure(c.id, "Unattach: not attached to a pane"); - c.pane.attached_to = null; + if (c.pane.docked_to == null) return c.p.reportFailure(c.id, "Undock: not docked to a pane"); + c.pane.docked_to = null; } }; @@ -1873,7 +1873,7 @@ fn testDump(buf: []u8) ![]const u8 { test "capabilities exactly gate setting builtins" { const Builtin = registry.Builtin(); - for (config.Runtime.settings) |setting| { + for (config.Settings.settings) |setting| { const registered = std.meta.stringToEnum(Builtin, setting.word) != null; try std.testing.expectEqual(setting.enabled(capabilities), registered); } diff --git a/core/builtins_json.zig b/core/builtins_json.zig index 3773e5ae..23e15098 100644 --- a/core/builtins_json.zig +++ b/core/builtins_json.zig @@ -65,11 +65,11 @@ pub fn write(w: *std.Io.Writer, addon_sources: []const []const u8) std.Io.Writer try w.writeAll(if (builtins.registry.takesArg(b)) "true" else "false"); try w.writeAll(", \"scope\": "); try str(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", .{}, w); - const setting = config.Runtime.find(name); + const setting = config.Settings.find(name); try w.writeAll(", \"setting\": "); try w.writeAll(if (setting != null) "true" else "false"); try w.writeAll(", \"choices\": "); - if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); + if (setting) |s| if (config.Settings.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); var buf: [2048]u8 = undefined; const doc = if (setting) |s| s.doc else ctl.summaryOf(name, &buf); try w.writeAll(", \"doc\": "); diff --git a/core/config.zig b/core/config.zig index 792a7e62..3dbfe566 100644 --- a/core/config.zig +++ b/core/config.zig @@ -39,7 +39,7 @@ comptime { @setEvalBranchQuota(20_000); // A path here is a leaf: no builtin's path is it or runs past it, and // none of it is a builtin's whole path. The library has no builtins. - if (!@import("pardes_config").lib) for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + if (!@import("pardes_options").lib) for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); }; @@ -79,7 +79,7 @@ pub const leader_path = paths: { .Mode = null, .Togglettymode = null, .Collapse = null, - .Unattach = null, + .Undock = null, .Undo = null, .Edit = null, .Redo = null, @@ -600,7 +600,7 @@ pub const delete_word_forward: []const Chord = &.{ .{ .cp = 'd', .alt = true }, pub const kill_to_line_start: []const Chord = &.{.{ .cp = 'u', .ctrl = true }}; pub const kill_to_line_end: []const Chord = &.{.{ .cp = 'k', .ctrl = true }}; -pub const Runtime = struct { +pub const Settings = struct { theme: usize = 0, wrap: bool = true, debug: bool = false, @@ -662,7 +662,7 @@ pub const Runtime = struct { tab: u16 = tab_width, callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, - /// A setting that is one of a few words, each an enum field of Runtime. + /// A setting that is one of a few words, each an enum field of Settings. pub const Choice = enum { pet }; pub const Pet = enum { off, cat, frog }; @@ -710,7 +710,7 @@ pub const Runtime = struct { }; // Validate the complete request before changing any member. - pub fn requestFont(state: *Runtime, path: []const u8, name: []const u8, size_hundredths: u16) bool { + pub fn requestFont(state: *Settings, path: []const u8, name: []const u8, size_hundredths: u16) bool { if (path.len > state.font.requested_path.bytes.len or name.len > state.font.requested_name.bytes.len) return false; if (size_hundredths != 0 and (size_hundredths < 800 or size_hundredths > 7200)) return false; @@ -834,7 +834,7 @@ pub const Runtime = struct { } /// `home`: what `~` is (the session's: Pardes.session_home). - pub fn apply(state: *Runtime, tape: *pardes.tape.Tape, setting: Setting, argument: ?[]const u8, home: ?[]const u8) bool { + pub fn apply(state: *Settings, tape: *pardes.tape.Tape, setting: Setting, argument: ?[]const u8, home: ?[]const u8) bool { switch (setting.action) { // Every toggle names a bool field of its own, so one line covers // all of them and a new toggle needs no arm here. Bare, a toggle @@ -903,7 +903,7 @@ pub const Runtime = struct { return switch (action) { .toggle => "on, off", .choice => |which| switch (which) { - inline else => |field| comptime words.of(@FieldType(Runtime, @tagName(field))), + inline else => |field| comptime words.of(@FieldType(Settings, @tagName(field))), }, else => null, }; @@ -970,7 +970,7 @@ pub const Runtime = struct { default_dump_dir: []const u8 = "", native_images: bool = false, capabilities: Capabilities, - state: *const Runtime, + state: *const Settings, /// The `LocationsConfig` argument in effect, as it would be typed. locations: []const u8 = "", }; @@ -1068,7 +1068,7 @@ pub const Runtime = struct { } test "a toggle flips when bare and sets when told on or off" { - var state: Runtime = .{}; + var state: Settings = .{}; const verbose = find("Verbose").?; try std.testing.expect(state.verbose); // Bare, it flips: that is what a tagline word does. @@ -1090,7 +1090,7 @@ pub const Runtime = struct { } test "simple setting application mutates only its plain field" { - var state: Runtime = .{}; + var state: Settings = .{}; try std.testing.expect(apply(&state, &pardes.tape.none, find("Wrap").?, null, null)); try std.testing.expect(!state.wrap); try std.testing.expect(apply(&state, &pardes.tape.none, find("Shell").?, " fish\n", null)); @@ -1100,7 +1100,7 @@ pub const Runtime = struct { test "tagline size validates before mutating live state" { const setting = find("TaglineSize").?; - var state: Runtime = .{}; + var state: Settings = .{}; for ([_][]const u8{ "1", " 82\n", "100" }) |argument| { try std.testing.expect(apply(&state, &pardes.tape.none, setting, argument, null)); @@ -1116,7 +1116,7 @@ pub const Runtime = struct { test "window opacity defaults to opaque validates atomically and retries" { const setting = find("WindowOpacity").?; - var state: Runtime = .{}; + var state: Settings = .{}; try std.testing.expectEqual(@as(u8, 100), state.window_opacity); try std.testing.expect(state.window_opacity_pending); try std.testing.expectEqual(Capability.window_opacity, availability(setting.action).?); @@ -1141,7 +1141,7 @@ pub const Runtime = struct { } test "font request tuple rejects atomically" { - var state: Runtime = .{}; + var state: Settings = .{}; try std.testing.expect(requestFont(&state, "/fonts/old.ttf", "Old", 1200)); var too_long: [256]u8 = @splat('x'); try std.testing.expect(!requestFont(&state, "/fonts/new.ttf", &too_long, 1800)); @@ -1168,7 +1168,7 @@ pub const Runtime = struct { // The switches, Theme, Shell, Pager and the shell's own lines are // test/behaviour/settings.zig's, read through the root ctl and the // +DumpConfig pane. - var state: Runtime = .{}; + var state: Settings = .{}; // Every setting, every context line: the report outgrows 4K. var storage: [8192]u8 = undefined; const context: ReportContext = .{ @@ -1219,7 +1219,7 @@ pub const Runtime = struct { "# Native images: on\n", }) |expected| try std.testing.expect(std.mem.indexOf(u8, report, expected) != null); - var defaults: Runtime = .{}; + var defaults: Settings = .{}; var defaults_context = context; defaults_context.startup_config_path = null; defaults_context.platform = "tui"; @@ -1693,7 +1693,7 @@ test "wheel drift guard" { } test { - _ = Runtime; + _ = Settings; _ = User; } @@ -1838,14 +1838,14 @@ test "reference.typ's #fstree is the tree the session serves, file for file" { } test "CallstackDepth is bounded and keeps the last valid runtime limit" { - var state: Runtime = .{}; + var state: Settings = .{}; try std.testing.expectEqual(@as(u8, 8), state.callstack_depth); for ([_][]const u8{ "1", "8", "16", "64" }) |value| { - try std.testing.expect(Runtime.apply(&state, &pardes.tape.none, Runtime.find("CallstackDepth").?, value, null)); + try std.testing.expect(Settings.apply(&state, &pardes.tape.none, Settings.find("CallstackDepth").?, value, null)); try std.testing.expectEqual(try std.fmt.parseInt(u8, value, 10), state.callstack_depth); } for ([_][]const u8{ "0", "65", "256", "-1", "+8", "1_6", "eight", "" }) |value| { - try std.testing.expect(!Runtime.apply(&state, &pardes.tape.none, Runtime.find("CallstackDepth").?, value, null)); + try std.testing.expect(!Settings.apply(&state, &pardes.tape.none, Settings.find("CallstackDepth").?, value, null)); try std.testing.expectEqual(@as(u8, 64), state.callstack_depth); } } diff --git a/core/dump.zig b/core/dump.zig index 1616f557..eb0ef263 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -261,7 +261,9 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 { /// 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; + // Under bytes, each terminal whole (as the join's step reloaded it on + // every side: panes.reloadTerminals), its sequence in flight with it. + slim_terminals = p.tape.screen_state; defer slim_terminals = false; // The join's file reads are the session's host's, between its steps: // with its io, which the core's tape holds (a walk's hook takes no more). @@ -270,7 +272,8 @@ pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![ return dumpWith(p, deferred); } -/// `dumpJoin`'s and `dumpExit`'s: a terminal dumps its size, not its emulator. +/// `dumpJoin`'s under screen state 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), /// read with this io. @@ -406,6 +409,7 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: for (others) |o| gpa.free(o.panes); gpa.free(others); l.shared.shrinkRetainingCapacity(at); + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.context.reload(p.tree_sitter_gpa, f.path, f.content, f.revision); p.readSessionFacts(); return p; } @@ -491,6 +495,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?* try views.undumpedOld(p, others, gpa); } l.made.shrinkRetainingCapacity(at); + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.context.reload(p.tree_sitter_gpa, f.path, f.content, f.revision); p.readSessionFacts(); return p; } @@ -708,11 +713,11 @@ pub fn savePane(gpa: std.mem.Allocator, pane: *pardes.panes.Pane, slim: bool) ![ // 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 docked_to = pane.docked_to; const terminal = pane.terminal; defer { pane.cwd = cwd; - pane.attached_to = attached_to; + pane.docked_to = docked_to; pane.terminal = terminal; } if (cwd == .inherited) { @@ -720,7 +725,7 @@ pub fn savePane(gpa: std.mem.Allocator, pane: *pardes.panes.Pane, slim: bool) ![ const dir = pane.cwdSlice(); pane.cwd = .{ .owned = @constCast(dir) }; } - pane.attached_to = null; + pane.docked_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); @@ -985,7 +990,7 @@ test "a session with every column it may hold dumps and restores them all" { } 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 th = @import("ninep/harness.zig"); const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -1037,7 +1042,7 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and 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 th = @import("ninep/harness.zig"); const node = if (word == .Del or word == .get) ctlfs.Node.of(restored.panes[id].?.serial, .ctl) else @@ -1171,7 +1176,7 @@ test "a session's byte dump read by name, field by field as another build reads 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 th = @import("ninep/harness.zig"); const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("kept in a .dump\n"); @@ -1200,7 +1205,7 @@ test "an old dump's file, a byte dump, is read by -l and by a Restore of its pat try std.testing.expectEqualSlices(u8, bytes, again); } -test "restored syntax context caches are rebuilt rather than loaded with the core allocator" { +test "restored syntax context caches are rebuilt from the text 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"); @@ -1237,9 +1242,13 @@ test "restored syntax context caches are rebuilt rather than loaded with the cor defer gpa.free(bytes); const q = try load(gpa, opts, bytes, null); defer q.deinit(); + // This build's: the revision kept, the declarations parsed again from + // the text, with the syntax allocator. + const want = try pardes.syntax.contextDeclarations(syntax_gpa.allocator(), f.path, f.content); + defer syntax_gpa.allocator().free(want); 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); + try std.testing.expectEqual(f.context.revision, file.context.revision); + try std.testing.expectEqualSlices(pardes.syntax.ContextDeclaration, want, file.context.declarations); }; } diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig index 43006503..9f1f7862 100644 --- a/core/edit_cmd.zig +++ b/core/edit_cmd.zig @@ -452,7 +452,7 @@ fn commit(p: *Pardes, pd: *Pending, outputs: []const []const u8) void { } const testing = std.testing; -const th = @import("ninep/testing.zig"); +const th = @import("ninep/harness.zig"); const tree = @import("ninep/tree.zig"); /// The answer of the Edit waiting on its commands: as a host's worker diff --git a/core/exec.zig b/core/exec.zig index 687faa98..1ec47eb3 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -288,7 +288,7 @@ pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { // A switch (Verbose, Wrap) clicked with some other text // selected flips, as it does bare: only `on` or `off` is an argument // for it. What a ctl write gives it is checked strictly instead. - if (config.Runtime.find(commandText(t))) |setting| switch (setting.action) { + if (config.Settings.find(commandText(t))) |setting| switch (setting.action) { .toggle => if (!std.mem.eql(u8, a, "on") and !std.mem.eql(u8, a, "off")) return txt, else => {}, }; @@ -688,7 +688,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi // A builtin or setting this build lacks (Fonts on a terminal) is said, // never run as a shell command. const word = cmd[0 .. std.mem.indexOfAny(u8, cmd, " \t") orelse cmd.len]; - if (builtins.absentWhy(word) orelse if (config.Runtime.find(word) != null) @as([]const u8, "GUI-only") else null) |why| { + if (builtins.absentWhy(word) orelse if (config.Settings.find(word) != null) @as([]const u8, "GUI-only") else null) |why| { var said: pardes.Kind.Buf(96) = .{}; p.reportFailure(id, said.print("{s} is {s}, invalid here", .{ word, why })); return null; @@ -937,7 +937,7 @@ fn applyInitText(p: *Pardes, text: []const u8, settings_only: bool) void { // `#` starts a comment only at a line's start: a value may hold one // (`#ff0000`). if (word.len == 0 or isComment(word)) continue; - const setting = config.Runtime.find(word[0 .. std.mem.indexOfAny(u8, word, " \t") orelse word.len]); + const setting = config.Settings.find(word[0 .. std.mem.indexOfAny(u8, word, " \t") orelse word.len]); // Saved in a pane, its settings run again and its commands do not: // a word that is neither (a typo) is still said, as at startup. if (settings_only and setting == null and std.meta.stringToEnum(Builtin, word[0 .. std.mem.indexOfAny(u8, word, " \t+") orelse word.len]) != null) continue; @@ -996,7 +996,7 @@ pub fn runBuiltinFrom(p: *Pardes, b: Builtin, id: usize, txt: []const u8, arg: ? builtins.registry.dispatch(b, c); } -pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[]const u8) void { +pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[]const u8) void { const v = p.view(); const previous_tagline_percent = p.settings.font.tagline_percent; switch (setting.action) { @@ -1015,7 +1015,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] }, .font => { if (comptime !font_picker) return; - const spec = config.Runtime.FontSpec.parse(arg orelse return) orelse return; + const spec = config.Settings.FontSpec.parse(arg orelse return) orelse return; // The session's machine's fonts, a question to its disk: a // client's replay takes the session's answer, never its own. const found = pardes.tape.site(.fonts, p.scratch.allocator(), fontNamed, .{ p.scratch.allocator(), spec.name }); @@ -1039,7 +1039,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] var text: pardes.Kind.Buf(340) = .{}; return p.reportFailure(v.active, text.print("Shell: {s}", .{refused})); } - if (!p.settings.apply(p.tape, setting, want, p.sessionHome())) p.reportFailure(v.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); + if (!p.settings.apply(p.tape, setting, want, p.sessionHome())) p.reportFailure(v.active, "Shell: takes " ++ comptime config.Settings.takes(.shell).?); }, // Bare, each says its value, as acme's Tab says the width. inline .tab, .callstack_depth => |_, tag| if (arg == null) { @@ -1047,14 +1047,14 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] return p.setMessage(.at(v.active), said.print("{s} {d}", .{ setting.word, @field(p.settings, @tagName(tag)) })); } else if (!p.settings.apply(p.tape, setting, arg, p.sessionHome())) { var said: pardes.Kind.Buf(96) = .{}; - p.reportFailure(v.active, said.print("{s}{s}: takes {s}", .{ setting.word, if (tag == .tab) ": invalid tab width" else "", comptime config.Runtime.takes(tag).? })); + p.reportFailure(v.active, said.print("{s}{s}: takes {s}", .{ setting.word, if (tag == .tab) ": invalid tab width" else "", comptime config.Settings.takes(tag).? })); }, // Said with what it takes: its words, its range. else => if (!p.settings.apply(p.tape, setting, arg, p.sessionHome())) { var buf: [160]u8 = undefined; var text: std.Io.Writer = .fixed(&buf); // A list of values too long for the row is cut. - (if (config.Runtime.takes(setting.action)) |values| text.print("{s}: takes {s}", .{ setting.word, values }) else text.print("{s}: does not take that value", .{setting.word})) catch {}; + (if (config.Settings.takes(setting.action)) |values| text.print("{s}: takes {s}", .{ setting.word, values }) else text.print("{s}: does not take that value", .{setting.word})) catch {}; p.reportFailure(v.active, text.buffered()); }, } diff --git a/core/fs.zig b/core/fs.zig index 0a10825d..0797beb0 100644 --- a/core/fs.zig +++ b/core/fs.zig @@ -11,7 +11,7 @@ const modal = @import("modal.zig"); const look = @import("look.zig"); pub const tree = @import("ninep/tree.zig"); const sources_fs = @import("ninep/sources.zig"); -const th = @import("ninep/testing.zig"); +const th = @import("ninep/harness.zig"); const Pardes = pardes.Pardes; const MAX_PANES = pardes.MAX_PANES; diff --git a/core/keys.zig b/core/keys.zig index 92e78b0e..72e3bb3b 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -632,7 +632,7 @@ test "Del from a key asks which neighbour takes the rows; nothing else asks" { p.newScratchBelow(foot); const tail = p.view().active; { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const asked = foot; p.view().active = asked; p.sync(); diff --git a/core/layout.zig b/core/layout.zig index 6ce0845f..9c99dc7d 100644 --- a/core/layout.zig +++ b/core/layout.zig @@ -339,7 +339,7 @@ pub fn movePane(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) void { for (moved[0..count], 0..) |m, j| insert(p, placement.preview_col, j, m); if (count > 1) setColumnWeights(p, placement.preview_col, &heights); if (source_multi) setColumnWeights(p, src.col, &heights); - if (owner != null) p.panes[id].?.attached_to = null; + if (owner != null) p.panes[id].?.docked_to = null; return; }; const af = findPane(p, above) orelse return; @@ -367,7 +367,7 @@ pub fn movePane(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) void { const pane = p.panes[id].?; // Still right under its owner's group: resized there. Anywhere // else it is a pane of its own. - if (af.col != (findPane(p, o) orelse return).col or !descends(p, above, o)) pane.attached_to = null; + if (af.col != (findPane(p, o) orelse return).col or !descends(p, above, o)) pane.docked_to = null; } } @@ -1115,7 +1115,7 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { // ---- Attached panes ---- // // A results pane (+Search, +Callstack, +Diff, +Errors) is ATTACHED to the -// pane it answers for, its owner (Pane.attached_to). The owner and what is +// pane it answers for, its owner (Pane.docked_to). The owner and what is // attached to it, and what is attached to those (a preview under a // +Search), are a GROUP: contiguous in one column, the owner first. A group // is one place to everything else in the layout: an unrelated pane is never @@ -1126,7 +1126,7 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { /// The slot of `id`'s owner, when `id` is attached to a live pane. pub fn ownerOf(p: *const Pardes, id: usize) ?usize { - const serial = (p.panes[id] orelse return null).attached_to orelse return null; + const serial = (p.panes[id] orelse return null).docked_to orelse return null; for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.serial == serial and i != id) return i; return null; } @@ -1168,10 +1168,10 @@ pub fn groupEnd(p: *const Pardes, c: usize, idx: usize) usize { pub fn keepGroups(p: *Pardes) void { for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n], 0..) |id, k| { const pane = p.panes[id] orelse continue; - if (pane.attached_to == null) continue; + if (pane.docked_to == null) continue; const kept = if (ownerOf(p, id)) |owner| k > 0 and descends(p, p.view().cols[c].panes[k - 1], owner) else false; if (kept) continue; - pane.attached_to = null; + pane.docked_to = null; }; } @@ -1206,7 +1206,7 @@ pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) insert(p, f.col, groupEnd(p, f.col, f.idx), id); g.vweight = @floatFromInt(oh - give); nw.vweight = @floatFromInt(give); - nw.attached_to = o.serial; + nw.docked_to = o.serial; compute(p); return true; } @@ -1991,9 +1991,9 @@ test "an attachment survives Dump and Restore, and one left away from its owner const restored = try dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqual(@as(?usize, 0), ownerOf(restored, s)); - // Unattach: a pane of its own where it stands. - pardes.exec.runBuiltin(p, .Unattach, s, "", null); - try std.testing.expect(p.panes[s].?.attached_to == null); + // Undock: a pane of its own where it stands. + pardes.exec.runBuiltin(p, .Undock, s, "", null); + try std.testing.expect(p.panes[s].?.docked_to == null); // Put above its owner by a route that does not carry groups: detached. const t = try testAttachment(p); try std.testing.expect(attachFrom(p, 0, t, 8, 0)); @@ -2001,7 +2001,7 @@ test "an attachment survives Dump and Restore, and one left away from its owner removePane(p, t); insert(p, 0, 0, t); compute(p); - try std.testing.expect(p.panes[t].?.attached_to == null); + try std.testing.expect(p.panes[t].?.docked_to == null); } test "a new column takes width only from the column that created it" { diff --git a/core/lib_editor.zig b/core/lib_editor.zig index c459241a..3fe631af 100644 --- a/core/lib_editor.zig +++ b/core/lib_editor.zig @@ -3,7 +3,7 @@ //! true`, docs/next-editor.md). In-memory editing with helix's keys: no //! files, commands, builtins, prompts or views, which come back to the //! caller as an `action`. Nothing is copied here: a key runs the editor's -//! own normal.zig and edit.zig, built with `pardes_config.lib`, where a +//! own normal.zig and edit.zig, built with `pardes_options.lib`, where a //! text has no pane and its characters are its own. //! //! The editor is a value of plain data (`Editor(capacity)`): no pointer, diff --git a/core/look.zig b/core/look.zig index f7084079..1023a532 100644 --- a/core/look.zig +++ b/core/look.zig @@ -2302,7 +2302,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 var fx: DiffFixture = undefined; try fx.init(true, &.{.{ "src/x.zig", numbered }}, diff_text); defer fx.tmp.cleanup(); - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); // `column` -1: wherever a click puts it, every other way the same. const Case = struct { text: []const u8, name: []const u8, row: u16, col: u16, sweep: [2]u16, line: i32, column: i32 }; const cases = [_]Case{ @@ -2391,7 +2391,7 @@ test "a tag word looked at by a click and by Enter is one record to an event rea var fx: DiffFixture = undefined; try fx.init(true, &.{.{ "src/x.zig", "line one\n" }}, diff_text); defer fx.tmp.cleanup(); - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); const pane = try fx.open(p, diff_text); diff --git a/core/memory.zig b/core/memory.zig index c628ae49..0e0dba29 100644 --- a/core/memory.zig +++ b/core/memory.zig @@ -1,6 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); -const config = @import("pardes_config"); +const config = @import("pardes_options"); const KiB = 1024; const MiB = 1024 * KiB; diff --git a/core/mouse.zig b/core/mouse.zig index 3d7c5af9..1882b691 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -184,7 +184,7 @@ fn programWheel(p: *Pardes, id: usize, m: Mouse, col: u16, row: u16) bool { .wheel_left => .wheel_left, else => .wheel_right, }; - const bytes = panes.Term.wheel(pane.terminal.?, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; + const bytes = panes.Term.wheel(pane.terminal.?, &pane.term_mouse, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; for (0..@intCast(config.wheel_rows)) |_| p.emitWrite(id, bytes); return true; } @@ -247,8 +247,11 @@ fn kindMouse(p: *Pardes, m: Mouse) bool { if (m.kind == .press) v.active = id; if (m.kind == .press and m.button != .wheel_up and m.button != .wheel_down and m.button != .wheel_left and m.button != .wheel_right) v.kind_grab = @intCast(id); if (m.kind == .release) v.kind_grab = null; - const col = std.math.clamp(m.col, x0, r.x + r.w -| 1) - x0; - const row = std.math.clamp(m.row, top, r.y + r.h -| 1) - top; + // Grabbed, it may be anywhere, and the pane since made too narrow + // or short for a cell of body (a resize, a pane added above): its + // body's last cell, the first of none. + const col = @min(m.col -| x0, (r.x + r.w) -| x0 -| 1); + const row = @min(m.row -| top, (r.y + r.h) -| top -| 1); return pardes.Kind.mouse(p, id, m, col, row); } kindLeave(p); @@ -298,7 +301,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { }; if (m.kind == .press) grab.held |= bit; if (m.kind == .release) grab.held &= ~bit; - const bytes = panes.Term.mouse(pane.terminal.?, &buf, action, button, mods, col, row, grab.held != 0); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &buf, action, button, mods, col, row, grab.held != 0); if (bytes.len > 0) p.emitWrite(grab.id, bytes); if (grab.held == 0) v.mouse_grab = null; return true; @@ -322,7 +325,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { pane.focus = .body; pane.closePrompt(); v.mouse_grab = .{ .id = id, .serial = pane.serial, .held = bit, .unshift = shifted_to_program }; - const bytes = panes.Term.mouse(pane.terminal.?, &buf, .press, button, mods, cell.col, cell.row, true); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &buf, .press, button, mods, cell.col, cell.row, true); if (bytes.len > 0) p.emitWrite(id, bytes); return true; }, @@ -330,7 +333,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { // pardes's. .release, .drag => return false, .motion => { - const bytes = panes.Term.mouse(pane.terminal.?, &buf, .motion, null, mods, cell.col, cell.row, false); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &buf, .motion, null, mods, cell.col, cell.row, false); if (bytes.len > 0) p.emitWrite(id, bytes); // Under 1003 the move is the program's; below that pardes // hovers as ever. @@ -432,7 +435,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { const row = @max(0, pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows)); var mb: [64]u8 = undefined; for ([_]panes.Term.MouseAction{ .press, .release }) |action| { - const bytes = panes.Term.mouse(pane.terminal.?, &mb, action, .left, .{}, col, row, action == .press); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &mb, action, .left, .{}, col, row, action == .press); if (bytes.len > 0) p.emitWrite(s.id, bytes); } } @@ -1497,7 +1500,7 @@ test "mouse thumb buttons navigate once and clear selection gestures" { } test "a chorded exec an event reader holds is told with its argument, and written back runs with it" { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const p = try th.withFile(std.testing.allocator, "Msg said\narg-text\n"); defer p.deinit(); const serial = p.panes[0].?.serial; diff --git a/core/ninep/addr.zig b/core/ninep/addr.zig index 72a2d815..fd343363 100644 --- a/core/ninep/addr.zig +++ b/core/ninep/addr.zig @@ -319,7 +319,7 @@ pub const Addr = struct { }; const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const tree = @import("tree.zig"); const Node = tree.Node; const E = tree.E; diff --git a/core/ninep/cols.zig b/core/ninep/cols.zig index 561a5ffa..88d8ef88 100644 --- a/core/ninep/cols.zig +++ b/core/ninep/cols.zig @@ -241,7 +241,7 @@ pub fn remove(p: *Pardes, req: Req, serial: u32, file: tree.ColFile) Reply { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const Node = tree.Node; test "New written to a column's exec makes its scratch in the session's directory, as tagexec's does" { diff --git a/core/ninep/ctl.zig b/core/ninep/ctl.zig index 302b916a..7b4e2754 100644 --- a/core/ninep/ctl.zig +++ b/core/ninep/ctl.zig @@ -298,7 +298,7 @@ pub fn captured(p: *Pardes, req: Req, id: usize, exec: bool, text: []const u8, i // ...and one that takes none, written with one (`Config extra`): // refused as a ctl's is, not run as a shell command of that name. if (std.mem.indexOfAny(u8, cmd, " \t")) |sp| if (std.meta.stringToEnum(Builtin, cmd[0..sp])) |b| { - if (!builtins.registry.takesArg(b) and config.Runtime.find(cmd[0..sp]) == null) { + if (!builtins.registry.takesArg(b) and config.Settings.find(cmd[0..sp]) == null) { p.fs.results_len = 0; return refuse(p, req, "wrong #args in control message", cmd); } @@ -535,7 +535,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? // A setting this build's frontend cannot show (Lift, GripWidth on a // terminal, the window's own words in a terminal's view) is known, // and says so rather than sound misspelt. - if (builtins.absentWhy(word) orelse if (config.Runtime.find(word) != null or std.meta.stringToEnum(Builtin, word) != null) @as([]const u8, "GUI-only") else null) |absent| { + if (builtins.absentWhy(word) orelse if (config.Settings.find(word) != null or std.meta.stringToEnum(Builtin, word) != null) @as([]const u8, "GUI-only") else null) |absent| { var why: pardes.Kind.Buf(64) = .{}; // EINVAL, a request this build cannot take, in words 9ns reads // as that: `invalid`. @@ -553,7 +553,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? ": write it to pane/<n>/ctl"); if (arg.len > 0 and !builtins.registry.takesArg(b)) return refuse(p, req, "wrong #args in control message", line); if (arg.len == 0 and builtins.registry.requiresArg(b)) return refuse(p, req, "wrong #args in control message", line); - const setting = config.Runtime.find(word) orelse return null; + const setting = config.Settings.find(word) orelse return null; const takes = switch (setting.action) { .theme => if (pardes.colors.themeIndex(arg) != null) true else { // `refuse` quotes the line after it, all in the 128 bytes an @@ -565,7 +565,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? var why: pardes.Kind.Buf(256) = .{}; return refuse(p, req, why.print(head ++ "{s}" ++ tail, .{pardes.colors.themesNear(near[0..@min(room, near.len)], arg)}), arg); }, - .font => config.Runtime.FontSpec.parse(arg) != null, + .font => config.Settings.FontSpec.parse(arg) != null, // Bare, it says the width, as from a pane's exec. .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, @@ -578,7 +578,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? var why: pardes.Kind.Buf(160) = .{}; // The offending word is the value: quoted, so two bad values read, // and log, as two. - return refuseQuoting(p, req, if (config.Runtime.takes(setting.action)) |values| + return refuseQuoting(p, req, if (config.Settings.takes(setting.action)) |values| why.print("bad value in control message; takes {s}", .{values}) else "bad value in control message", arg, ""); @@ -628,13 +628,13 @@ fn writeSettings(p: *Pardes, w: *std.Io.Writer) !void { /// The setting words of `s`, one a line, those a frontend of `caps` takes /// (the root ctl's: the live view's), and the session's LocationsConfig. -fn writeSettingsFor(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer, caps: config.Runtime.Capabilities) !void { +fn writeSettingsFor(p: *Pardes, s: *const config.Settings, w: *std.Io.Writer, caps: config.Settings.Capabilities) !void { // DumpConfig's words: a `# Word unsupported` comment for what `caps` lacks. var dump_dir: [1024]u8 = undefined; var located_buf: [256]u8 = undefined; var located: std.Io.Writer = .fixed(&located_buf); try p.locations_config.write(&located); - try config.Runtime.writeSettings(w, .{ + try config.Settings.writeSettings(w, .{ .locations = located.buffered(), .theme_name = p.theme().name, .theme_file = pardes.colors.loadedThemeFile(p), @@ -879,7 +879,7 @@ fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void { }); // A setting that chooses among words: the words, comma-joined. Bare, // it steps to the next of them (a two-valued one flips). - if (config.Runtime.find(@tagName(b))) |setting| if (config.Runtime.choices(setting.action)) |values| { + if (config.Settings.find(@tagName(b))) |setting| if (config.Settings.choices(setting.action)) |values| { try w.writeByte(' '); var parts = std.mem.splitSequence(u8, values, ", "); var first = true; @@ -887,7 +887,7 @@ fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void { }; // Then ` -- ` and what it does: a setting's doc, else its source's. var summary_buf: [2048]u8 = undefined; - const summary = if (config.Runtime.find(@tagName(b))) |setting| setting.doc else summaryOf(@tagName(b), &summary_buf); + const summary = if (config.Settings.find(@tagName(b))) |setting| setting.doc else summaryOf(@tagName(b), &summary_buf); if (summary.len > 0) { // The sentence whole unless it is long, then cut between words. const kept = @import("../Messages.zig").clip(summary, 240); @@ -1323,7 +1323,7 @@ pub fn get(p: *Pardes, pane: *Pane) GetError!void { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const call = th.call; const rd = th.rd; const wr = th.wr; @@ -1374,7 +1374,7 @@ test "commands lists every builtin with its argument and the ctl that takes it" const b = std.meta.stringToEnum(Builtin, words.next().?).?; if (builtins.registry.takesArg(b)) try testing.expectEqualStrings("arg", words.next().?); try testing.expectEqualStrings(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", words.next().?); - if (config.Runtime.find(@tagName(b))) |s| if (config.Runtime.choices(s.action) != null) try testing.expect(words.next() != null); + if (config.Settings.find(@tagName(b))) |s| if (config.Settings.choices(s.action) != null) try testing.expect(words.next() != null); // Then, where the source has one, ` -- ` and what it does. if (words.next()) |dashes| try testing.expectEqualStrings("--", dashes); } @@ -1766,7 +1766,7 @@ test "after a ThemeFile the root ctl and DumpConfig say ThemeFile and its path, try testing.expect(std.mem.indexOf(u8, settings, "Theme mine") == null); var storage: [16384]u8 = undefined; var out: std.Io.Writer = .fixed(&storage); - try config.Runtime.writeReport(&out, .{ + try config.Settings.writeReport(&out, .{ .startup_config_path = null, .platform = @tagName(pardes.platform), .theme_name = p.theme().name, @@ -2490,7 +2490,7 @@ test "every word's /commands description is its own doc comment's first sentence continue; }; const word = line[0..std.mem.indexOfScalar(u8, line, ' ').?]; - if (config.Runtime.find(word)) |setting| { + if (config.Settings.find(word)) |setting| { try testing.expect(std.mem.endsWith(u8, line, setting.doc)); continue; } @@ -2890,7 +2890,7 @@ test "the init file reads past a BOM, and every line it fails is a notice and an } test "a setting the other frontend has is passed over in the init file, not failed" { - const other = for (config.Runtime.settings) |s| { + const other = for (config.Settings.settings) |s| { if (!s.enabled(pardes.builtins.capabilities)) break s.word; } else return; // this frontend has them all var text: [64]u8 = undefined; diff --git a/core/ninep/events.zig b/core/ninep/events.zig index 93a1187a..1951a434 100644 --- a/core/ninep/events.zig +++ b/core/ninep/events.zig @@ -828,7 +828,7 @@ pub fn writeEvent(p: *Pardes, asked: Req, id: usize) Reply { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const call = th.call; const rd = th.rd; const wr = th.wr; diff --git a/core/ninep/testing.zig b/core/ninep/harness.zig index cf75d80d..cf75d80d 100644 --- a/core/ninep/testing.zig +++ b/core/ninep/harness.zig diff --git a/core/ninep/pane.zig b/core/ninep/pane.zig index 8be26602..1d514a3c 100644 --- a/core/ninep/pane.zig +++ b/core/ninep/pane.zig @@ -1031,7 +1031,7 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const call = th.call; const rd = th.rd; const wr = th.wr; diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index 6f3a8af0..26bb7661 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -469,7 +469,7 @@ pub fn writeData(p: *Pardes, req: Req, id: usize) Reply { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const events = @import("events.zig"); const call = th.call; const rd = th.rd; diff --git a/core/ninep/screen.zig b/core/ninep/screen.zig index 1e2791b1..1e31bac0 100644 --- a/core/ninep/screen.zig +++ b/core/ninep/screen.zig @@ -83,7 +83,7 @@ pub fn listenersText(p: *Pardes) std.Io.Writer.Error![]const u8 { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const fs = @import("../fs.zig"); const call = th.call; const rd = th.rd; diff --git a/core/ninep/sources.zig b/core/ninep/sources.zig index 1d804e31..540506d4 100644 --- a/core/ninep/sources.zig +++ b/core/ninep/sources.zig @@ -109,7 +109,7 @@ pub fn handle(p: *Pardes, req: Req) Reply { } const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const limits = @import("../memory.zig").limits; test "embedded sources appear under the root only when the build carries them" { diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig index d5a6b2fe..46a4e3d2 100644 --- a/core/ninep/tree.zig +++ b/core/ninep/tree.zig @@ -1504,7 +1504,7 @@ fn writeSend(p: *Pardes, req: Req) Reply { // ---- tests ---- const testing = std.testing; -const th = @import("testing.zig"); +const th = @import("harness.zig"); const config = @import("../config.zig"); const call = th.call; const rd = th.rd; diff --git a/core/panes.zig b/core/panes.zig index b928917a..fd152e1e 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -125,6 +125,12 @@ pub const Pane = struct { pub const Focus = enum { body, tag }; pub const SessionView = struct { wrap: bool = true, layered: bool = true, body_h: u32 = 0, tagline_h: u32 = 0, rect_h: u16 = 0 }; terminal: ?*Term.State = null, + /// Its terminal's, kept by the pane, which a rollback puts back, not by + /// the emulator, which none does (a speculation writes them): the grid + /// cell its program last heard the mouse at (motion is told once a + /// cell), and its kitty graphics drawn as glyph art (Petscii). + term_mouse: ?Term.Coordinate = null, + term_petscii: bool = false, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the @@ -144,7 +150,7 @@ pub const Pane = struct { /// closes with it (layout.zig, "Attached panes"). An owner that is /// gone, or a pane no longer right under its owner's group, leaves it /// an ordinary pane (layout.keepGroups). - attached_to: ?u32 = null, + docked_to: ?u32 = null, /// This pane is a query pane: its line 1 the query, its rows made live /// from a source (Query.zig, gpa-owned). query: ?*Query = null, @@ -960,15 +966,17 @@ pub const Pane = struct { /// replica by its authority (the next delta says), on such an authority /// once the step's unit is out (`resizeDeferred`). pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { - // A screen-state client's speculation does what its replay does - // (its selections, never the grid): it waits for no round trip. - if (!tape.screenState() and tape.authorityOnly("resize a terminal")) return; + // A client's speculation does what its replay does (its + // selections) but the grid: it waits for no round trip. Under bytes + // it owes the grid (`touchTerminal`): its input is replayed when + // confirmed, never taken as speculated (replica.zig `confirm`). const state = pane.terminal orelse return; if (cols != pane.cols) for (0..pane.sel.len) |button| { pane.clearPointerSelection(button); pane.sel[button].state = .none; }; if (tape.screenReplica()) return; + if (tape.speculating()) return tape.touchTerminal(); // A client typing at another size than the last typist's read // history rows its replay held as holes, and the rows came // renumbered (2026-10-30): the authority's waits for the unit. @@ -1111,6 +1119,31 @@ pub const Term = @import("Term.zig"); /// not follow the output (no memory for its pin), so it was reset. pub const positions_lost = "terminal edit position reset: out of memory"; +/// At a join (Core's openView, rejoinView): under bytes, every live +/// terminal made again from its own snapshot, on every side alike, the +/// session included (Term.reload): an emulator loaded from a snapshot holds +/// its rows in other pages than one fed from its start, and ghostty prunes +/// its history a page at a time, so the joiner, loaded from the session's +/// dump made next, and the replicas there before it, would part. The +/// session's snapshot's hash is taped, and each replica's own compared +/// with it: a check of the whole emulator at every join. +pub fn reloadTerminals(p: *Pardes) void { + if (tape.screenState()) return; + for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { + // Its cells' size in pixels as a feed sets it (`feedOutput`): a + // frontend's draw sets its own view's between steps (ansi.zig), a + // window's other than a terminal's, and the snapshot holds it. + Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); + const mine: ?u64 = Term.reload(state) catch null; + p.shell_rows.markStale(pane); + if (tape.value(.reload, sameHash, .{mine}) != mine) tape.diverged("a terminal reloaded at a join is not the session's"); + }; +} + +fn sameHash(h: ?u64) ?u64 { + return h; +} + /// The sizes steps gave terminals (`Pane.resizeGrid`), made: between /// units, on an authority with screen-state replicas (replica.Peers.unit). pub fn resizeDeferred(p: *Pardes) void { @@ -1141,16 +1174,17 @@ pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { return pane; } -/// A screen-state replica's emulators' allocator (`Term.State.gpa`): the C -/// heap, outside its rollback epoch: written by deltas while a copy is -/// held, no part of it is ever a copy's to save or put back. +/// A replica's emulators' allocator (`Term.State.gpa`): the C heap, +/// outside its rollback epoch: written (by the session's bytes or deltas) +/// while a copy is held, no part of it is ever a copy's to save or put +/// back, or the pages an emulator gains then are freed with the copy. pub const emulator_gpa = std.heap.c_allocator; /// What a terminal's emulator is made with, by `createTerminal` or a pane's /// load (dump.loadPane, a closed terminal brought back): `gpa`, but on a -/// screen-state replica `emulator_gpa`. +/// replica `emulator_gpa`. pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator { - return if (tape.screenReplica()) emulator_gpa else gpa; + return if (tape.replaying()) emulator_gpa else gpa; } // ---- the session's pane slots: making, finding, closing and freeing panes, and their prompts ---- @@ -1437,7 +1471,7 @@ pub fn removePane(p: *Pardes, id: usize, to: ?usize) error{OutOfMemory}!void { const pane = p.panes[id] orelse return; // What is attached to it closes with it, first, each giving its rows // back to it: then its rows, theirs among them, go where a pane's go. - for (0..p.panes.len) |k| if (p.panes[k]) |other| if (k != id and other.attached_to == pane.serial) { + for (0..p.panes.len) |k| if (p.panes[k]) |other| if (k != id and other.docked_to == pane.serial) { if (layout.ownerOf(p, k) != id) continue; try p.removePane(k, id); layout.compute(p); diff --git a/core/replica.zig b/core/replica.zig index c68848f2..a52061f4 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -40,8 +40,10 @@ const checked = builtin.mode == .debug or builtin.mode == .safe; const head_len = 6; // origin or client: u16le, seq: u32le /// A `stamp` frame (wire.zig): its header and the two clocks. const stamp_len = wire.header_len + 16; -/// Confirmed units fast-pathed under one copy before it is taken afresh: -/// a rollback replays them all. +/// Confirmed units kept under one copy before it is let go, at the next +/// unit that leaves nothing applied on top (free: it is the confirmed +/// state); a rollback replays them all, so with inputs applied on top all +/// the while it is put back at twice as many. const rebase_after = 32; /// A client compares its core's digest with the session's at most once in /// this many confirmed units (a unit that carries one, its state the @@ -568,6 +570,8 @@ pub const Stats = struct { /// the authority did not share), or another's unit first. mispredicted: u32 = 0, foreign: u32 = 0, + /// The copy put back at `rebase_after` kept units with inputs applied + /// on top: the kept units replayed, the inputs applied again. rebases: u32 = 0, units: u32 = 0, /// Its digest compared with the session's (a unit's, or quiet). @@ -905,7 +909,7 @@ pub const Replica = struct { // nothing ends on again (`neutral`); none, not known. r.last_digest.clearRetainingCapacity(); if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; - if (r.pending.items[0].terminal and r.applied > 1) { + if (r.pending.items[0].terminal and (r.applied > 1 or !r.t.screen_state)) { // Right, but what it did read a terminal: replayed later (a // rollback's `since`) it would read the deltas that came // after it. So it is taken now, over the emulator its step @@ -959,7 +963,12 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { + // A terminal's output is never taken so (the one rule): what it + // writes outside the copy is applied once, at its place, and much + // of it no digest covers (a colour set, a mode). + if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and + (r.t.screen_state or !tape.feedsTerminal(u.tape))) + { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the // copy is next put back. @@ -992,6 +1001,7 @@ pub const Replica = struct { // replayed by a rollback were, if at all, as they came). const check = ends != null and r.checkDue(); r.t.checks = check; + const writes = Term.writes; const replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { @@ -1015,10 +1025,15 @@ pub const Replica = struct { // or freed here, and is not put back with the copy: a rollback // replaying the unit again would close a terminal freed already (the // soak, a `Del` of the shell). Let go with the copy. + // The one rule: a unit that wrote an emulator (a terminal's output, + // a grid reflowed, a view moved, one reloaded at a join) wrote what + // no copy holds: kept, a rollback would replay it into what it + // wrote already (the bytes fed twice). It goes with the copy: the + // state is the confirmed one, nothing being on top. const c = r.core(); for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n; - if (retiring) { + if (retiring or (!r.t.screen_state and Term.writes != writes)) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -1035,22 +1050,23 @@ pub const Replica = struct { if (r.diverged == null) r.diverged = r.gpa.dupe(u8, why) catch return; } - /// A unit kept to replay when the copy is next put back; past - /// `rebase_after` of them, that is now (`toConfirmed`). + /// A unit kept to replay when the copy is next put back (`rebase_after`). fn keepSince(r: *Replica, unit: []const u8) void { const kept = r.gpa.dupe(u8, unit) catch return r.fail("out of memory"); r.since.append(r.gpa, kept) catch return r.fail("out of memory"); - if (r.since.items.len >= rebase_after) { - r.stats.rebases += 1; - // Nothing on top: it is the confirmed state already. - if (r.applied == 0) { - r.copy.release(); - rollback.Epoch.select(null); - return r.clearSince(); - } - r.toConfirmed(); - r.dirty = true; + if (r.since.items.len < rebase_after) return; + // Nothing on top: it is the confirmed state already. + if (r.applied == 0) { + r.copy.release(); + rollback.Epoch.select(null); + return r.clearSince(); } + // An input applied on top (the session's pump unit before its own + // unit, the next to come): let go then, not replayed whole now. + if (r.since.items.len < 2 * rebase_after) return; + r.stats.rebases += 1; + r.toConfirmed(); + r.dirty = true; } fn clearSince(r: *Replica) void { @@ -1139,7 +1155,9 @@ pub const Replica = struct { const keyboard = if (c.panes[c.view().active]) |pane| pane.terminal != null else false; c.update(in.event); c.step(); - p.terminal = r.t.screen_state and (keyboard or r.t.touched); + // Under bytes: it owes an emulator a write it skipped (a grid's + // size), replayed when confirmed. + p.terminal = if (r.t.screen_state) keyboard or r.t.touched else r.t.touched; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -1215,7 +1233,6 @@ pub const Replica = struct { r.retiring = for (c.retired_panes.current, c.retired_panes.previous) |x, y| { if (x != null or y != null) break true; } else false; - if (!r.t.screen_state) return; for (r.core().panes, &r.views) |slot, *v| v.* = if (slot) |pane| if (pane.terminal) |state| pardes.Term.grid(state).view else null else null; } @@ -1230,7 +1247,6 @@ pub const Replica = struct { } fn putViews(r: *Replica) void { - if (!r.t.screen_state) return; for (r.core().panes, r.views) |slot, at| if (slot) |pane| if (pane.terminal) |state| pardes.Term.viewTo(state, at); } @@ -2055,6 +2071,10 @@ pub const Peers = struct { /// After each flush of a client's terminals, told: the soak's record /// of each terminal as each version left it (test/replicas.zig). flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null, + /// Its clients' terminals cross as the pty's bytes in its units, each + /// client's emulator its own (P29, P32), not as screen state: the + /// soak's (test/replicas.zig `--bytes`), until the switch. + bytes: bool = false, pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer }; /// A connection to join, and the view it joins again for, if it does. @@ -2175,6 +2195,14 @@ pub const Peers = struct { ps.screensOut(core, .flush); } + /// What its steps recorded passed a unit's bound (`tape.unit_max`): a + /// unit of its own now, between two inputs of the pump (Tape.cut). + fn cutUnit(ctx: *anyopaque) void { + const ps: *Peers = @ptrCast(@alignCast(ctx)); + ps.seq += 1; + ps.unit(0, ps.seq); + } + const ScreensOut = enum { flush, fill }; /// What each client is owed of the terminals (`Screens.flush`), or the @@ -2186,6 +2214,7 @@ pub const Peers = struct { } fn screensTo(ps: *Peers, core: *Pardes, peer: *Peer, comptime what: ScreensOut) void { + if (ps.bytes) return; defer { for (ps.msgs.items) |m| ps.gpa.free(m); ps.msgs.clearRetainingCapacity(); @@ -2219,8 +2248,9 @@ pub const Peers = struct { ps.t.unit_digests = true; // Terminals cross as screen state: a unit carries no pty bytes, // and its digest is a word (PARDES_REPLICA_TRACE: one a field). - ps.t.screen_state = true; + ps.t.screen_state = !ps.bytes; ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null; + ps.t.cut = .{ .ctx = ps, .f = cutUnit }; ps.screens = .init(ps.gpa); tape.on = &ps.t; core.tape = &ps.t; @@ -3241,13 +3271,13 @@ pub const Link = struct { var buf: [1024]u8 = undefined; const e = &c.r.echo.stats; var w: std.Io.Writer = .fixed(&buf); - w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d} draws {d} again {d}", .{ + w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d} draws {d} again {d} rebases {d} copies {d} checks {d}", .{ st.inputs, st.speculated, st.stopped, st.units, st.fast, c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, pctOf(st.spec_ns.items, 50) / 1000, pctOf(st.spec_ns.items, 99) / 1000, pctOf(st.copy_ns.items, 50) / 1000, pctOf(st.copy_ns.items, 99) / 1000, pctOf(st.rollback_ns.items, 50) / 1000, pctOf(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, c.join.sent_bytes >> 10, e.predicted, e.predicted + e.unpredicted, e.confirmed, e.mispredicted, - c.draws, c.again, + c.draws, c.again, st.rebases, st.copies, st.checks, }) catch return; // What stopped its inputs, last: a word a pair before it. w.writeAll(" stops ") catch return; @@ -3678,6 +3708,56 @@ test "the copy taken for an input of its own stays once the input is confirmed: try std.testing.expectEqual(@as(u32, 1), r.stats.foreign); } +test "the session's pump units that moved nothing, kept under a key applied on top, reach the kept list's bound: it is let go at the confirm that leaves nothing applied, never replayed whole" { + // The live pair's order (core/replica.zig Peers.boundary): before it + // steps a client's key the session sends its pump's unit, which moved + // nothing; the client takes it with the key applied on top (`neutral`, + // kept), then the key's own unit (fast, kept). Two kept a key: which + // of them is the bound's is the arrivals' parity, and a pump's unit + // while idle turns it. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + freshSecond(); + // A first key, confirmed: the copy held, one unit kept (the parity + // that puts the bound on a pump's unit). + try key(r, 'j', &sent); + r.confirm(try a.take(sent.items[0])); + for (1..rebase_after) |i| { + try key(r, if (i % 2 == 0) 'j' else 'k', &sent); + a.pump(); + r.confirm((try a.pending()).?); + r.confirm(try a.take(sent.items[i])); + r.settle(); + try std.testing.expect(r.since.items.len <= rebase_after); + } + try std.testing.expectEqual(@as(u32, rebase_after - 1), r.neutral); + try std.testing.expectEqual(@as(u32, 0), r.stats.rebases); + try agrees(a, r); + // Keys applied on top all the while (one ahead of the session): the + // list is put back and replayed at twice the bound, not let grow. + try key(r, 'j', &sent); + for (0..3 * rebase_after) |i| { + try key(r, 'k', &sent); + a.pump(); + r.confirm((try a.pending()).?); + r.confirm(try a.take(sent.items[rebase_after + i])); + r.settle(); + try std.testing.expect(r.since.items.len <= 2 * rebase_after); + } + try std.testing.expect(r.stats.rebases >= 1); + r.confirm(try a.take(sent.items[sent.items.len - 1])); + r.settle(); + try agrees(a, r); +} + test "a rollback over a Tab it applied measures tabs as its core has them again" { // A tab's width is the core's (settings.tab, handed to every width // function), which the copy holds: once the process's (config.tab_now), @@ -4139,6 +4219,214 @@ test "a unit that closes or tears down a terminal is never kept over a copy take try std.testing.expectEqual(a.core.store.closed.items.len, r.core().store.closed.items.len); } +/// The emulators of a session's and a replica's terminals as a dump keeps +/// them (what pardes keeps beside each, its whole snapshot): the same +/// bytes, or a test fails. +fn sameTerminals(a: *Authority, r: *Replica) !void { + const gpa = std.testing.allocator; + for (a.core.panes, r.core().panes) |x, y| { + const theirs = (x orelse continue).terminal orelse continue; + const mine = (y orelse return error.NoPane).terminal orelse return error.NoTerminal; + var w1: std.Io.Writer.Allocating = .init(gpa); + defer w1.deinit(); + var w2: std.Io.Writer.Allocating = .init(gpa); + defer w2.deinit(); + try theirs.dumpWrite(gpa, &w1.writer); + try mine.dumpWrite(gpa, &w2.writer); + try std.testing.expectEqualSlices(u8, w1.written(), w2.written()); + } +} + +/// A session and a replica of the bytes kind (its terminals fed the pty's +/// bytes the session's units carry), the session's view on its text pane, +/// and the shell's slot. +const BytesPair = struct { + a: *Authority, + r: *Replica, + shell: pardes.Pane.Id, + + fn init() !BytesPair { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), false); + errdefer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + var shell: ?pardes.Pane.Id = null; + for (a.core.panes, 0..) |slot, id| if (slot) |pane| { + if (pane.isTerminal()) shell = .at(id) else if (pane.file != null) a.core.view().active = @intCast(id); + }; + const pair: BytesPair = .{ .a = a, .r = r, .shell = shell orelse return error.NoShell }; + r.confirm(try a.local(.{ .focus = true })); + return pair; + } + + fn deinit(b: BytesPair) void { + b.r.deinit(); + b.a.deinit(); + } + + /// The session's program prints `bytes`, a unit of its own the replica takes. + fn output(b: BytesPair, bytes: []const u8) !void { + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = bytes } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + } + + /// The client types a key over the text, and the session's own key + /// comes first: a rollback, which replays what was kept since the copy. + fn rollback(b: BytesPair) !void { + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + b.r.confirm(try b.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + b.r.settle(); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + } +}; + +test "bytes: a session's output taken over a copy held ahead is fed once: a rollback does not feed it again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + b.r.ready(); + try std.testing.expect(b.r.copy.held); + try b.output("one line of the program's\r\n"); + try b.rollback(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: what a terminal's emulator gains while a copy is held is its own: a rollback frees none of it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + b.r.ready(); + // Pages and their side tables the emulator had not: thousands of rows, + // a colour and a link a word. + var line: [128]u8 = undefined; + for (0..3000) |i| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i }) } }); + b.r.confirm((try b.a.pending()).?); + try b.rollback(); + try b.output("after\r\n"); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a session's output that moves nothing the digest covers (a colour set) is never taken as moving nothing: it is fed, at its place" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + // A key of its own applied on top, the session's colour comes, then the + // key is confirmed, and the session's next output is in that colour. + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + try b.output("\x1b[31m"); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try b.output("red\r\n"); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a mouse motion a speculation told a terminal's program is told again when its input is replayed: the cell last told is the pane's, put back with it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + // The program hears every motion, in SGR form. + try b.output("\x1b[?1003h\x1b[?1006h"); + const at = b.a.core.view().rects[b.shell.index()]; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // Its speculation encodes the motion (the cell noted) and stops at the + // pty's write; the session's unit for it is replayed. + try sent.append(gpa, try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .none, .kind = .motion, .col = at.x + 3, .row = at.y + at.h / 2 } }))); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try agrees(b.a, b.r); +} + +test "bytes: a client joins from a dump with its terminals whole, and every side, the session too, reloads each terminal in the step that opens its view: their hashes agree, and all go on as one" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + // History with colours and links, a sequence left open at the cut. + var line: [128]u8 = undefined; + for (0..400) |i| try b.output(try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i })); + try b.output("half a colour: \x1b[38;2;10;20"); + const reloads = pardes.Term.writes; + const joined = (try b.a.join(2, null)).?; + defer gpa.free(joined.dump); + b.r.confirm(joined.unit); + try std.testing.expect(b.r.diverged == null); + try std.testing.expect(pardes.Term.writes != reloads); + const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + late.t.screen_state = false; + late.core().echo = null; + try std.testing.expectEqual(joined.digest, late.digest()); + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = ";30mthe rest of it\x1b[0m\r\n" } }); + const rest = (try b.a.pending()).?; + b.r.confirm(rest); + late.confirm(rest); + late.settle(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); + try agrees(b.a, late); + try sameTerminals(b.a, late); +} + +test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + const Cuts = struct { + a: *Authority, + units: std.ArrayListUnmanaged([]u8) = .empty, + fn cut(ctx: *anyopaque) void { + const c: *@This() = @ptrCast(@alignCast(ctx)); + c.a.batched = 0; + c.a.seq += 1; + const u = c.a.unit(0, c.a.seq) catch unreachable; + c.units.append(std.testing.allocator, std.testing.allocator.dupe(u8, u) catch unreachable) catch unreachable; + } + }; + var cuts: Cuts = .{ .a = b.a }; + defer { + for (cuts.units.items) |u| gpa.free(u); + cuts.units.deinit(gpa); + } + b.a.t.cut = .{ .ctx = &cuts, .f = Cuts.cut }; + defer b.a.t.cut = null; + // A pump's worth of reads, 64 KiB each, 3 MiB in all. + var read: [64 * 1024]u8 = undefined; + for (&read, 0..) |*c, i| c.* = if (i % 80 == 79) '\n' else @intCast('a' + i % 26); + for (0..48) |_| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = &read } }); + try std.testing.expect(cuts.units.items.len >= 2); + for (cuts.units.items) |u| { + try std.testing.expect(u.len <= tape.unit_max + read.len + 4096); + b.r.confirm(u); + } + if (try b.a.pending()) |u| b.r.confirm(u); + b.r.settle(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + test "a replica joined from the session's dump replays the units after it" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); @@ -5342,7 +5630,6 @@ const may_wait = [_]Wait{ .{ .what = "Dump", .on = .any, .stop = "write_dump", .why = "a dump written" }, .{ .what = "Upgrade", .on = .any, .stop = "upgrade", .why = "the session execs itself" }, .{ .what = "Detach", .on = .any, .stop = "detach", .why = "the session lets its frontend go" }, - .{ .what = "focus lost and found", .on = .any, .stop = "newer_build", .why = "a window found again asks whether a newer build is installed: the session's disk" }, // What the session alone holds: its closed panes, Recent and History // (every session of its user writes them), the config and theme files. .{ .what = "Restore", .on = .any, .stop = "the authority's own state", .why = "the session's dumps" }, @@ -5354,10 +5641,7 @@ const may_wait = [_]Wait{ .{ .what = "DumpConfig", .on = .any, .stop = "the authority's own state", .why = "the config file written" }, .{ .what = "ThemeFile *", .on = .any, .stop = "the authority's own state", .why = "a theme file, the session's" }, .{ .what = "DumpThemes", .on = .any, .stop = "the authority's own state", .why = "the theme files written" }, - // A search's rows: the session's worker or its loop writes them, and - // whether it has a worker is not the client's to know (12a); a - // +Preview's text is read from the session's disk. - .{ .what = "Search *", .on = .any, .stop = "search", .why = "a search's rows, the session's worker's" }, + // A +Preview's text is read from the session's disk. .{ .what = "Search *", .on = .any, .stop = "preview", .why = "a +Preview's file, from the session's disk" }, // A kind's own state on the session (a PDF's document): asking it. .{ .what = "*", .on = .addon, .stop = "a kind's search", .why = "a search in a kind's pane: its own state, the session's" }, @@ -5884,3 +6168,489 @@ test "an idle client's check answered covers the units that came while it was as c.take(.{ .checked = digestOf(a) }); try std.testing.expect(!c.asked and c.changed); } + +// A window's keyboard found again asked the session's host whether a newer +// pardes is installed, in the core's focus step: a client's refocus waited +// a round trip for a question about the session's binary that its own +// window has nothing to do with. Each process's build is its own frontend's +// to look at, at its own focus-in (upgrade.noticeNewer). +test "a far client's window found again is instant: its refocus asks the session's host nothing, and the session's unit confirms it" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, FullHost.host(), false); + defer a.deinit(); + const r = try joinedFresh(a); + defer r.deinit(); + for ([_]bool{ false, true }) |focused| { + const msg = try gpa.dupe(u8, try r.input(.{ .focus = focused })); + defer gpa.free(msg); + try std.testing.expectEqual(@as(usize, 1), r.applied); + r.confirm(try a.take(msg)); + r.settle(); + try agrees(a, r); + } + try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); + try std.testing.expectEqual(@as(u32, 2), r.stats.fast); +} + +/// Kind `ops`'s code in the client for its pane `id`, as a client that +/// has its library runs it (initDump: Addon.plainOps, dump.plainHere). +fn runsHere(r: *Replica, id: usize, ops: *const pardes.Kind.Ops) !void { + const was = Stepping.begin(&r.t, &r.epoch); + defer was.end(); + const c = r.core(); + const slot = c.panes[id].?.addon.?; + c.kinds.ops[c.kinds.byName(slot.nameOf()).?] = ops; + c.panes[id].?.addon = try pardes.dump.plainHere(c, id, slot, ops); +} + +/// A plain kind that takes the mouse (normal mode has its keys). +const Pointed = struct { + const pa = pardes.Kind.c; + fn mouse(_: ?*anyopaque, _: [*c]const pa.pa_mouse) callconv(.c) c_int { + return 1; + } + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Pointed", .opens = 1, .doc = "a pane that takes the mouse" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "pointed".* ++ @as([9]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), + .open = Still.open, + .paint = Still.paint, + .mouse = mouse, + }); +}; + +// A press grabs a kind's pane (the drag and release after it are the +// kind's wherever they land); a step between can leave that pane too +// short for a row of body, and the drag's row clamped into an empty range +// tripped std.math.clamp's assertion (the soak, once, at rtt 207, in a +// client's speculation). +test "a far client's drag in a kind's pane it grabbed, the pane since too short for a row of body: the kind is told its edge, at once and as on the session" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const pointed = pardes.Kind.loadedOf(&Pointed.ops, "/x/pointed.so", @splat(8), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &pointed } }); + _ = try a.local(.{ .command = "Pointed" }); + const kid = a.core.view().active; + const r = try joinedFresh(a); + defer r.deinit(); + try runsHere(r, kid, &Pointed.ops); + const rect = r.core().view().rects[kid]; + const col = rect.x + 4; + const row = rect.y + r.core().panes[kid].?.tag_rows + 1; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + for ([_]pardes.Event{ + .{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row } }, + .{ .resize = .{ .cols = 80, .rows = 4 } }, + .{ .mouse = .{ .button = .left, .kind = .drag, .col = col, .row = 30 } }, + .{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = 30 } }, + }) |ev| { + try sent.append(gpa, try gpa.dupe(u8, try r.input(ev))); + } + try std.testing.expectEqual(@as(u16, 1), r.core().view().rects[kid].h); + try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); + for (sent.items) |m| { + r.confirm(try a.take(m)); + r.settle(); + } + try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); + try agrees(a, r); +} + +// A draw's token is its slot's count of draws, which the rollback copy +// holds with the slot: a frame drawn under a speculation asks token T, the +// rollback takes the count back, and the next frame's draw (of the state +// the replay came to) is given T again. Its answer and the discarded one's +// both come to job_done as T, in the order the workers finish. +test "a far client's frame drawn under a speculation that rolls back asks a picture whose token the next draw is never given again: the kind keeps the picture of the state it shows" { + // A plain kind whose picture is a draw of its count (api.draw from its + // paint, when the picture asked for is of another count), its answer kept + // for the token it asked last, once: a kind with one draw outstanding. + // What it shows is this process's (a kind's own memory, never its block). + const Drawn = struct { + const pa = pardes.Kind.c; + var want: u32 = 0; + var asked: ?u32 = null; + var shown: ?u32 = null; + fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { + const n: *u32 = @ptrCast(@alignCast(pardes.Kind.api.alloc.?(4))); + n.* = 0; + return n; + } + fn paint(st: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void { + const n: *const u32 = @ptrCast(@alignCast(st.?)); + if (asked == n.*) return; + asked = n.*; + want = pardes.Kind.api.draw.?(n, 4); + } + fn press(st: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { + const n: *u32 = @ptrCast(@alignCast(st.?)); + n.* = n.* * 2 + 1; + return 1; + } + fn jobRun(in: [*c]const u8, n: u32, out: [*c]pa.pa_out) callconv(.c) u32 { + const o: [*]u8 = @ptrCast(out.*.alloc.?(out, n) orelse return 0); + @memcpy(o[0..n], in[0..n]); + return n; + } + fn jobDone(_: ?*anyopaque, token: u32, out: [*c]const u8, n: u32) callconv(.c) void { + if (token != want or n != 4) return; + want = 0; + shown = std.mem.readInt(u32, out[0..4], .little); + } + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Drawn", .opens = 1, .doc = "a picture of a count" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "drawn".* ++ @as([11]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), + .open = open, + .paint = paint, + .key = press, + .job_run = jobRun, + .job_done = jobDone, + }); + }; + + // A frontend's workers for draws, run when the test says, each landing + // when it says (host_io.KindJob: run on a worker, landed on the loop). + const HeldDraws = struct { + var held: [4]*@import("dev").host_io.KindJob = undefined; + var n: usize = 0; + fn go(_: ?*anyopaque, j: *@import("dev").host_io.KindJob) bool { + j.run(); + held[n] = j; + n += 1; + return true; + } + }; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const drawn = pardes.Kind.loadedOf(&Drawn.ops, "/x/drawn.so", @splat(9), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &drawn } }); + _ = try a.local(.{ .command = "Drawn" }); + const kid = a.core.view().active; + const r = try joinedFresh(a); + defer r.deinit(); + try runsHere(r, kid, &Drawn.ops); + Drawn.want = 0; + Drawn.asked = null; + Drawn.shown = null; + HeldDraws.n = 0; + const was = pardes.Kind.drawer; + pardes.Kind.drawer = .{ .ctx = null, .go = HeldDraws.go }; + defer pardes.Kind.drawer = was; + const none: pardes.views.Present = .{ .ctx = null, .f = null }; + // Its own key: 0 -> 1, drawn (a picture of 1 asked). + const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'x', .text = "x" } })); + defer gpa.free(msg); + _ = r.draw(none); + try std.testing.expectEqual(@as(?u32, 1), Drawn.asked); + // The session's own key first: rolled back, its own applied again on + // top (0 -> 1 -> 3), drawn (a picture of 3 asked). + r.confirm(try a.own(.{ .key = .{ .cp = 'x', .text = "x" } })); + r.settle(); + _ = r.draw(none); + try std.testing.expectEqual(@as(?u32, 3), Drawn.asked); + try std.testing.expectEqual(@as(usize, 2), HeldDraws.n); + // The discarded picture's worker done first, then the other's; a frame. + for (HeldDraws.held[0..2]) |j| pardes.Kind.landDraw(r.core(), j); + _ = r.draw(none); + try std.testing.expectEqual(@as(?u32, 3), Drawn.shown); + r.confirm(try a.take(msg)); + r.settle(); + try agrees(a, r); +} + +// A program that asked for focus events is told of a click into its shell +// by the session's step (Core.reportFocus): a client's own step writes +// nothing. Where the shell's queue is backed up (a 9P write past what the +// effects ring holds, parked until the session's next pump), the session's +// report parks behind it, into `pending_write`, which is digested, where +// the client's speculation skips the write. It cannot differ: a client's +// step settles as the session's does, draining the queue, and what is +// parked is a write into the shell, which stops it (the client holds the +// same queue: the unit that parked it is the session's, which it replays). +test "a far client's click into a shell whose queue is backed up: the session's focus report queues behind what is parked, and the client ends as the session does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const Told = struct { + var bytes: usize = 0; + var tail: [3]u8 = @splat(0); + fn write(_: ?*anyopaque, _: pardes.Pane.Id, b: []const u8) void { + bytes += b.len; + if (b.len >= 3) @memcpy(&tail, b[b.len - 3 ..]); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write }; + }; + const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }, true); + defer a.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[?1004h$ " } }); + _ = (try a.pending()).?; + _ = try a.local(.{ .command = "New" }); + var screens: Screens = .init(gpa); + defer screens.deinit(a.core); + const peer = try screens.addPeer(); + const r = try joinedFresh(a); + defer r.deinit(); + try deliver(a, &screens, peer, r, .flush); + r.settle(); + // A 9P write into the shell, past the ring: the rest parked, on both. + const big = try gpa.alloc(u8, pardes.memory.limits.effect_cap * pardes.effect_write_cap + 100); + defer gpa.free(big); + @memset(big, 'x'); + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + _ = a.core.serveFs(.{ .tag = 1, .op = .write, .node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_data), .data = big }); + } + a.seq += 1; + r.confirm(try a.unit(0, a.seq)); + r.settle(); + try std.testing.expect(a.core.pending_write[shell] != null and r.core().pending_write[shell] != null); + Told.bytes = 0; + const rect = r.core().view().rects[shell]; + const row = rect.y + r.core().panes[shell].?.tag_rows + 1; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + r.stats.stops = @splat(.{}); + for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .mouse = .{ .button = .left, .kind = kind, .col = rect.x + 2, .row = row } }))); + // The client's own step drains the queue it holds as the session's + // does: what is parked is a write into the shell, so it stops there, + // and waits for the session's step, focus report and all. + try std.testing.expectEqual(@as(usize, 0), r.applied); + for (r.stats.stops) |st| if (st.n > 0) try std.testing.expectEqualStrings("pty_write", st.name); + for (sent.items) |m| { + try deliver(a, &screens, peer, r, .flush); + const u = try gpa.dupe(u8, try a.take(m)); + defer gpa.free(u); + try deliver(a, &screens, peer, r, .fill); + r.confirm(u); + r.settle(); + } + // The program had what was parked, then the focus. + try std.testing.expectEqual(big.len + 3, Told.bytes); + try std.testing.expectEqualStrings("\x1b[I", &Told.tail); + try std.testing.expectEqual(@as(usize, shell), r.core().view().active); + try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); + try agrees(a, r); +} + +// A `/` in a file groups its rows under the declarations they are in once +// a parse of the text exists (Query.ownerDecls): the pane's context, a +// worker's answer, or the locations cache's (a Diff's). Both were kept out +// of the dump as made again from the text, so a client joined since had +// neither, and its replay of the session's next row asked a parse the +// session never asked: the context is dumped now, the cache's no longer read. +test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has the owner's declarations from a worker's parse" { + // A session's host whose parses and searches run on a worker (a tty's, + // Stream.start), their batches posted to an inbox; `land` hands them to + // the core as the session's inputs, as its loop does. + const WorkerSearch = struct { + const Inbox = @import("dev").host_io.Inbox; + var q: Inbox = undefined; + var core: ?*Pardes = null; + fn search(_: ?*anyopaque, gen: u32) void { + pardes.Stream.start(std.testing.io, std.testing.allocator, core.?, gen, &q, Inbox.pushSearch); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; + fn init(a: *Authority) void { + q = .{ .gpa = std.testing.allocator, .lsp_allocator = std.testing.allocator, .io = std.testing.io }; + core = a.core; + } + // The batches posted until the parse asked has answered (a second's + // wait at most), each a unit the replica takes. + fn land(a: *Authority, r: ?*Replica) !void { + var waited: u32 = 0; + while (a.core.stream.parse != null) : (waited += 1) { + if (waited == 1000) return error.Timeout; + var batch: Inbox.Batch = .{}; + q.takeInto(&batch); + for (batch.slice()) |m| switch (m) { + .search => |b| { + const u = try a.local(.{ .search = b }); + if (r) |c| { + c.confirm(u); + c.settle(); + } + b.deinit(std.testing.allocator); + }, + else => m.deinit(std.testing.allocator, std.testing.allocator), + }; + if (a.core.stream.parse != null) { + const rest: std.c.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = std.c.nanosleep(&rest, null); + } + } + } + }; + if (comptime !pardes.syntax.enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false); + defer a.deinit(); + WorkerSearch.init(a); + defer WorkerSearch.q.deinit(); + // The session's own `/`: its parse asked of the worker, its answer an + // input (the rows grouped once it lands). + _ = try a.local(.{ .command = "Search /pub" }); + try WorkerSearch.land(a, null); + // A client joined now, and a key typed into the query: both its rows. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + try std.testing.expectEqual(digestOf(a), r.digest()); + try std.testing.expectEqual(a.core.panes[0].?.file.?.context.declarations.len, r.core().panes[0].?.file.?.context.declarations.len); + const u = try gpa.dupe(u8, try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); + defer gpa.free(u); + r.confirm(u); + r.settle(); + try agrees(a, r); +} + +// A text's places show as ticks on its rail (Places.addTicks), made again +// only when `gen` moves (buildTicks), by a frame or by a step's rail click +// (tickHit), whichever asks first; a dump keeps neither. A frame's ticks +// that a click read after the places changed under them would land it +// elsewhere on a core that drew than on one that did not. +test "a client joined from a dump lands a click on a rail's tick as the session does, the session's ticks drawn before the places changed" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + defer a.deinit(); + _ = try a.local(.{ .command = "Search /pub" }); + const owner: usize = 0; + try std.testing.expect(a.core.panes[owner].?.places.hits.items.len > 1); + // The session draws: its ticks, of `/pub`'s places. + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try a.core.render(arena.allocator()); + } + const ticks_gen = a.core.panes[owner].?.places.ticks_gen; + try std.testing.expectEqual(a.core.panes[owner].?.places.gen, ticks_gen); + const r = try joinedFresh(a); + defer r.deinit(); + // Its places changed (`/publ`), then a click on each row of the rail. + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'l', .text = "l" } }))); + const rect = r.core().view().rects[owner]; + const pane = r.core().panes[owner].?; + for (rect.y + pane.tag_rows..rect.y + rect.h) |row| for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| { + try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .mouse = .{ .button = .left, .kind = kind, .col = rect.x, .row = @intCast(row) } }))); + }; + try std.testing.expect(a.core.panes[owner].?.places.ticks_gen == ticks_gen); + for (sent.items) |m| { + r.confirm(try a.take(m)); + r.settle(); + } + // (The key may be mispredicted: a step's places are a frame's time's + // worth, `tape.over`, the session's verdict, and its drawn caches let + // it find more in that time than the client's speculation did.) + try agrees(a, r); + try std.testing.expectEqual(a.core.panes[owner].?.places.current, r.core().panes[owner].?.places.current); +} + +// `search` stopped every client's step that asked for one, because a host +// with no worker wrote the rows outside any record: then no client had them, +// stopped or not (a replay answers the entry from the tape and runs no +// host). Its rows are inputs now, as a worker's are, and a step that asks +// the session's host for a search goes on. +test "a far client's step that asks for a search goes on at once, and a session whose host searches on its loop gives every client its rows" { + // A session's host with no worker for a search (a frontend before its + // threads, or one whose worker could not be had: Stream.start): it runs + // the search on its loop, in its `search` entry. + const LoopSearch = struct { + var core: ?*Pardes = null; + fn search(_: ?*anyopaque, gen: u32) void { + pardes.Stream.runHere(core.?, gen, true); + } + fn now(_: ?*anyopaque) u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @intCast(ts.sec * std.time.ns_per_s + ts.nsec); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search, .now = now }; + }; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.zig", .data = "const needle = 1;\nfn f() void {}\n// a needle\n" }); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/a.zig", .{dir}); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = path }, .{ .vtable = &LoopSearch.vtable }, false); + defer a.deinit(); + LoopSearch.core = a.core; + const r = try joinedFresh(a); + defer r.deinit(); + // A `/` in a file asks the session's host for its parse. + const msg = try gpa.dupe(u8, try r.input(.{ .command = "Search /ne" })); + defer gpa.free(msg); + try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); + r.confirm(try a.take(msg)); + r.settle(); + try agrees(a, r); + // A Grep the session's loop runs when the typing pauses: its rows. + r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); + r.confirm(try a.local(.{ .command = "Search Grep needle" })); + r.settle(); + var ticks: u32 = 0; + while (a.core.stream.state == .waiting) : (ticks += 1) { + if (ticks == 200) return error.Timeout; + const rest: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; + _ = std.c.nanosleep(&rest, null); + r.confirm(try a.local(.tick)); + r.settle(); + } + try std.testing.expect(a.core.stream.state == .done); + try agrees(a, r); +} + +// PARDES_NOTIME (the tests' `--:--:--` clock) is read by `Message.stamp`, +// which only a host calls: between steps, or in its own entry during one. +// The stamped text crosses as the setMessage the host makes, so a client +// whose environment says otherwise replays the session's text. +test "a far client's replay of a message its session's host stamped takes the session's text, whatever its own PARDES_NOTIME says" { + const gpa = std.testing.allocator; + const Stamping = struct { + var core: ?*Pardes = null; + fn yank(_: ?*anyopaque, _: []const u8) void { + var buf: [64]u8 = undefined; + const c = core.?; + c.setMessage(.at(c.view().active), pardes.Messages.Message.stamp(&buf, "yanked", "x")); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .set_clipboard = yank }; + }; + const Shell = @import("dev").host_io.Shell; + const was = if (std.c.getenv("PARDES_NOTIME")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; + defer if (was) |v| gpa.free(v); + defer _ = if (was) |v| Shell.setenv("PARDES_NOTIME", v, 1) else @import("dev").host_io.testUnsetenv("PARDES_NOTIME"); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &Stamping.vtable }, false); + defer a.deinit(); + Stamping.core = a.core; + const r = try joinedFresh(a); + defer r.deinit(); + // The session's machine says `--:--:--`; the client's the time of day. + _ = Shell.setenv("PARDES_NOTIME", "1", 1); + const u = try gpa.dupe(u8, try a.own(.{ .command = "ClipYank" })); + defer gpa.free(u); + _ = @import("dev").host_io.testUnsetenv("PARDES_NOTIME"); + r.confirm(u); + r.settle(); + try agrees(a, r); + try std.testing.expect(try shows(r.core(), "--:--:-- yanked x")); +} diff --git a/core/rollback.zig b/core/rollback.zig index 3d5ab921..c7d0a4e8 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -88,6 +88,9 @@ pub const Epoch = struct { } pub fn deinit(e: *Epoch) void { + // Gone with a copy still held (a test that failed between take and + // restore): the process-wide hold must not point into it. + if (pardes.syntax.held_trees == &e.trees) pardes.syntax.held_trees = null; var it = e.live.iterator(); while (it.next()) |kv| e.child.rawFree(@as([*]u8, @ptrFromInt(kv.key_ptr.*))[0..kv.value_ptr.len], kv.value_ptr.alignment, @returnAddress()); e.live.deinit(e.meta); @@ -579,6 +582,9 @@ test "a copy put back is the core as it was; one let go keeps what was done" { const gpa = e.allocator(); const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa }); p.pump(.{}) catch {}; + const f = for (p.panes) |slot| { + if (slot) |pane| if (pane.file) |*file| break file; + } else return error.NoFile; const before = walk.digest(Pardes, p); var c: Copy = .{}; defer c.deinit(); @@ -588,6 +594,7 @@ test "a copy put back is the core as it was; one let go keeps what was done" { p.update(.{ .key = .{ .cp = pardes.Key.escape } }); p.pump(.{}) catch {}; const edited = walk.digest(Pardes, p); + const stamped = f.mtime; try std.testing.expect(edited != before); try std.testing.expect(c.restore()); try std.testing.expectEqual(before, walk.digest(Pardes, p)); @@ -596,6 +603,9 @@ test "a copy put back is the core as it was; one let go keeps what was done" { for (typed) |k| p.update(.{ .key = .{ .cp = k, .text = &.{k} } }); p.update(.{ .key = .{ .cp = pardes.Key.escape } }); p.pump(.{}) catch {}; + // An edit stamps the text with the wall clock's second (File.edit's + // mtime): the same typing in the next second is the same edit. + f.mtime = stamped; try std.testing.expectEqual(edited, walk.digest(Pardes, p)); c.release(); try std.testing.expectEqual(edited, walk.digest(Pardes, p)); diff --git a/core/root.zig b/core/root.zig index 69ec3ded..a57934a6 100644 --- a/core/root.zig +++ b/core/root.zig @@ -98,12 +98,12 @@ pub const Host = host_io.Host; pub const frameMark = tracy.frameMark; /// The shell this build is for (build.zig's `-Dplatform`). -pub const platform = @import("pardes_config").platform; +pub const platform = @import("pardes_options").platform; -pub const version = @import("pardes_config").version; -pub const commit: ?[]const u8 = @import("pardes_config").commit; +pub const version = @import("build_info").version; +pub const commit: ?[]const u8 = @import("build_info").commit; -pub const isolated = @import("pardes_isolation").isolated; +pub const isolated = @import("pardes_options").isolated; pub const font_picker = platform == .gui or platform == .macos; @@ -324,7 +324,8 @@ comptime { } } -/// Said at a focus-in when the Host's `newer_build` answers yes (upgrade.zig). +/// Said by a session's own frontend at its focus-in, when the build at the +/// path it started from is not its own (upgrade.noticeNewer). pub const newer_build_words = "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"; pub const Rect = layout.Rect; @@ -442,7 +443,7 @@ test { // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. - if (comptime @import("term_options").terminal and platform == .gui) _ = @import("dev").gui; + if (comptime @import("pardes_options").terminal and platform == .gui) _ = @import("dev").gui; } /// The container-level `var`s core/ may hold (at the top of a file, in a @@ -457,9 +458,10 @@ const allowed_vars = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Kind.zig", "current", "the kind call in progress, put back at its end (threadlocal)" }, .{ "Kind.zig", "breach", "Debug: the first call over budget, for the addon test tool" }, .{ "Kind.zig", "drawer heap seed_base", "set once by the host at start" }, - .{ "Kind.zig", "ready", "this process's draws done, each keyed by its core, pane and serial" }, + .{ "Kind.zig", "ready drawn", "this process's draws: those done, each keyed by its core, pane and serial, and the last token given, which no rollback takes back" }, .{ "Names.zig", "dp_rows dp_trace", "the scorer's scratch, written before it is read in one call" }, .{ "Turn.zig", "yield_depth", "this thread's nesting of yields (threadlocal)" }, + .{ "Term.zig", "writes reloads", "this process's emulators' writes, read across one replay on its thread (the replica engine's one rule), and its reloads' count and time" }, .{ "c_heap.zig", "allocators allocators_len allocators_lock last", "the C heap's registry of allocators and its lookup's memo" }, .{ "c_heap.zig", "test_allocator stateless", "its tests'" }, .{ "config.zig", "other_build addon_sources", "the docs check's data, a test's" }, @@ -613,7 +615,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "FrameStats.zig", 7, "a frame's clock and log: frames are local, never digested" }, .{ "Handover.zig", 29, "a window carried to another process over a socket: the session's host" }, .{ "Kind.zig", 1, "host_io's KindJob: a kind's job is the host's" }, - .{ "Messages.zig", 6, "the message clock, read through tape.value(.clock); PARDES_NOTIME, the tests' (a step's read of the environment: set on one side only it would diverge)" }, + .{ "Messages.zig", 6, "the message clock, read through tape.value(.clock); PARDES_NOTIME, the tests', read by a host's `stamp` alone (between steps, or in a host's call), whose text the tape carries in the setMessage it makes: never a step's" }, .{ "Output.zig", 2, "the fonts module (Fonts lists them under tape.site(.fonts)) and the build's version line" }, .{ "Stream.zig", 14, "the disk search's worker: it runs off the step and its batches are inputs" }, .{ "builtins.zig", 2, "Mount's probe (tape.site(.probe)) and Term's shell check (tape.site(.shell))" }, @@ -744,12 +746,13 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest)" }, - .{ "File.zig", "context", "the declarations of the text at a revision: found in sync (refreshContext), by a parse's answer (a step) or a dump's load" }, + .{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" }, + .{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" }, .{ "File.zig", "node_tree node_tree_revision node_tree_edits node_history", "the parse of the text at its revision, made by the first key that walks it" }, .{ "File.zig", "tables", "the whole text's, read at once by whoever asks first (Tables.ensure): no reading under way that a frame could move" }, .{ "Text.zig", "room", "a buffer's capacity" }, .{ "Kind.zig", "ops st gpa arena plain file opened reloads jobs record", "the kind's code and memory here: a plain kind's block is in the copy, and its state hash is checked at every call (Kind.Call.end)" }, - .{ "Kind.zig", "thumb_at thumb_span pointer painted over used draws", "a frame's: written by a paint; `painted` is read by a tick of a kind that is not plain, whose calls are the authority's alone" }, + .{ "Kind.zig", "thumb_at thumb_span pointer painted over used", "a frame's: written by a paint; `painted` is read by a tick of a kind that is not plain, whose calls are the authority's alone" }, .{ "Places.zig", "ticks ticks_gen re", "the rail's ticks, made again when the places move (`gen`), and the compiled pattern, of the pattern" }, .{ "Plumb.zig", "parsed parsed_arena", "the rules parsed, of their text" }, .{ "Stream.zig", "parse_ns paint paint_retired paint_count ahead ahead_for painted_ahead painted_on_loop ahead_seen ahead_ask", "the workers' paints and timings: how a text looks, and numbers" }, diff --git a/core/sam_edit.zig b/core/sam_edit.zig index 0f4a70ba..700c2c01 100644 --- a/core/sam_edit.zig +++ b/core/sam_edit.zig @@ -1158,7 +1158,7 @@ fn expectEdit(text: []const u8, command: []const u8, want: []const u8) !void { } test "an x over 100k lines is 100k searches, each with its own step budget" { - const th = @import("ninep/testing.zig"); + const th = @import("ninep/harness.zig"); const line = &@as([80]u8, @splat('x')) ++ "\n"; const text = try std.testing.allocator.alloc(u8, line.len * 100_000); defer std.testing.allocator.free(text); diff --git a/core/surface.zig b/core/surface.zig index fdcb52c8..6e05f25f 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -221,7 +221,7 @@ pub const Facts = struct { forward: bool = false, cursor_blink: bool = true, jump_trail: bool = false, - pet: config.Runtime.Pet = .off, + pet: config.Settings.Pet = .off, inactive_dim: u8 = 0, tagline_percent: u8 = 100, diff --git a/core/syntax.zig b/core/syntax.zig index f95b745a..ba3851ab 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -1,5 +1,5 @@ const std = @import("std"); -const config = @import("pardes_config"); +const config = @import("pardes_options"); const tracy = @import("tracy.zig"); const grammar_manifest = @import("grammar_manifest.zig"); const locations = @import("locations.zig"); @@ -7,10 +7,9 @@ const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); const diff = @import("diff.zig"); -pub const enabled = config.syntax_highlighting; -const zig_grammar = config.syntax_zig_grammar; -const minimal_grammars = config.syntax_minimal_grammars; -const full_grammars = config.syntax_full_grammars; +pub const enabled = config.grammars != .disabled; +const minimal_grammars = config.grammars == .minimal or config.grammars == .full; +const full_grammars = config.grammars == .full; pub const ts = if (enabled) @import("tree-sitter") else struct { pub const Language = opaque {}; @@ -44,7 +43,7 @@ const Spec = struct { fn grammarSelected(comptime g: grammar_manifest.Grammar) bool { return switch (g.tier) { - .zig => zig_grammar, + .zig => enabled, .minimal => minimal_grammars, .full => full_grammars, }; @@ -2169,7 +2168,7 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al } test "syntax: a grammar handed in at run time colours and walks as the one compiled in" { - if (!zig_grammar) return error.SkipZigTest; + if (!enabled) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); diff --git a/core/tagline.zig b/core/tagline.zig index 456a6b6e..afee0659 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -35,9 +35,9 @@ pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; /// A query pane's while its rows are made (Query.zig), and once Enter froze -/// them into text a Save keeps; Unattach leaves it where it stands. +/// them into text a Save keeps; Undock leaves it where it stands. pub const query_live_tail = " Del"; -pub const query_frozen_tail = " Save Unattach Del"; +pub const query_frozen_tail = " Save Undock Del"; /// ...and while its Grep waits at 2000 lines for More (Stream.zig). pub const query_capped_tail = " More Del"; /// A file with changes it has not saved. @@ -157,7 +157,8 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; // A terminal showing kitty graphics says how it draws them, as an image // pane does, and so does one drawing them as glyph art by choice. - if (panes.Term.petscii(pane.terminal)) |chosen| { + if (pane.terminal != null) { + const chosen = pane.term_petscii; const on = chosen or !p.view().frontend.native_images; if (chosen or panes.Term.hasImages(pane.terminal)) return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" }); diff --git a/core/tape.zig b/core/tape.zig index 00486666..d977b53e 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -131,6 +131,10 @@ pub const Site = enum(u16) { /// What a call into a kind did (Kind.Outcome), and a kind's pane's /// tag prefix: the authority's, whose core alone runs the kind. addon, + /// The hash of a terminal's snapshot as the session reloaded it at a + /// join (panes.reloadTerminals), which every replica's own reload + /// compares. + reload, }; /// What the sites return. wire.semantics hashes their shape with the @@ -297,6 +301,10 @@ pub const Tape = struct { /// not recorded, and no digest covers it. A replica's core never writes /// one but by `apply`. screen_state: bool = false, + /// The session's (replica.Peers): called between two of its inputs once + /// what it recorded since its last unit passes `unit_max`, to send that + /// as a unit: a pump of a flood's reads is cut into units under it. + cut: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque) void } = null, /// A digest as one word (screen-state replicas: every unit of a pty's /// output carries one, at the pty's read rate), not one a field; what /// differs is then not named. @@ -440,6 +448,7 @@ pub const Tape = struct { if ((t.depth == 0 or t.every) and !t.no_digest and !t.unit_digests) recordDigest(t); if (t.depth == 0) t.flush(); t.seeFields(); + if (t.depth == 0 and t.buf.items.len >= unit_max) if (t.cut) |c| c.f(c.ctx); } // ---- replaying ---- @@ -803,6 +812,16 @@ pub const Tape = struct { // Diverged (said in `diverged`): what a speculation gets, harmless, // for the rest of the input. A replica joins again; a replay says so. if (!t.expectHost(id, @tagName(s))) return poisonOf(R); + // What a terminal told (its rows moved, its prompt, a command's + // output) is the session's answer, kept, and a replica whose + // emulators are fed the same bytes asks its own and compares: a + // check a unit, for nothing (P30: a digest, not state). + if (comptime s == .positions or s == .prompt) if (!t.screen_state) { + const mine = @call(.auto, f, full); + t.scratch.clearRetainingCapacity(); + walk.encode(R, &mine, &t.scratch.writer) catch @panic("tape: out of memory"); + if (!std.mem.eql(u8, t.scratch.written(), t.last_ret.bytes[t.last_ret.at..])) t.diverge("what this replica's terminal told ({t}) is not what the session's did", .{s}); + }; var ret = t.last_ret; return walk.decode(R, &ret, a orelse t.arena.allocator()) catch { t.diverge("the tape's answer to {t} is short", .{s}); @@ -882,17 +901,12 @@ pub const Tape = struct { return true; } - /// A speculation that moves a terminal's view: a screen-state replica's - /// may (its rollback puts the view back, replica.zig `views`, and a delta - /// sets it), any other stops (`authorityOnly`). - pub fn viewOnly(t: *Tape, comptime why: []const u8) bool { - if (!t.speculating) return false; - if (t.screen_state) { - t.touched = true; - return false; - } - t.poison(why); - return true; + /// A speculation that moves a terminal's view: it may (its rollback + /// puts the view back, replica.zig `views`); a screen-state replica's + /// says it did (a delta sets the view again). + pub fn viewOnly(t: *Tape, comptime _: []const u8) bool { + if (t.speculating and t.screen_state) t.touched = true; + return false; } /// A speculation read a terminal's rows or moved its view (`Tape.touched`). @@ -1181,10 +1195,6 @@ const keeps_stopping = .{ "upgrade", "hand_over", "detach", - // A host with no worker runs the search on its loop and writes the - // rows outside any record (Stream.runHere, from tui's and gui's - // `search`); whether the session has one is not the client's to know. - "search", // The loop's, never a step's. "wait_input", "present", @@ -1505,6 +1515,30 @@ pub fn endSpeculation(t: *Tape) bool { return !t.poisoned; } +/// About what a unit of the session's holds at most (`Tape.cut`): a pump +/// takes up to 496 reads of 64 KiB, which as one unit could pass the 16 MiB +/// a message may be (replica.zig `lag_max`'s neighbour, wire's bound). +pub const unit_max = 1 << 20; + +/// Whether a unit feeds a terminal its program's output (a pty's read; an +/// input kept by hash is taken to): never taken as moving nothing (the +/// replica engine's one rule, core/replica.zig `confirm`). +pub fn feedsTerminal(bytes: []const u8) bool { + const Tag = std.meta.Tag(Input); + const EventTag = std.meta.Tag(pardes.Event); + var r: walk.Reader = .{ .bytes = bytes }; + while (nextRecord(&r)) |rec| switch (rec.kind) { + .blob => if (rec.payload.len > 0 and rec.payload[0] == @backingInt(Kind.input)) return true, + .input => { + if (rec.payload.len < @sizeOf(Tag) + @sizeOf(EventTag)) continue; + if (!std.mem.eql(u8, rec.payload[0..@sizeOf(Tag)], std.mem.asBytes(&@as(Tag, .update)))) continue; + if (std.mem.eql(u8, rec.payload[@sizeOf(Tag)..][0..@sizeOf(EventTag)], std.mem.asBytes(&@as(EventTag, .output)))) return true; + }, + else => {}, + }; + return false; +} + /// Whether two tapes record the same inputs, host calls and answers, /// their digests aside. pub fn sameRecords(a: []const u8, b: []const u8) bool { @@ -1777,7 +1811,7 @@ test "every place that sets the global tape aside sets the core's field aside: a test "a client's frame drawn between its steps records nothing into its idle tape" { const gpa = std.testing.allocator; - const p = try @import("ninep/testing.zig").withFile(gpa, "x\n"); + const p = try @import("ninep/harness.zig").withFile(gpa, "x\n"); defer p.deinit(); const bytes = try pardes.dump.dumpBytes(p); defer p.gpa.free(bytes); diff --git a/core/term/TerminalImages.zig b/core/term/TerminalImages.zig index feba5ddc..d0d364a1 100644 --- a/core/term/TerminalImages.zig +++ b/core/term/TerminalImages.zig @@ -24,9 +24,6 @@ const image_decode_pixels: usize = 64 * 1024 * 1024; /// oldest past this): a 4K picture in RGBA, with room for a second. pub const storage_limit = 64 * 1024 * 1024; -/// This pane asks for its images as glyph art even where pixels could be -/// drawn (the Petscii builtin). -petscii: bool = false, /// Pixels in RGBA for images ghostty-vt holds in another format (RGB, /// grey): only for images on screen, dropped the frame they are not. /// The emulator's own allocator's, as the emulator is (`draw`'s `own`): @@ -191,7 +188,7 @@ pub fn draw( const bottom = pages.getBottomRight(.viewport) orelse return; const cw: u32 = @max(1, where.cell_w); const ch: u32 = @max(1, where.cell_h); - const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch }; + const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch, .glyph = where.petscii }; // Handed on lowest z first (the storage's order is a hash map's), the // order a shell draws them in; equal z keeps the order they came in. const first = out.items.len; @@ -283,6 +280,8 @@ const Ctx = struct { rows_of: []const ?u16, cw: u32, ch: u32, + /// Its images as glyph art (the pane's Petscii). + glyph: bool, /// Draw `src` of `img` over `dst`, one cell row of it at a time: a row /// is shown, or not, or shown elsewhere, as the body lays it out. @@ -323,7 +322,7 @@ const Ctx = struct { }, .key = plain.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)), .z = z, - .art = .{ .glyph = ctx.ti.petscii }, + .art = .{ .glyph = ctx.glyph }, }) catch {}; } } diff --git a/core/term/term.zig b/core/term/term.zig index 6e36816a..b18f5875 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -31,6 +31,8 @@ pub const ops: iface.Ops = .{ .parts = cast(iface.Ops, "parts", terminal_.parts), .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot), .load = cast(iface.Ops, "load", terminal_.load), + .reload = cast(iface.Ops, "reload", terminal_.reload), + .direct = cast(iface.Ops, "direct", terminal_.direct), .feed = cast(iface.Ops, "feed", terminal_.feed), .grid = cast(iface.Ops, "grid", terminal_.grid), .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), @@ -62,8 +64,6 @@ pub const ops: iface.Ops = .{ .spanColor = terminal_.spanColor, .paint = cast(iface.Ops, "paint", terminal_.paint), .images = cast(iface.Ops, "images", terminal_.images), - .petscii = cast(iface.Ops, "petscii", terminal_.petscii), - .togglePetscii = cast(iface.Ops, "togglePetscii", terminal_.togglePetscii), .hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages), .encoder = cast(iface.Ops, "encoder", terminal_.encoder), .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree), diff --git a/core/term/terminal.zig b/core/term/terminal.zig index d99cfb79..055c8981 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -181,9 +181,6 @@ pub const State = struct { reply: [4096]u8 = undefined, reply_len: u16 = 0, reply_dropped: u32 = 0, - /// The grid cell the program last heard the mouse at, so motion is - /// reported once per cell. - mouse_cell: ?ghostty_vt.Coordinate = null, /// The kitty graphics its program placed, as drawn (TerminalImages.zig). images: TerminalImages = if (images_enabled) .{} else {}, /// Counts the emulator's writes (output, a resize, its view scrolled): @@ -198,16 +195,25 @@ pub const State = struct { /// the step reads the grid it had, as its replicas' replays do, and the /// rows sent them for it (Screens.fill) are of that grid's numbering. resize_to: ?struct { cols: u16, rows: u16 } = null, + /// Its program's kitty images by direct data alone (`direct`): a + /// replica's emulator, which is not the session's. A file, a temporary + /// file or shared memory is the session's machine's (and a temporary + /// one is deleted by its first reader): its image is absent here. + direct: bool = false, /// The stream over the emulator, its answers to the program and its /// size reports routed here, PNG decoded: what `create` and a dump's - /// load both do once the emulator is in place. - fn wire(s: *State) void { - s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa }); + /// load both do once the emulator is in place. False when the stream's + /// keeper of a sequence in flight had no room (ghostty goes on without + /// it, swallowing the error): `open` and `load` refuse the terminal then, + /// as at any allocation that fails. + fn wire(s: *State) bool { + s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa, .continuation_max_bytes = continuation_max }); s.stream.handler.inner.effects.write_pty = ptyReport; s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; s.stream.handler.inner.effects.size = ptySize; if (comptime images_enabled) TerminalImages.installPngDecoder(); + return s.stream.continuation.?.bytes.capacity > 0; } }; @@ -253,8 +259,6 @@ pub fn parts(s: *const State) Term.Parts { return .{ .reply = s.reply[0..s.reply_len], .reply_dropped = s.reply_dropped, - .mouse_cell = if (s.mouse_cell) |c| .{ .x = c.x, .y = c.y } else null, - .petscii = if (comptime images_enabled) s.images.petscii else false, .view = s.vt.screens.active.pages.scrollbar().offset, .phase = h.phase, .started = h.started, @@ -268,14 +272,42 @@ pub fn parts(s: *const State) Term.Parts { }; } +/// The most bytes of a sequence its program began and has not ended (a +/// CSI, an OSC, a UTF-8 codepoint, a kitty graphics chunk: 4 KiB of payload) +/// that its stream keeps, so a snapshot taken between any two reads carries +/// it (`snapshot`). Past it the sequence is lost at a cut, as every one was +/// before. +pub const continuation_max = 64 * 1024; + /// Its emulator as the dump keeps it: ghostty's snapshot (both screens, -/// their history, styles, links and kitty images). A sequence its program -/// had begun and not ended is not kept: the snapshot is at the ground -/// state. `slim`, a join's dump (dump.zig `dumpJoin`): its size alone, an +/// their history, styles, links and kitty images), and the sequence its +/// program had begun and not ended, which `load` feeds again. `slim`, a +/// join's dump under screen state (dump.zig `dumpJoin`): its size alone, an /// emulator made afresh there, which its first delta replaces. pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void { if (slim) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); - try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); + var held: std.Io.Writer.Allocating = .init(gpa); + defer held.deinit(); + s.stream.writeContinuation(&held.writer) catch |err| switch (err) { + // Longer than it keeps: lost, as at the ground state. + error.ContinuationUnavailable, error.ContinuationDisabled => held.clearRetainingCapacity(), + error.WriteFailed => return error.OutOfMemory, + }; + const continuation: ghostty_vt.snapshot.Continuation = if (held.written().len > 0) .{ .bytes = held.written() } else .ground; + try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = continuation }); +} + +/// `snapshot`'s bytes decoded, the emulator not yet at its address. +fn decode(gpa: std.mem.Allocator, bytes: []const u8) !ghostty_vt.snapshot.Decoded { + if (bytes.len == 4) { + const size = std.mem.bytesToValue([2]u16, bytes[0..4]); + return .{ .terminal = try emulator(gpa, @max(1, size[0]), @max(1, size[1]), scrollback_max), .continuation = .ground, .history_rows = .{} }; + } + var reader: std.Io.Reader = .fixed(bytes); + return ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ + .max_continuation_bytes = continuation_max, + .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + }); } /// `snapshot`'s bytes and `parts` back into a new terminal, as `open` @@ -283,28 +315,81 @@ pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State { const out = try gpa.create(State); errdefer gpa.destroy(out); - var reader: std.Io.Reader = .fixed(bytes); - if (reader.buffer.len == 4) { - const size = std.mem.bytesToValue([2]u16, bytes[0..4]); - out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; - } else { - var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ - .max_continuation_bytes = 0, - .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, - }); - defer decoded.deinit(gpa); - out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; + var decoded = try decode(gpa, bytes); + defer decoded.deinit(gpa); + out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; + if (!install(out, decoded.continuation, saved)) { + out.stream.deinit(); + out.vt.deinit(gpa); + return error.OutOfMemory; + } + return out; +} + +/// Its emulator made again from its own snapshot, where it is, what pardes +/// keeps beside it kept: what a replica and its session do at a join, so +/// that both, and the joiner loaded from the session's, hold the same pages +/// (ghostty cuts rows into pages, and prunes whole ones, by its history, +/// which a snapshot does not carry). The snapshot's hash, which every side +/// compares; on an error it is as it was. +pub fn reload(s: *State) !u64 { + const gpa = s.gpa; + var bytes: std.Io.Writer.Allocating = .init(gpa); + defer bytes.deinit(); + try snapshot(s, gpa, &bytes.writer, false); + var decoded = try decode(gpa, bytes.written()); + defer decoded.deinit(gpa); + var saved = parts(s); + var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined; + @memcpy(reply[0..saved.reply.len], saved.reply); + saved.reply = reply[0..saved.reply.len]; + const kept = .{ s.changes, s.read, s.resize_to, s.direct }; + if (comptime images_enabled) s.images.deinit(gpa); + s.stream.deinit(); + s.vt.deinit(gpa); + s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2], .direct = kept[3] }; + // Short of room for its sequence in flight it goes on without it (lost + // at the next cut), as ghostty's stream does: not worth a terminal. + _ = install(s, decoded.continuation, &saved); + return joinHash(bytes.written()); +} + +/// What a join compares of a snapshot (`reload`): every record of it but +/// its kitty images' (tags 8 to 10, which ghostty's framing makes optional: +/// snapshot/record.zig, a u16 tag, a u32 length, a u32 CRC and the payload, +/// after a 10-byte envelope): an image by file or shared memory is the +/// session's alone (P32, `direct`), and no digest reads an image. +fn joinHash(bytes: []const u8) u64 { + const envelope = 10; + const head = 10; + var h: std.hash.Wyhash = .init(0); + h.update(bytes[0..@min(bytes.len, envelope)]); + var at: usize = envelope; + while (at + head <= bytes.len) { + const tag = std.mem.readInt(u16, bytes[at..][0..2], .little); + const end = @min(bytes.len, at + head + std.mem.readInt(u32, bytes[at + 2 ..][0..4], .little)); + if (tag < 8 or tag > 10) h.update(bytes[at..end]); + at = end; } + return h.final(); +} + +/// A decoded emulator at its address made a terminal: its stream wired, +/// the sequence in flight fed again, what pardes kept beside it put back; +/// whether its stream had all the room it wanted (`wire`). +fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool { if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { - if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); + if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = if (out.direct) .direct else .allWithTempDir(tempDir()); }; - out.wire(); + const whole = out.wire(); + switch (continuation) { + .ground => {}, + .bytes => |bytes| out.stream.nextSlice(bytes), + } const reply = saved.reply[0..@min(saved.reply.len, out.reply.len)]; @memcpy(out.reply[0..reply.len], reply); out.reply_len = @intCast(reply.len); out.reply_dropped = saved.reply_dropped; - out.mouse_cell = coordinate(saved.mouse_cell); - out.images = if (images_enabled) .{ .petscii = saved.petscii } else {}; const h = &out.stream.handler; h.phase = saved.phase; h.started = saved.started; @@ -321,7 +406,17 @@ pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) const screen = out.vt.screens.active; const bottom = screen.pages.scrollbar().offset; screen.scroll(.{ .delta_row = @as(isize, @intCast(saved.view)) - @as(isize, @intCast(bottom)) }); - return out; + return whole; +} + +/// Its program's kitty images by direct data alone from now on: the +/// emulator of a replica that is not the session (P32). +pub fn direct(s: *State) void { + if (comptime !images_enabled) return; + s.direct = true; + inline for (.{ .primary, .alternate }) |which| { + if (s.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .direct; + } } /// The allocator it was opened with, its own from then on. @@ -607,10 +702,13 @@ pub fn paste(state: ?*const State, text: []u8) [3][]const u8 { /// 1015 urxvt, 1005 UTF-8, else X10) how, modifiers as shift+4, meta+8, /// ctrl+16. `col`,`row` are the 0-based grid cell; a drag that left the /// grid is reported clamped to its edge, motion only when the cell -/// changed. Empty when the program does not hear of it. -pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { +/// changed from `last`, the cell it last heard of (its pane's, which a +/// rollback puts back). Empty when the program does not hear of it. +pub fn mouse(state: *State, last: *?Term.Parts.Coordinate, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { const input = ghostty_vt.input; var writer = std.Io.Writer.fixed(buf); + var cell = coordinate(last.*); + defer last.* = if (cell) |c| .{ .x = c.x, .y = c.y } else null; var opts: input.MouseEncodeOptions = .{ .event = state.vt.flags.mouse_event, .format = state.vt.flags.mouse_format, @@ -620,7 +718,7 @@ pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Ter .padding = .{}, }, .any_button_pressed = any_pressed, - .last_cell = &state.mouse_cell, + .last_cell = &cell, }; // A release is always reported; the rest only over the grid, or held. if (action == .release) opts.any_button_pressed = true; @@ -649,7 +747,7 @@ pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Ter /// program: its mouse report while it tracks the mouse, else, on the /// alternate screen, an arrow key in the cursor keys' mode (none for a /// sideways turn). Null when the wheel is not the program's (`Modes.wheel`). -pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 { +pub fn wheel(state: *State, last: *?Term.Parts.Coordinate, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 { const now = modes(state); if (!now.wheel) return null; const m = &state.vt.modes; @@ -658,7 +756,7 @@ pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: .wheel_down => if (m.get(.cursor_keys)) "\x1bOB" else "\x1b[B", else => null, }; - return mouse(state, buf, .press, turn, mods, col, row, false); + return mouse(state, last, buf, .press, turn, mods, col, row, false); } /// The whole scrollback as plain text, `gpa`-owned: what a terminal's body @@ -731,11 +829,14 @@ pub fn close(state: *State) void { } /// A terminal pane's emulator, `cols` by `rows`, as `open` makes one. -fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { +/// How much history a terminal keeps, in bytes of ghostty's pages. +const scrollback_max = 16 * 1024 * 1024; + +fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !ghostty_vt.Terminal { return ghostty_vt.Terminal.init(terminalIo(), gpa, .{ .cols = cols, .rows = rows, - .max_scrollback_bytes = 16 * 1024 * 1024, + .max_scrollback_bytes = history, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, // Every kitty medium, as ghostty and kitty take them: a file (t=f), // a temporary file it then deletes (t=t, in the temp directory and @@ -750,12 +851,22 @@ fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { /// A new emulator, `cols` by `rows`, allocated with `gpa`, its own from /// then on (`State.gpa`). pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { + return openKeeping(gpa, cols, rows, scrollback_max); +} + +/// `open`, keeping `history` bytes of history (the tests below fill a +/// smaller one). +fn openKeeping(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !*State { const state = try gpa.create(State); errdefer gpa.destroy(state); // Every other field its default, never what the heap had: a digest // reads them, and two replicas must agree (core/replica.zig). - state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined }; - state.wire(); + state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows, history), .stream = undefined }; + if (!state.wire()) { + state.stream.deinit(); + state.vt.deinit(gpa); + return error.OutOfMemory; + } return state; } @@ -1456,21 +1567,6 @@ pub fn due(state: *const State) ?u64 { return state.images.animation_due_ms; } -/// The Petscii builtin on a terminal: its kitty graphics as glyph art, -/// or back to pixels where the shell draws pixels. -pub fn togglePetscii(state: *State) void { - if (comptime !images_enabled) return; - state.images.petscii = !state.images.petscii; -} - -/// Whether the pane draws its kitty graphics as glyph art by choice; null -/// for a pane with no emulator. -pub fn petscii(maybe: ?*const State) ?bool { - if (comptime !images_enabled) return null; - const state = maybe orelse return null; - return state.images.petscii; -} - /// Whether the screen showing holds any kitty graphics image. pub fn hasImages(maybe: ?*const State) bool { if (comptime !images_enabled) return false; @@ -1522,3 +1618,186 @@ test "the luminance table answers exactly what ghostty computes" { } } } + +/// Its snapshot as the dump writes it, `gpa`'s (the tests below). +fn snapshotOf(gpa: std.mem.Allocator, s: *const State) ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try snapshot(s, gpa, &out.writer, false); + return out.toOwnedSlice(); +} + +/// Two terminals as a replica compares them: their snapshots' bytes, what +/// pardes keeps beside the emulator, and the digest. +fn expectSame(gpa: std.mem.Allocator, a: *const State, b: *const State) !void { + const x = try snapshotOf(gpa, a); + defer gpa.free(x); + const y = try snapshotOf(gpa, b); + defer gpa.free(y); + try std.testing.expectEqualSlices(u8, x, y); + var ma: [marks_len]u8 = undefined; + var mb: [marks_len]u8 = undefined; + try std.testing.expectEqualSlices(u8, marksOf(a, &ma), marksOf(b, &mb)); + try std.testing.expectEqualSlices(u8, a.reply[0..a.reply_len], b.reply[0..b.reply_len]); + var ha: std.hash.Wyhash = .init(0); + var hb: std.hash.Wyhash = .init(0); + digest(a, &ha, true); + digest(b, &hb, true); + try std.testing.expectEqual(ha.final(), hb.final()); +} + +test "a snapshot taken inside a sequence carries it: over pardes's own handler the load continues as the terminal fed whole" { + // ghostty promises the continuation for its standard handler; pardes's + // MarkedHandler wraps it (OSC 133 marks, erases): cut at every byte of + // a CSI, an OSC (a link, pardes's own marks), a UTF-8 codepoint, a + // kitty graphics payload (APC) and a device query. + const gpa = std.testing.allocator; + const streams = [_][]const u8{ + "a\x1b[38;2;10;20;30mcolour\x1b[0m b", + "\x1b]8;;https://example.com/x\x1b\\link\x1b]8;;\x1b\\ c", + "x\u{1F469}\u{200D}\u{1F4BB}y \u{6F22}\u{5B57} \u{E9}", + "\x1b_Ga=T,i=7,f=24,s=1,v=1;AAAA\x1b\\ after", + "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07ls\r\n\x1b]133;C;aid=pardes\x07out\r\n\x1b]133;D;0;aid=pardes\x07", + "q\x1b[6n\x1b[c\x1b[16t z", + }; + for (streams) |stream| for (1..stream.len) |cut| { + const whole = try open(gpa, 24, 5); + defer close(whole); + whole.stream.nextSlice(stream[0..cut]); + whole.stream.nextSlice(stream[cut..]); + const cutting = try open(gpa, 24, 5); + defer close(cutting); + cutting.stream.nextSlice(stream[0..cut]); + const bytes = try snapshotOf(gpa, cutting); + defer gpa.free(bytes); + const loaded = try load(gpa, bytes, &parts(cutting)); + defer close(loaded); + loaded.stream.nextSlice(stream[cut..]); + expectSame(gpa, whole, loaded) catch |err| { + std.debug.print("cut at byte {d} of {f}\n", .{ cut, std.ascii.hexEscape(stream, .lower) }); + return err; + }; + }; +} + +/// What the join tests below stream: plain text, a build's log, and heavy +/// colour and links (a truecolour a cell, a link a word, marks piled on +/// letters, wide characters: what runs a page out of room for styles, +/// links and graphemes), `lines` of it, no clear. +const Corpus = enum { text, logs, heavy }; + +fn corpus(gpa: std.mem.Allocator, which: Corpus, lines: usize) ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + var prng: std.Random.DefaultPrng = .init(@as(u64, @intFromEnum(which)) + 11); + const random = prng.random(); + const words = [_][]const u8{ "the", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog", "./core/replica.zig:1234:", "error:", "expected", "\u{6F22}\u{5B57}", "na\u{EF}ve" }; + for (0..lines) |i| switch (which) { + .text => { + for (0..random.uintLessThan(usize, 18)) |_| try w.print("{s} ", .{words[random.uintLessThan(usize, words.len)]}); + try w.print("{d}\r\n", .{i}); + }, + .logs => try w.print("[{d:>3}%] \x1b[32mBuilding CXX object\x1b[0m src/CMakeFiles/core.dir/module_{d}.cpp.o{s}\r\n", .{ i * 100 / lines, i, if (i % 9 == 0) " \x1b[1;33mwarning:\x1b[0m unused variable" else "" }), + .heavy => switch (i % 3) { + 0 => { + for (0..100) |x| try w.print("\x1b[38;2;{d};{d};{d}m{c}", .{ (i * 7 + x * 3) % 256, (i * 13 + x * 5) % 256, (x * 11 + i) % 256, @as(u8, @intCast(97 + (x + i) % 26)) }); + try w.writeAll("\x1b[0m\r\n"); + }, + 1 => { + for (0..18) |x| try w.print("\x1b]8;;https://example.com/{d}/{d}\x1b\\w{d}\x1b]8;;\x1b\\ ", .{ i, x, x }); + try w.writeAll("\r\n"); + }, + else => { + for (0..40) |x| { + try w.writeByte(@intCast(97 + (x + i) % 26)); + for (0..1 + x % 6) |j| try w.print("{u}", .{@as(u21, @intCast(0x300 + (x * 3 + j + i) % 0x6f))}); + } + try w.writeAll(" \u{6F22}\u{5B57}\u{6F22}\u{5B57} \u{1F469}\u{200D}\u{1F4BB}\r\n"); + }, + }, + }; + return out.toOwnedSlice(); +} + +/// `bytes[from..to]` fed in reads of 4 KiB, and two reflows on the way +/// at `stops` (to a little over half the width and three rows taller, then +/// back), as the join tests' every side takes them. +fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2]usize) void { + const cols = s.vt.cols; + const rows = s.vt.rows; + var at = from; + while (at < to) { + if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, false); + if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, false); + var end = @min(to, at + 4096); + for (stops) |stop| if (at < stop and stop < end) { + end = stop; + }; + s.stream.nextSlice(bytes[at..end]); + at = end; + } +} + +fn sameSnapshot(gpa: std.mem.Allocator, a: *const State, b: *const State) !bool { + const x = try snapshotOf(gpa, a); + defer gpa.free(x); + const y = try snapshotOf(gpa, b); + defer gpa.free(y); + return std.mem.eql(u8, x, y); +} + +test "a join at a cut: every side reloaded from its own snapshot holds the same terminal as the joiner, after more bytes and after two reflows; a joiner nobody reloaded for with heavy colour does not" { + // The sizing pass's join check (reports/pardes-term-bytes.md, section 2) + // in the tree: a scrollback past its limit (pruned a page at a time, + // by the history of its pages), cut at a random read boundary, often + // inside a sequence. + const gpa = std.testing.allocator; + var prng: std.Random.DefaultPrng = .init(29); + const random = prng.random(); + var heavy_apart: usize = 0; + for ([_]Corpus{ .text, .logs, .heavy }, [_]usize{ 6000, 6000, 3000 }) |which, lines| { + const bytes = try corpus(gpa, which, lines); + defer gpa.free(bytes); + for (0..2) |_| { + const cut = bytes.len / 3 + random.uintLessThan(usize, bytes.len / 3); + const mid = cut + (bytes.len - cut) / 2; + const stops: [2]usize = .{ mid + (bytes.len - mid) / 3, mid + 2 * (bytes.len - mid) / 3 }; + // The session, and a replica that was there from the start. + const session = try openKeeping(gpa, 120, 40, 1 << 20); + defer close(session); + const there = try openKeeping(gpa, 120, 40, 1 << 20); + defer close(there); + feedReflowing(session, bytes, 0, cut, stops); + feedReflowing(there, bytes, 0, cut, stops); + // The same join made without the reload: the session as it + // would go on, and a joiner loaded from its snapshot. + const lineage = try openKeeping(gpa, 120, 40, 1 << 20); + defer close(lineage); + feedReflowing(lineage, bytes, 0, cut, stops); + const before = try snapshotOf(gpa, session); + defer gpa.free(before); + const unreloaded = try load(gpa, before, &parts(session)); + defer close(unreloaded); + // The join as it is made: every side reloads, the joiner loads + // the session's snapshot taken after (the join's dump). + const hash = try reload(session); + try std.testing.expectEqual(hash, try reload(there)); + try std.testing.expectEqual(hash, joinHash(before)); + const after = try snapshotOf(gpa, session); + defer gpa.free(after); + const joiner = try load(gpa, after, &parts(session)); + defer close(joiner); + for ([_]*State{ session, there, joiner, unreloaded, lineage }) |s| feedReflowing(s, bytes, cut, mid, stops); + try expectSame(gpa, session, there); + try expectSame(gpa, session, joiner); + if (!try sameSnapshot(gpa, lineage, unreloaded)) heavy_apart += @intFromBool(which == .heavy); + for ([_]*State{ session, there, joiner }) |s| feedReflowing(s, bytes, mid, bytes.len, stops); + try expectSame(gpa, session, there); + try expectSame(gpa, session, joiner); + } + } + // The fault the reload mends is real: a joiner nobody reloaded for is + // another terminal once heavy colour has pruned pages cut otherwise. + try std.testing.expectEqual(2, heavy_apart); +} diff --git a/core/tracy.zig b/core/tracy.zig index 3b0b8621..56429b1b 100644 --- a/core/tracy.zig +++ b/core/tracy.zig @@ -5,7 +5,7 @@ const std = @import("std"); const builtin = @import("builtin"); -pub const enable = if (builtin.is_test) false else @import("pardes_config").enable_tracy; +pub const enable = if (builtin.is_test) false else @import("pardes_options").enable_tracy; const SourceLocation = extern struct { name: ?[*:0]const u8, diff --git a/core/views.zig b/core/views.zig index 9985288d..89dcb454 100644 --- a/core/views.zig +++ b/core/views.zig @@ -33,7 +33,7 @@ pub const max = 4; /// A pane's fields that are each view's own: where it is in the view's /// layout, which of its texts has the keyboard, how far it is scrolled, and /// what the view's step measured of it (its tag's rows, its bands). -const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "attached_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices", "pan", "follow_scroll" }; +const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices", "pan", "follow_scroll" }; /// The body's: its cursor, selections and mode. Its undo stays the pane's. const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" }; @@ -43,7 +43,7 @@ pub const PaneView = struct { focus: Pane.Focus = .body, vweight: f32 = 1, collapsed: bool = false, - attached_to: ?u32 = null, + docked_to: ?u32 = null, hscroll: i32 = 0, tag_scroll: u16 = 0, tag_top: u16 = 0, diff --git a/dev/Host.zig b/dev/Host.zig index 24df3895..a23c9ef5 100644 --- a/dev/Host.zig +++ b/dev/Host.zig @@ -28,9 +28,6 @@ pub const VTable = struct { /// Upgrade: this process exec'd as the pardes installed since, at /// the step's end (upgrade.zig); `pane` hears why if it cannot be. upgrade: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id) void = null, - /// Whether a newer pardes is installed at the path this process - /// started from, to be said once (upgrade.zig): asked at a focus-in. - newer_build: ?*const fn (ctx: ?*anyopaque) bool = null, spawn: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, cwd: []const u8) void = null, pty_write: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, bytes: []const u8) void = null, pty_resize: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, cols: u16, rows: u16) void = null, diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 49c412ba..c3272957 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -584,7 +584,7 @@ fn acknowledgeGuiFont(g: *const Gui, core: *pardes.Pardes) void { /// A replica client's font is the window's raster state: it follows the /// session's request by the face's name on this machine (fonts.fromSession), /// never acknowledging it or otherwise changing the replicated core. -fn syncReplicaFont(g: *Gui, f: *const @FieldType(pardes.config.Runtime, "font"), gpa: std.mem.Allocator) bool { +fn syncReplicaFont(g: *Gui, f: *const @FieldType(pardes.config.Settings, "font"), gpa: std.mem.Allocator) bool { const path = f.requested_path.get(); const name = f.requested_name.get(); if (path.len == 0 and name.len == 0) return false; @@ -3312,7 +3312,7 @@ fn kindJob(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void { fn search(ctx: ?*anyopaque, gen: u32) void { const s = shellOf(ctx); if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.queue, Queue.pushSearch); - pardes.Stream.runHere(s.core, gen); + pardes.Stream.runHere(s.core, gen, true); } /// Handover `seq`'s dump to its file, and a worker to carry it to another @@ -5622,7 +5622,7 @@ fn cursorDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, /// The triangle overlay: the cursor's glide, over everything. fn buildOverlay( g: *Gui, - which: pardes.config.Runtime.Pet, + which: pardes.config.Settings.Pet, trail_on: bool, surface: *const pardes.Surface, now_ns: u64, @@ -5671,7 +5671,7 @@ fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u6 /// The workspace tag's pet (the Pet setting, gui/pet.zig): in the blank /// end of the grid's first row, past the tag's text, in the tag's colours, /// on the window's own clock. Nothing of it reaches the core. -fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { +fn appendWorkspacePet(g: *Gui, which: pardes.config.Settings.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { const kind: pet.Kind = @fromBackingInt(@backingInt(which)); if (kind == .off or surface.rows == 0 or surface.cols == 0) { g.pet_state = .{}; diff --git a/dev/jump_trail.zig b/dev/jump_trail.zig index 25eba636..05664ec1 100644 --- a/dev/jump_trail.zig +++ b/dev/jump_trail.zig @@ -4,7 +4,7 @@ //! the cursor of the Surface it shows, frame after frame, and times the fade //! on its own clock; the tty tints those cells' ground toward the text, the //! window draws over them. Nothing of it reaches the core, which keeps the -//! setting alone (config.Runtime.jump_trail). +//! setting alone (config.Settings.jump_trail). const std = @import("std"); pub const life_ns: u64 = 120 * std.time.ns_per_ms; diff --git a/dev/lsp/lsp_client.zig b/dev/lsp/lsp_client.zig index 83aea44f..4ad8dace 100644 --- a/dev/lsp/lsp_client.zig +++ b/dev/lsp/lsp_client.zig @@ -783,8 +783,13 @@ fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *s if (!try timedWait(c, io, startup_deadline)) break; } if (starting or c.loading or c.progress > 0) { - tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); - post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); + // Said only when the server says it: a startup window that ran + // out with no word of loading is asked again quietly, and the + // message row keeps what it had (an empty answer is an answer). + if (c.loading or c.progress > 0) { + tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); + post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); + } while ((c.loading or c.progress > 0) and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); out.end = before; try attempt(c, io, si, arena, req, out, tr, g); diff --git a/dev/macos/Sources/AppDelegate.swift b/dev/macos/Sources/AppDelegate.swift index 767d3766..4168999f 100644 --- a/dev/macos/Sources/AppDelegate.swift +++ b/dev/macos/Sources/AppDelegate.swift @@ -132,7 +132,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { // to change the day macos_min_version reaches 14. NSApp.activate(ignoringOtherApps: true) - var runtime = pardes_runtime_s( + var runtime = pardes_callbacks_s( userdata: Unmanaged.passUnretained(self).toOpaque(), wakeup: { ud in // A pty reader thread. Every other function in pardes.h is diff --git a/dev/root.zig b/dev/root.zig index 08c246fb..fb1d1ad9 100644 --- a/dev/root.zig +++ b/dev/root.zig @@ -26,9 +26,9 @@ test { _ = glide; // The frontends', which main.zig's test block collected: a shell's // build (shell-test); the core without a terminal never compiled them. - if (comptime @import("term_options").terminal) { - if (comptime @import("pardes_config").platform == .tui) _ = tui; - if (comptime @import("pardes_config").platform == .gui) _ = gui; + if (comptime @import("pardes_options").terminal) { + if (comptime @import("pardes_options").platform == .tui) _ = tui; + if (comptime @import("pardes_options").platform == .gui) _ = gui; _ = vaxis_input; _ = host_io.Ptys; } diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 25172b4a..5c1945e6 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1251,7 +1251,6 @@ const Shell = struct { .detach = detach, .adopt = PtyCalls.adopt, .upgrade = upgradeAsked, - .newer_build = newerBuild, .spawn = PtyCalls.spawn, .pty_write = PtyCalls.write, .pty_resize = PtyCalls.resize, @@ -1365,12 +1364,6 @@ const Shell = struct { const PtyCalls = host_io.Ptys.Calls(Shell); - /// A client's own build is not the session's to say (its core's host - /// is the session's, through the tape). - fn newerBuild(ctx: ?*anyopaque) bool { - return of(ctx).client == null and upgrade.newer(); - } - fn upgradeAsked(ctx: ?*anyopaque, id: pardes.Pane.Id) void { const pane = id.index(); const s = of(ctx); @@ -1700,7 +1693,10 @@ const Shell = struct { c.link.gone = true; return true; }, - .focus_in => s.feed(.{ .focus = true }), + .focus_in => { + s.feed(.{ .focus = true }); + if (s.client == null) upgrade.noticeNewer(s.core); + }, .focus_out => { s.feed(.pointer_leave); s.feed(.{ .focus = false }); @@ -2085,7 +2081,7 @@ const Shell = struct { fn search(ctx: ?*anyopaque, gen: u32) void { const s = of(ctx); if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); - pardes.Stream.runHere(s.core, gen); + pardes.Stream.runHere(s.core, gen, true); } /// A draw (api.draw) on a worker, as a job is. diff --git a/docs/ghostty-macos-notes.md b/docs/ghostty-macos-notes.md index 830d4b1f..3dc03265 100644 --- a/docs/ghostty-macos-notes.md +++ b/docs/ghostty-macos-notes.md @@ -56,10 +56,10 @@ comptime { The payoff is that adding a feature adds an enum case, not a struct field: hosts that do not implement it return `false` and the ABI never changed. Worth copying the day a fixed callback list starts growing. pardes has three callbacks today -— `wakeup`, `set_clipboard`, `read_clipboard` (`Runtime` in `runtime/macos.zig:153`) +— `wakeup`, `set_clipboard`, `read_clipboard` (`Callbacks` in `runtime/macos.zig:153`) — and does not need it yet. -Two userdata scopes, worth noting: the runtime struct's `userdata` is +Two userdata scopes, worth noting: the callbacks struct's `userdata` is app-scoped, and each surface carries its own. Swift round-trips both with `Unmanaged.passUnretained(self).toOpaque()` — libghostty never retains, so lifetime stays entirely on the Swift side. diff --git a/docs/ghostty-page-size.md b/docs/ghostty-page-size.md new file mode 100644 index 00000000..6e65f36a --- /dev/null +++ b/docs/ghostty-page-size.md @@ -0,0 +1,128 @@ +# ghostty: a terminal's state depends on the OS page size + +A report for upstream (https://github.com/ghostty-org/ghostty), against +the commit pardes pins (83fb95624b04, 1.4.0, `build.zig.zon`). pardes +patches its fetched copy at build time (build/patches.zig, `ghostty_page` +and `ghostty_mem`) until it is fixed there, if upstream wants it fixed. + +## What happens + +A page's memory is rounded up to the OS page (`src/terminal/page.zig`, +`Page.layout`): + +```zig +const total_size = alignForward(usize, meta_end, std.heap.page_size_min); +``` + +`page_size_min` is 4 KiB on x86-64 and aarch64 Linux, FreeBSD and x86-64 +macOS, and 16 KiB on aarch64 macOS (Zig's `std/heap.zig`). The rounding is +not only slack: `Capacity.adjust` fills the rounded size with rows +(`availableBytesForGrid` is `total_size` less the metadata), and a style +table that grows is sized to fill it too. A standard page is 401,408 bytes +on Linux and 409,600 on an Apple silicon Mac. The scrollback limit +(`max_scrollback_bytes`) counts these bytes and prunes a whole page at a +time, so the same bytes fed to two terminals of the same size keep +different history on the two machines, and the snapshot of either +records its own capacity hints. + +pardes meets it because a client of a session runs its own emulator on +the pty's bytes: a Mac client of a Linux session must end with the +session's terminal, row for row. + +## Measured + +A driver fed eight streams through pardes's own wrapper +(`core/term/terminal.zig`), at 120x40, in reads of 4,096 and 65,536 bytes, +resized to 61x43 at a third and back at two thirds; then the hash of +pardes's per-unit digest (the active screen's text, the history's extent, +the view, the cursor) and of ghostty's full snapshot. Linux x86-64 (SIMD +on and off) and FreeBSD 15.1 amd64 gave the same lines; the Mac +(Darwin 25.6, arm64): + +| stream | digest | snapshot | history rows, Linux / Mac | +|---|---|---|---| +| shell, 90 KB | equal | differs (a style capacity hint, 388 / 397, and its record's CRC) | 0 / 0 | +| TUI, 31 KB | equal | equal | 0 / 0 | +| source text, 3.1 MB | differs | differs | 25,323 / 25,264 | +| build logs, 1.6 MB | differs | differs | 15,531 / 15,495 | +| heavy colour and links, 10 MB | differs | differs | 14,201 / 13,024 | +| a colour a cell, a link a word, stacked marks, 9 MB | differs | differs | 4,296 / 3,716 | +| kitty images, raw RGBA, 8.4 MB | equal | equal | 0 / 0 | + +The active screen's text, the cursor and the modes are the same on both; +what differs is how much history is kept and, on the last stream, which +links were dropped for lack of room in a page (19,002 `start_hyperlink +OutOfSpace` on Linux, 19,750 on the Mac). The smallest streams that show +it: the first 601,027 bytes of the source text (the first prune) for the +history, the first 11,690 bytes of the shell stream (its page's style +table grows) for the snapshot alone. + +The same driver built for Linux with `std.options.page_size_min = 16 KiB` +gives the Mac's lines exactly, digest and snapshot, on every stream: the +page size is the whole cause. + +## The fix + +Round a page's size to 4 KiB on every target, whatever the OS page is: + +```diff +--- a/src/terminal/page.zig ++++ b/src/terminal/page.zig +@@ Page.layout +- const total_size = alignForward(usize, meta_end, std.heap.page_size_min); ++ const total_size = alignForward(usize, meta_end, 4 << 10); +@@ Page.init +- assert(l.total_size % std.heap.page_size_min == 0); ++ assert(l.total_size % (4 << 10) == 0); +--- a/src/terminal/mem.zig ++++ b/src/terminal/mem.zig +@@ decommit, recommit +- assert(memory.len % std.heap.page_size_min == 0); ++ assert(memory.len % (4 << 10) == 0); +``` + +Why the Mac is the one that changes: on Linux and FreeBSD, where +`page_size_min` is 4 KiB, the three lines are what they were, so their +terminals are byte for byte what they were (the same history, the same +cost); only an Apple silicon Mac's pages shrink to Linux's sizes. + +Why a Mac can: the length of a page's memory need not be a whole number of +OS pages. A page's memory is `mmap`ed (`Page.init`, `AllocPosix`) or a +pool item allocated alone by the page allocator (`UntouchedPool`, ghostty's +tagged allocator on Darwin, which rounds the mapping up to whole pages and +unmaps it the same way); the pointer stays 16 KiB aligned, as its type +says; only the length is shorter than the mapping. `madvise` (`decommit`, +`recommit`: `FREE_REUSABLE`, `FREE_REUSE`) acts on whole pages, and the +last page of a mapping is that page's alone, the slack included. What +asked for whole OS pages were three assertions, which now ask for 4 KiB: +in a safe build they failed at once on a Mac; in a fast one they were +promises to the optimiser. Nothing else in ghostty's terminal, its page +pool, its compression or its snapshot loader reads the rounding. + +With it, the Mac gives Linux's lines on every stream (and with the PNG fix +of docs/zstbi-fp-contract.md, the PNG stream too). + +## What it costs + +Nothing on Linux and FreeBSD. On an Apple silicon Mac a page's mapping +keeps up to 12 KiB it does not use (8 KiB for a standard page: 401,408 +bytes in 409,600), never touched, so never resident; the scrollback's +16 MiB budget counts the 4 KiB-rounded size, so a Mac now keeps Linux's +history (above: 25,323 rows of source text, 14,201 of heavy colour, where +it kept 25,264 and 13,024). + +Measured with the Edit: on Linux and FreeBSD the cross-check driver's +eighteen lines are the lines it gave before, page counts and page bytes +included; pardes-perf's per-operation counts are within 0.03% of the +base's (its terminal cells +0.007%); on the Mac a ReleaseSafe build of +the driver runs all eight streams, the full scrollbacks' pruning and +page reuse included, with no assertion, and gives Linux's lines. + +## Upstream today + +Not read beyond what is on this machine (no network). The pin, 83fb956 +(1.4.0), has the rounding at `page.zig:1770`. The newest other copy here, +`~/05-genizah/ghostty` at its `main` (e8e7fea1, 2026-06-16, 1.3.2-dev), is +OLDER than the pin and has the same line (`page.zig:1753`). So moving the +pin is no fix as far as can be seen from here; whether upstream changed +it after 1.4.0 is not known. diff --git a/docs/macos.md b/docs/macos.md index 44b77d67..98cd5312 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -85,7 +85,7 @@ copies had in common is the argument for the shared file existing: none set the pty master, so a program in one pane could read and write another pane's terminal and closing a master did not reliably hang its shell up. -That is why the runtime struct is three callbacks rather than a second vtable — +That is why the callbacks struct is three callbacks rather than a second vtable — and why two of the three are the clipboard: the pasteboard is AppKit's, in both directions, and is the one piece of IO the Zig side cannot reach for itself. @@ -128,7 +128,7 @@ is made of and what opens a path from argv or the Dock (`Look <path>`). it. `pardes_resize` also carries one cell in *physical* pixels, which only the native PDF placement path reads — pass the backing-store size, not points. -**Runtime callbacks.** `pardes_runtime_s` is a `userdata` and three functions, +**Callbacks.** `pardes_callbacks_s` is a `userdata` and three functions, copied by value during init so the struct need not outlive the call. `wakeup` means "your state moved, please pump me". `set_clipboard` hands over text to put on the pasteboard, borrowed for the duration of the call; it fires inside a tick diff --git a/docs/next-daemon.md b/docs/next-daemon.md index d93cbbea..37ba0241 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -9,8 +9,9 @@ Designed 2026-10-29 in discussion (the user, the coordinator, a survey agent), and built since, phase by phase (phases 1 to 6, then the -architecture steps): each phase's notes below say what was built, and where -it went otherwise than the design that follows. Where the build differs, the +architecture steps, then the reorganisation of 2026-11-17 to 19): each +phase's notes below say what was built, and where it went otherwise than +the design that follows; the reorganisation's notes are the last but two. Where the build differs, the design's line is kept and marked *Built otherwise*. What runs today, in the words ruled on 2026-11-17 (session, client, far, frontend, detached, attach), is the manual's "How pardes runs" (`docs/typ/running.typ`); where @@ -338,7 +339,7 @@ the ponytail lens: one on a plain terminal differ. The 223 comptime platform branches stay comptime: a session is one build, which the semantics hash says. - Each pane's, each view's own (`PaneView`): `vweight`, `collapsed` and - `attached_to` (a layout's); `focus`; the body's mode, cursor, + `docked_to` (a layout's); `focus`; the body's mode, cursor, selections, sticky column, pending normal command and find; a document's scroll, `hscroll` and size; and what the step measured for that view (`tag_rows`, `tag_top`, `tag_scroll`, `view`, `notices`), so a view drawn @@ -3358,7 +3359,10 @@ either kind. Decisions at the forks, with the ponytail lens: - **The wheel in a client moves a row a turn.** The window's glide and a touchpad's fraction run on the core's clock, which in a client is the session's and moves only with its units. ponytail: whole rows, no glide; - the local window's is unchanged. + the local window's is unchanged. *Built since:* the notch glides in a + client as in the session's own window (measured 2026-11-17, 5 frames, 0 + to -22 px): whole rows go to the session, and the picture moves between + them on the client's own clock (`dev/gui/gui.zig` `glideFrame`). - **A client says its frontend first** (`Event.frontend`: windowed, native images and patches; wire 16, client tag 0x20): the view the session opens for a joiner copies the live view's, and a window's view of a terminal's @@ -3610,7 +3614,7 @@ Not done, and why: touchpad's fractions are the client window's own picture, and only its whole rows go to the session (`gui.zig`, the test "detached trackpad scrolling keeps fractions local and queues whole rows for replication"); - a wheel's notch is still whole rows with no glide. + a wheel's notch glides too (above). - **The notice a client gets is in its title and its log, not its frame** (the session's words: joined again, let go, refused). The tty's draws them on its notice band, which the window's frame has no slot for @@ -4615,6 +4619,103 @@ After it, the query pane's two: min and six clients (late windows and a late terminal among them): no rejoin, no differing check, no panic. All pass. +## The reorganisation notes (2026-11-17 to 2026-11-19) + +The reorganisation (`.scratch/sketch/PARDES.md`, its rulings P12 to P30) +kept the design above: speculation and rollback, the session the only +orderer. The user's rulings it built on: a far client keeps instant local +echo and the replicated core stays (P12, P13); on a far client typing, +motions, edits and layout are instant and what has a side effect on the +system may take the round trip (P14); a client's yank fills the client's +clipboard, and a layout change beside a shell is instant (P16). And the +rule every later choice is measured by (P30): "keep the wire protocol +simple and raw, and the local state process it" (`docs/typ/building.typ`, +"The principle"). What was built, as it stands: + +- **The tree.** `src/` became four directories, each a module that names + the others: `core/` (`core/root.zig`, the core's struct + `core/Core.zig`), `dev/` (the frontends `dev/tui`, `dev/gui`, `dev/macos`, + and `dev/host_io.zig` cut into `Host`, `Shell`, `Inbox`, `KindJob`, + `Lsp`), `runtime/` (main, the daemon, the upgrade, 9P's transport, the + loops) and `abi/` (the wire, `plain`, `term`, the headers). A test + program runs its root module's tests, so a suite runs one a module. +- **The frontends draw from the frame.** A frontend reads the `Surface` + and one record beside it, `Facts` (`core/surface.zig`, filled by + `draw.place`), to draw and to turn input into events, never the core; + so a client no longer makes its view live to read it (`OwnView`, + `Replica.within` deleted). Its frame statistics are its runner's + (`FrameStats`), and `present` says whether it showed the frame + (`present_skipped` gone). Left reading the core: the window's hit + test, its close, a session window's font. +- **One client loop** (`runtime/client.zig`, `Loop(Frontend)`), which the + terminal's client (`Tty`) and the window's (`Client`) run: the joins and + the reader thread, and a pass of the frontend's calls (`own`, `again`, + `deadline`, `wait`, `present`, `copy`, `paste`, `open`, ...), written + once where `runClient` and `clientSession` each had their own. A client's + input is sent before it is applied (`Replica.pend`), and its yank, paste + and link are done on the client's machine. +- **One session loop** (`runtime/session.zig`, `Loop(Frontend)`), which + the terminal's and the window's own frontend (`Own`) run: the + allocators, the workers, the core, the prompt files, the 9P listener, + `Peers`, the pump and the unit, an Upgrade or a Restore, and one order + for the parts' end. The devices are still each frontend's. +- **The soak runs both** (`test/replicas.zig`): each client is + `client.Loop`, the session `session.Loop` over a frontend whose host is + the soak's delayed network (`Peers.threads` off: the soak does the + reader's and the writer's work in memory). It judges every stop against + `may_wait`, runs a frame corpus through a client (22 scenes, its frame + and `Facts` against a session's own), and ends each run with the + session's allocators' leak check. `replica.Authority` remains the + session's stand-in in the core's unit tests and the soak's side cases. +- **What a far client does at once.** A Host entry that returns nothing no + longer stops a speculation, but for those on `keeps_stopping` + (`core/tape.zig`); closing a pane learns from its open whether Recent + keeps the file (`File.State.on_disk`), with no stat; `n`/`N` in a kind's + pane step the rows' own places, asking the disk nothing; a pane switch + beside a shell that asked for focus events tells the program a round + trip later. What may wait is one list, `may_wait` (`core/replica.zig`), + each row with why, pinned by a test that walks every word, key and + gesture on four kinds of pane. +- **The session's facts** (its home, default shell and directory) are the + core's state, read once through the tape; `DumpDir`'s check and + `Font`/`Fonts` read the session's machine through it too. A count of + what `core/` asks of the machine is a test (`core/root.zig`, + `machine_lines`). +- **Nothing of a core is a process global**: `config.tab_now`, + `Addon.distrusted` and `Kind.draw_tokens` went (the tab is the core's + `settings.tab`, handed down; the distrusted list is the client's, + `Options.distrusted`; a draw's token is its slot's); a test walks + `core/` for container-level `var`s (`allowed_vars`). With it, two + faults a rollback met: a terminal's image cache on the epoch's allocator, + a non-plain kind's slot freed by a speculation. +- **Nothing a frame writes is read by a step.** A step read a pane's + notice bands and a big markdown text's tables as the last frame left + them; both are made from the step's state now (the tables read whole at + once, the budgeted reading deleted). `kept_out` (`core/root.zig`) names + every field out of the digest with who writes it, and `core/draw.zig`'s + test steps a core that draws and one that never does, digests equal. +- **An entry written once.** Each of the core's taped entries is a private + body with its public name beside it, + `pub const update = pardes.tape.taped(updateInner);`; the tape's `Input` + variant and the replay come from the body's parameters. Six stay by + hand, each with why. +- **The tape as a handle.** A core holds its tape as it holds its + allocator (`p.tape`, never null; `tape: *Tape` where no core is handed), + and the kinds, the addons, a directory's listing, the file system, the + core's own files and the smaller ones ask it so. The effects, the + budgets, the terminals and the process's `tape.on` are not moved yet. +- **A slot is a type** where it crosses the core's edge: `Pane.Id` and + `View.Id`, each an `enum(u8)`, in the entries, events, effects, the Host + table, the wire's welcome and the device messages. +- **Found by the real loops**: an idle client's quiet check woke its + session every 0.3 s for ever (now a check answered covers the units that + came while it was asked); an addon load under way in another live process + was taken for a crash (the mark is the loader's, `addon-loading.<pid>`); + a kind's draw landing after its pane closed was kept; the command line's + serve thread freed its core under a request; mvzr read past a pattern cut + short (`a{`), patched as it is fetched (`build/patches.zig`, + `docs/mvzr-bounds.md`). + ## Architecture step 6 notes: the rollback and the digest through the journal The clean-room plan's step 6 (`.scratch/clean-room/architecture.md` 9.4) diff --git a/docs/next-drag.md b/docs/next-drag.md index cfaa6c69..47ccdb0b 100644 --- a/docs/next-drag.md +++ b/docs/next-drag.md @@ -56,15 +56,15 @@ window it goes to is found by asking every registry session. at the pointer where SDL can place windows), in its own session, so it outlives the source and leaves no zombie. It waits (up to 15 s) for the child's registry entry to answer `status`; the child reads the dump before - it listens (gui.localSession), so then the file is removed and `handed` - is posted into `host_io.Inbox`. + it listens (runtime/session.zig's `Loop.run`), so then the file is removed and `handed` + is posted into `host_io.Inbox` (dev/Inbox.zig). - `Handover.finish`: taken, each carried pane is closed with `Pardes.removePane` (Del's rows rule: its rows go to its neighbour; a carried column's empty column is dropped); a pane whose revision changed since the dump is kept, unattached ("copied to …; edited on the way, kept here too"). Refused or failed: everything stays, the reason on the message row. One handover flies at a time. -- New option `--geometry=WxH[+X+Y]` (main.zig, `Options.geometry`). +- New option `--geometry=WxH[+X+Y]` (runtime/main.zig, `Options.geometry`). ### 3. A grip let go over another pardes window: it goes there diff --git a/docs/next-editor.md b/docs/next-editor.md index 120b4c09..e7168256 100644 --- a/docs/next-editor.md +++ b/docs/next-editor.md @@ -7,7 +7,7 @@ Decided 2026-11-17 on the coordinator's leans (survey: `.scratch/sketch/reports/editor-lib.md`); built the same day. One source of truth: the library runs the functions pardes runs, compiled from the -same files with `pardes_config.lib` set; nothing is copied for it. +same files with `pardes_options.lib` set; nothing is copied for it. ## The calls, as built diff --git a/docs/next-run.md b/docs/next-run.md index dc189bc6..06941026 100644 --- a/docs/next-run.md +++ b/docs/next-run.md @@ -11,7 +11,7 @@ stays as built; the vocabulary and the manual's page first, no code moved yet. Nothing in this note is built. What runs today, with a figure for each way of starting pardes, is the manual's "How pardes runs" (`docs/typ/running.typ`); the daemon's history is `docs/next-daemon.md`. -Line numbers are this tree's, 2026-11-17. +Line numbers are this tree's, 2026-11-19. ## The ruling @@ -38,7 +38,7 @@ docs/next-run.svg`). Today `pardes attach` is four mechanisms, picked by the daemon's `find` (`runtime/daemon.zig:901-972`) and by `main.zig`'s `attachTo` -(`runtime/main.zig:1774-1810`): a terminal handed to a detached terminal's +(`runtime/main.zig:1806-1842`): a terminal handed to a detached terminal's session, which draws on it in its own process while the attach process waits as its stub; a window's detached session asked to open its own window again, while the attach process exits; a client here, when the @@ -51,19 +51,19 @@ The reorganisation plan's option b, checked against this tree: | What goes | Where today | Lines, about | |---|---|---| -| A terminal handed to a session: the daemon's `attach` request and answer, the session's `attachTerminal`, the `attach` note and message | `daemon.zig:400-403`, `:431-437`, `:504-533`, `:883-897`; `tui.zig:105-107`, `:1065-1068`, `:1162-1167`, `:1373-1406`, `:1723`; `main.zig:1789-1810` | 110 | -| A window opened again in place | `gui.zig:540-544` (what it reopens with), `:982-1000` (`reopenWindow`), `:2534-2547` (`openTheWindow`), `:2753`, `:3275-3281` | 50 | -| The daemon choosing which session takes a frontend: `find`, its `other` answer, the use of `daemon.Kind` to match | `daemon.zig:901-972`, `:506-509` | 75 | -| The stub's second use: an attach process waiting on a session that is not its child (`stubWait`'s `child = false`, its `r` refusals) | `daemon.zig:561-616` in part (`:593-597`, `:613-615`) | 10 | +| A terminal handed to a session: the daemon's `attach` request and answer, the session's `attachTerminal`, the `attach` note and message | `runtime/daemon.zig:400-403`, `:431-437`, `:504-533`, `:883-897`; `dev/tui/tui.zig:107-109`, `:1037-1040`, `:1135-1140`, `:1354-1387`, `:1711`; `runtime/main.zig:1821-1842` | 110 | +| A window opened again in place | `dev/gui/gui.zig:550-557` (what it reopens with), `:1004-1022` (`reopenWindow`), `:2588-2601` (`openTheWindow`), `:2823`, `:3388-3394` | 50 | +| The daemon choosing which session takes a frontend: `find`, its `other` answer, the use of `daemon.Kind` to match | `runtime/daemon.zig:901-972`, `:506-509` | 75 | +| The stub's second use: an attach process waiting on a session that is not its child (`stubWait`'s `child = false`, its `r` refusals) | `runtime/daemon.zig:561-616` in part (`:593-597`, `:613-615`) | 10 | What does not go, against the plan's list: the upgrade record's terminal and window fields. A session born with a terminal still takes it across an -Upgrade (`tui.zig:1455-1463`, `upgrade.zig:101-117`), and a window's still -says whether it had its window (`gui.zig:2600`). Only the record's other -terminals (`tui.zig:1504-1523`, a build's from before 2026-11-06, when a +Upgrade (`dev/tui/tui.zig:1438-1446`, `runtime/upgrade.zig:101-117`), and a window's still +says whether it had its window (`dev/gui/gui.zig:2656`). Only the record's other +terminals (`dev/tui/tui.zig:1487-1506`, a build's from before 2026-11-06, when a second local terminal stopped being the session's) are already dead weight. -Detach of the session's own frontend stays too (`tui.zig:1346-1371`, -`gui.zig:2476-2485`, `:2521-2532`): it is how a session becomes detached. +Detach of the session's own frontend stays too (`dev/tui/tui.zig:1327-1352`, +`dev/gui/gui.zig:2530-2539`, `:2575-2586`): it is how a session becomes detached. `daemon.Kind` stays in the hello and in `pardes ps` (`tty` or `gui`). The plan counted 87 + about 60 + 67 lines for the first three rows; the @@ -102,15 +102,16 @@ what is true, and whether it was measured. for the wheel, measured (`.scratch/sketch/reports/pardes-measure.md` sections C and E): a notch in a client glides as it does in the session's own window (5 frames, 0 to -22 px, in both). Only whole rows - go to the session (`gui.zig:2147-2161`; its comment and - `docs/next-daemon.md`'s GUI replica notes still say "no glide"); the + go to the session (`dev/gui/gui.zig:2200-2214`; its comment still says + "no glide", which `docs/next-daemon.md`'s GUI replica notes said too + until 2026-11-19); the picture moves between them on the client's own clock (`glideFrame`, - `gui.zig:3544`). A touchpad's fractions are the client window's own + `dev/gui/gui.zig:3673`). A touchpad's fractions are the client window's own picture too (the test "detached trackpad scrolling keeps fractions local - and queues whole rows for replication", `gui.zig:8042`). Fonts: a client follows the session's font request by + and queues whole rows for replication", `dev/gui/gui.zig:8190`). Fonts: a client follows the session's font request by the face's name when that face is installed on its machine - (`gui.zig:580-608`, `syncReplicaFont`); its opacity is its own (not in - the client's per-frame chores, `gui.zig:1311-1323`). The note said "keeps + (`dev/gui/gui.zig:595-623`, `syncReplicaFont`); its opacity is its own (not in + the client's per-frame chores, `dev/gui/gui.zig:1296-1322`). The note said "keeps its own font"; it is corrected there. Measured: a face the client lacks leaves it at its old face and its old size, and it diverged and joined again (2 runs of 2, cause not found). @@ -122,29 +123,32 @@ what is true, and whether it was measured. ## A session registering again -Today a session says hello once, at its start (`main.zig:1535-1563`), or -on its link after an Upgrade (`daemon.zig:392-398`). When the daemon dies -the session's reader sees the link end (`daemon.zig:419-425`) and nothing +Today a session says hello once, at its start (`runtime/main.zig:1567-1595`), or +on its link after an Upgrade (`runtime/daemon.zig:392-398`). When the daemon dies +the session's reader sees the link end (`runtime/daemon.zig:419-425`) and nothing dials again, so the session runs on unlisted: `pardes ps` and attach do not find it, Detach and Adopt refuse, and its frontend closing ends it -(`tui.zig:1711-1721`, `gui.zig:1784`). The next daemon knows only the +(`dev/tui/tui.zig:1699-1709`, `dev/gui/gui.zig:1839`). The next daemon knows only the sessions that start after it. The work: when `gone` is set, the session's loop (which calls -`daemon.watch` each iteration already, `tui.zig:1115`, `gui.zig:1154`) +`daemon.watch` each iteration already, `runtime/session.zig:115`, `:133-135`) dials again, starting a daemon if none answers (`daemon.connect(true)`), says its hello with its state, sends a dup of every pty master it holds -(at most 64 fds a message, `daemon.zig:37`), and its clients' pids. What +(at most 64 fds a message, `runtime/daemon.zig:37`), and its clients' pids. What cannot come back: the shells of sessions killed earlier, which only the dead daemon held. ## `--detach` forking -Today `--detach` is the launch process itself (`main.zig:1502-1537`): it -blocks the shell unless backgrounded by hand, it stays the job of the -terminal it was typed in, and a window's detached session ends on that -terminal's hangup (no handler of its own: `9p_io.zig:704-729`). The work: -fork as `daemon.forkSession` does (`daemon.zig:663-698`), `setsid` in the +Today `--detach` is the launch process itself (`runtime/main.zig:1517-1569`): it +blocks the shell unless backgrounded by hand, and it stays the job of the +terminal it was typed in. `pardes-gui --detach` runs the `pardes` beside +it in its place (`runtime/main.zig:1518-1534`), so a window's binary is a +detached session only where no `pardes` is beside it, and that one ends +on its terminal's hangup (no handler of its own: +`runtime/9p_io.zig:704-729`). The work: +fork as `daemon.forkSession` does (`runtime/daemon.zig:663-698`), `setsid` in the child, its stdin, stdout and stderr on `/dev/null`, and the parent printing the session's name and exiting 0, with no stub (nothing waits on it). For the window's build the fork comes before SDL starts. Then @@ -181,7 +185,7 @@ session takes back. - Re-registration: dial again at once and back off, or only when something needs the daemon (a Detach, an Adopt, the frontend closing)? - `--detach` with no daemon starts a session nothing can attach to - (`main.zig:1535-1537` ignores the failed registration). Refuse, or keep + (`runtime/main.zig:1567-1569` ignores the failed registration). Refuse, or keep it as a 9P-only session? - `pardes ps` says "has a frontend" for a session with a frontend of its own (the daemon's list, and so /sessions, still says `attached`, a wire diff --git a/docs/next-terminal.md b/docs/next-terminal.md index 26996897..ad21ef9b 100644 --- a/docs/next-terminal.md +++ b/docs/next-terminal.md @@ -184,9 +184,9 @@ What differs from the plan above, and why: - **The ops are a compile-time constant, not handed over at start.** `Term.ops` (core/Term.zig:18) is `&@import("term").ops` when the build's - `term_options.terminal` says the core has a terminal, null otherwise. + `pardes_options.terminal` says the core has a terminal, null otherwise. Every core module but core-test's is given `term`; core-test's - (`core_lean` in build.zig) is not, and its `term_options` say so. A + (`core_lean` in build.zig) is not, and its `pardes_options` say so. A run-time `Pardes.Options.terminal` would have put the table in every test's options and every host's start for no gain: no build ever has two terminals, and a null known at compile time drops the dead code. @@ -230,7 +230,7 @@ What differs from the plan above, and why: of them fail for want of a terminal (they open a shell or a command pane, read the emulator, or index the classic boot's three shells) and say so on their first line (`if (pardes.Term.ops == null) return - error.SkipZigTest; // a shell`), and ninep/testing.zig's `withTerm` + error.SkipZigTest; // a shell`), and ninep/harness.zig's `withTerm` once for its 29. The rest run. core-test: 810 of 949 run, 139 skip; `shell-test` runs all of them with the terminal. The 28 tests that read terminal.zig's own state through a core are in test/terminal.zig diff --git a/docs/next-tests.md b/docs/next-tests.md index 2266b06a..7da60470 100644 --- a/docs/next-tests.md +++ b/docs/next-tests.md @@ -13,7 +13,7 @@ agent's survey. The `e2e` line (kbdin, mousein) is its first step. `mousein`), the process (flags, daemon, attach, signals, terminal bytes), and files on disk and effects. A rewrite that keeps those keeps its tests. - **T1, in-process 9P, is the main tier.** The core is driven only through - `serveFs` (core/ninep/testing.zig's `call`, `rd`, `wr`): as behavioural + `serveFs` (core/ninep/harness.zig's `call`, `rd`, `wr`): as behavioural as a client on a socket, and milliseconds a case. - **One process runner, not Python (the user, 2026-11-04):** test/process.zig's `Process` starts `pardes` detached (over its socket), in a pty, or as the diff --git a/docs/next-winmode.md b/docs/next-winmode.md index c2a01da8..1f7c87c2 100644 --- a/docs/next-winmode.md +++ b/docs/next-winmode.md @@ -36,13 +36,13 @@ Typed in one go, the `j` after `SPC d` lands 100-250 ms after the `d` waiting to see something happen. 400 ms clears a relaxed typist with margin and is still quick enough to read as "it is asking", not "it is broken". Key-hint popups elsewhere (which-key) wait a few hundred ms for the same reason. It is a compile-time -constant beside `del_question` (keys are compiled in); a Runtime setting +constant beside `del_question` (keys are compiled in); a `Settings` field would be one line in config if the author wants to tune it live. ## Tests - `window mode d deletes the outlined pane and asks k or j, c collapses - it, and the mode stays` (pardes.zig): c twice restores the height; d asks, + it, and the mode stays` (core/layout.zig): c twice restores the height; d asks, Esc keeps it, d j gives the rows below and the outline follows; d with one neighbour closes at once onto it; labels hold none of h j k l d c. - `the Del question shows only once its delay is up: a quick SPC d j never diff --git a/docs/render-pipeline.md b/docs/render-pipeline.md index 05bc8cfa..4f3cc7a5 100644 --- a/docs/render-pipeline.md +++ b/docs/render-pipeline.md @@ -15,7 +15,8 @@ frontend keeps the little it draws on its own. deadline (`nextWake`: a message's linger, the look-hover preview, a question's hint, a paused Grep, work that resumes a frame at a time); `now`; `poll_frame`; `render` and `present` only when a frame is owed - (`needs_frame`); and `post_present`, whose `Pardes.presented` lets a + (`needs_frame`; `present` says whether it showed the frame, and one it + held is owed again); and `post_present`, whose `Pardes.presented` lets a drag's moving end and a look-hover follow what is under the pointer now. - `advance(now)` steps `.tick`s a `frame_ns` (16 ms) at a time, for the work that resumes a frame at a time; a wait is jumped in one step. @@ -24,7 +25,12 @@ frontend keeps the little it draws on its own. owner and focus; a body's first line and the text it shows, `Region.line` and `Region.doc`), the layers a pixel shell draws at the tagline's pitch and with compact context rows, the placements, the - cursor and the palette (`Chrome`). Nothing on it moves. + cursor and the palette (`Chrome`). Nothing on it moves. Beside it, + `draw.place` fills one record, `Facts` (surface.zig): the view's size, + each open pane's rectangle, tag rows and kind, and the settings a + frontend draws by. A frontend draws, and turns its input into events, + from the Surface and its Facts, not from the core, so a client draws + its own view as a session's own frontend does. - A placement (surface.zig's `Placement`) is a picture over the cells, a pane's at a time and lowest first: its pixels (`raster`: RGBA, straight alpha), the part shown (`src`), the cells it lies over and is clipped to @@ -41,9 +47,10 @@ frontend keeps the little it draws on its own. ## The frontends' own -Each draws these on its own clock, from the Surface alone, and draws their -frames itself while they move (the last frame again: the tty's -`poll_frame`, the window's loop), pacing its own waits: +Each draws these on its own clock, from the Surface and its Facts alone, and draws their +frames itself while they move (the last frame again: a session's own +frontend through its host's `poll_frame`, a client's through the client +loop's `again`, runtime/client.zig), pacing its own waits: | what | tty | window | from | |---|---|---|---| @@ -55,9 +62,9 @@ frames itself while they move (the last frame again: the tty's | `Pet` | (unsupported) | a sprite in the workspace tag's blank end (gui/pet.zig) | the grid's first row; SDL's ticks | | a placement | a kitty image placed over its cells, or glyph art in them (Art.zig) without kitty graphics or when its pane asks | a texture by key, scissored to its cells, or glyph art when its pane asks | the frame's placements | -The settings these read are plain bytes in the core's settings, dumped -and replicated as any other; nothing a frontend keeps goes back to the -core. +The settings these read are the core's settings, plain bytes dumped and +replicated as any other, copied into the frame's Facts; nothing a frontend +keeps goes back to the core. ## The window's composition diff --git a/docs/search-proto-converge.md b/docs/search-proto-converge.md index ddc41196..da336f7c 100644 --- a/docs/search-proto-converge.md +++ b/docs/search-proto-converge.md @@ -15,7 +15,7 @@ only the prompts that are not search. | piece | file | lifted from | |---|---|---| -| attached panes: a group under its owner, rows from the owner alone, moving/folding/closing with it, seam drag, Dump/Restore, `Unattach` | `core/layout.zig` "Attached panes", `Pane.attached_to` | attached | +| attached panes: a group under its owner, rows from the owner alone, moving/folding/closing with it, seam drag, Dump/Restore, `Undock` | `core/layout.zig` "Attached panes", `Pane.docked_to` | attached | | places: every match tinted, rail ticks (B1 on a tick goes there), current selected and in view, smart-case regex, view-first sliced scan, silent wrap | `core/Places.zig`, `Pane.places` | incsearch (MatchSet) | | the query pane: line 1, its first word the source, live rows, preview, Enter/Esc/Del, reuse, settings | `core/Query.zig`, `Pane.query` | queryline, pick, live, preview, everywhere | | fuzzy names (files, recent, panes, declarations) | `core/Names.zig` | pick (its scorer, whole) | @@ -115,7 +115,7 @@ erases it and B2 / B3 on it take the word clicked, as on any row. **Enter** puts the keyboard on the current hit in its pane (the +Preview promoted in place: same slot, serial, rect, an unattached file pane from then on), fills `/`, and freezes the rows into ordinary text (tag ` Save -Unattach Del`). A `/` freezes its whole list (every place found first, 2000 +Undock Del`). A `/` freezes its whole list (every place found first, 2000 rows at most), a Grep every line it has. **Esc** while typing puts every view back, clears the places it fed and closes the pane, its rows back to the owner; a reused pane's frozen rows and their places come back instead. @@ -145,7 +145,7 @@ cursor on line 15000. | keystroke 1, `p` | Every `p` in the view tinted at once, the rest found a 4 ms slice a frame (the tag `1/38479+` until done); rail ticks fill in; the first `p` at or after the cursor selected in layout.zig (scrolled only if off screen). Rows: the lines holding `p`, each ` 15003 code`, from two before the current one, the current marked as the visited row, a note row above saying how many places come before them. | | keystroke 2, `a` | `pa`: tints, ticks and rows narrow (`1/10189`); the current is again the first at or after where `/` was pressed, not after the last preview. The pane is the same size, line 1 where it was. | | Ctrl-n / Ctrl-p | The next / previous `pa` current, selected in layout.zig; `2/10189`. | -| Enter | The keyboard on that `pa`, `pa` in `/`, the rows frozen (the whole list, 2000 rows), tag `+Search 2/10189 Save Unattach Del`; tints and ticks stay while the pane lives. Ctrl-o goes back to where `/` was pressed. | +| Enter | The keyboard on that `pa`, `pa` in `/`, the rows frozen (the whole list, 2000 rows), tag `+Search 2/10189 Save Undock Del`; tints and ticks stay while the pane lives. Ctrl-o goes back to where `/` was pressed. | | `n` | The next `pa` in layout.zig, `3/10189`, its row marked in the +Search. | | `N` | Back to `2/10189`; from the first, round to the last with no message. | | Esc (typing) | layout.zig's selection and scroll exactly as at `/`, tints and ticks gone, the +Search closed, its rows back to layout.zig. | diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 5273298e..9350b484 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -1,7 +1,8 @@ -// Building pardes, for contributors: platforms, options, the library, tests, -// the release gates and sending patches, then how the pieces fit: the core -// and its shells, the threads, the daemon and its sessions, the 9P engine, the -// listeners and mounts. +// Building pardes, for contributors: platforms, options, the patches to +// dependencies, the library, tests, the release gates and sending patches, +// then how the pieces fit: the principle, the tree, the core and its +// frontends, the loops, the tape, the checks, the threads, the daemon and its +// sessions, the 9P engine, the listeners and mounts. #import "style.typ": key, keys, btn, chord, word, tag, addr, file, cmd, doc, pairs For contributors: how pardes is built, tested and released, and how its @@ -9,7 +10,7 @@ pieces fit. To install it, see #doc("setup", section: "install"). = Platforms -Zig *0.17.0* (`build.zig.zon` pins `minimum_zig_version`). Dependencies are +Zig *0.17.1* (`build.zig.zon` pins `minimum_zig_version`). Dependencies are fetched and pinned by the manifest; the terminal build needs no system package. The SDL shell builds SDL3 and FreeType from source. Pictures and PDFs are addons, each its own step: `zig build image`, `zig build pdf` @@ -73,6 +74,22 @@ must share with its session; `pardes --help` lists every flag. [`-Dhelix-harness`], [reference executable for live differential tests; `HX_HARNESS`, else `hx-harness` on `PATH`], ) +== Patches to dependencies <dep-patches> + +A fault in a dependency is fixed in the dependency, never guarded in the +core. pardes builds a few with edits of its own, made as each is fetched: +`build/patches.zig` holds, for each patched file, a table of exact edits +(and a file to append, in `build/patches/`), which `tools/patch.zig` +applies at make time, so a fresh fetch is patched the same and a bump that +moves an anchor fails that file's step. Each table says why, edit by edit. + +#pairs( + [vaxis], [its input parser (no reply, split read or malformed sequence reaches the editor as typed text), its event queue (every blocked writer woken) and its render (a blank whose ink alone changed is not sent)], + [zstbi], [stb_image and its writer cut out: its resize alone is left, for a terminal PNG's downscale], + [ghostty], [kitty graphics: a path opened only once it is a regular file, shared memory non-blocking, an image no larger than a screen's storage], + [mvzr], [a step budget, a group's backtracking, `$` before `|`, the `**` Zig 0.17 removed, a class's range to `\xff`, and its reads past a pattern cut short; `docs/mvzr-group-backtrack.md` and `docs/mvzr-bounds.md` are the reports for upstream], +) + == As a library <library> A Zig package that depends on pardes is given one module and nothing of @@ -174,6 +191,9 @@ zig build lib-test the library, from a package that depends on pardes (t zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane) zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/), and the T1 runner's short run of random 9P requests +zig build replicas the soak: a session and clients in process, on the real + session and client loops, each client typing over a + delayed link (-- [--seeds N] [--clients C] [--rtt 30,80,207]) zig build process-test real sessions over their sockets: mounts, flags, shells (test/process/), and the tty's own cases, each a pardes in a pty against its golden (test/process/tty_*.zig, test/snapshots/); -Dplatform=gui runs the @@ -251,12 +271,60 @@ Mail patches to the list `~gbrls/[email protected]`; it is the preferred way to #link("https://git-send-email.io")[git-send-email.io] sets `git send-email` up. The mirrors (#doc("setup", section: "install")) are for cloning, as a GitHub one will be; pull requests are not the preferred route. -= The core and its shells += The principle <principle> + +The owner's rule, in their words: "keep the wire protocol simple and raw, +and the local state process it" (2026-11-19). Every design choice is +measured against it. + +What crosses between processes is raw and ordered: a client's keys and +gestures, and the session's steps, each with what the session's machine +answered inside it (a file's bytes, the clock, a directory's listing) as +the machine said it. Each process's own core turns them into state. Nothing +computed is shipped where the input that computes it can be, and bandwidth +is spent before correctness is. What follows from it in the tree today: + +- A client is a whole core, loaded once from the session's dump. It applies + its own input at once and replays the session's units over it, rolling + back where the session ordered otherwise; nothing it draws is sent to it. + A picture or a game is drawn by the process that shows it, from its own + addon's code. +- A step that asks the machine asks through the tape (#link(<tape>)[below]): + the session records the answer, a client's replay reads that answer and + not its own machine's. The session's home, shell and directory are state + of the core for the same reason. +- What may wait is what touches the session's machine; the lists that say + so are checked by a test (#link(<may-wait>)[below]). +- Nothing a frame writes is read by a step, and nothing of a core is a + process global, so a core that drew and one that did not, in this process + or another, step alike (#link(<core-checks>)[the checks]). +- The exceptions, each small and named: the dump a client joins from (it + cannot replay from the start); the digests and quiet checks (a check, not + state); and a terminal, which crosses as the session's screen state + (rows and their changes), not as the pty's bytes. + += The tree <tree> + +#pairs( + [`core/`], [the editor as a state machine: panes, layout, the frame, the 9P tree, the tape and the replica engine. Module `core`, rooted at `core/root.zig`; the core's struct is `core/Core.zig`, `pardes.Pardes`], + [`dev/`], [the devices: the frontends (`dev/tui`, `dev/gui`, the Mac app's Swift in `dev/macos`), the host's services (`dev/host_io.zig` and the files beside it: `Host`, `Shell`, `Inbox`, `KindJob`, `Lsp`), the file watcher, the fonts, the language servers' client. Module `dev`], + [`runtime/`], [what runs a session: a session's loop (`session.zig`) and a client's (`client.zig`), the daemon and the stub, the upgrade, the crash file, the 9P listener and client (`9p_io.zig`). Module `runtime`; beside it each product's root, a module of its own: `runtime/main.zig` (`pardes`, `pardes-gui`) and `runtime/macos.zig` (the Mac's library)], + [`abi/`], [what crosses a process or a language: the replica stream (`abi/wire.zig`, module `wire`), the records the core and the terminal share (`plain.zig`), the terminal's table (`term.zig`), the addon's header and module, `pardes.h`], +) + +The modules name each other. A Zig test program runs the tests of the +module it is rooted at, so `core-test` and `shell-test` run one program a +module (core, dev, runtime, wire, and for `shell-test` `runtime/main.zig`'s); +each module's `root.zig` lists the files whose tests it runs. Beside the +four: `addons/`, `build/` (the build script's parts, the patches), `test/`, +`tools/`, `shaders/`, `vendor/`, `assets/` and `docs/`. + += The core and its frontends -One core, three shells (tui, gui, macos). The core owns -editing, layout, rendering and the virtual filesystem it serves over 9P; a shell turns native -input into `pardes.Event`, presents `pardes.Surface`, and performs host -effects such as spawning processes. +One core, three frontends (tui, gui, macos). The core owns +editing, layout, rendering and the virtual filesystem it serves over 9P; a +frontend turns native input into `pardes.Event`, presents `pardes.Surface`, +and its host performs effects such as spawning processes. - The core is a state machine: input arrives as an `Event` through `update`; output leaves as a `Surface` from `render(arena)` and as a ring @@ -271,13 +339,21 @@ effects such as spawning processes. - `pump` runs: wait for input (the host owns the sleep), flush paused 9P write batches, drain queued events, drain effects, settle the turn, then render and present only when a frame is needed and someone is looking. -- `host_io.Host` is a context pointer and a vtable of optional callbacks; a - null method is not an error, and `Host{}` is a complete in-process pardes - that the tests use. Comptime decides what a build has (`pardes.platform`, - `can_attach`); the vtable - decides who serves it. -- The root module is chosen by platform: `main.zig` (tui, gui), - `macos.zig`. The macOS shell is a library whose host owns `main()`. +- `Host` (`dev/Host.zig`) is a context pointer and a table of optional + callbacks; a null method is not an error, and `Host{}` is a complete + in-process pardes that the tests use. Comptime decides what a build has + (`pardes.platform`, `can_attach`); the table decides who serves it. +- The terminal and the window draw from the frame alone: the `Surface` + (cells, regions, layers, placements, cursor, `Chrome`) and one record + beside it, `Facts` (`core/surface.zig`: the view's size, each open + pane's rectangle, tag rows and kind, the settings a frontend draws by), + which `draw.place` fills with the frame. Each reads these, not the core, + to draw and to turn its input into events, so a client draws its own + view with no view of the core made live. A few reads of the core remain, in the window: its + hit test, its close and a session window's font. +- The macOS build is a library whose Swift app owns `main()` and the run + loop (`runtime/macos.zig`); it reads the core beyond the frame (its + theme, a pane's document state) and runs neither loop below. - The terminal is a module of its own, `term` (`core/term/`): the emulator (ghostty-vt), kitty images (wuffs, zstbi), the pager's parse and the replicas' screen state. It never imports the core; the core @@ -292,14 +368,115 @@ effects such as spawning processes. safe, its checks in Debug builds only. Code map: `core/panes.zig` and the pane kinds it names (`core/File.zig`, -`src/Terminal.zig`, ...), `core/layout.zig`, `core/fs.zig` (host access, -mounts and resolution) and `core/root.zig` (input), with one file per -thing beside them (`edit.zig`, `normal.zig`, `look.zig`, `exec.zig`, -`mouse.zig`, ...). `core/ninep/` is the control tree, `runtime/daemon.zig` the -per-user daemon and a terminal's stub, `abi/wire.zig` the input -wire a remote client will speak, `core/lsp/` the -language-server client; `test/` holds harnesses, goldens and helix cases, -`build/` the process tests' build steps. +`core/Term.zig`, `core/Kind.zig`, ...), `core/layout.zig`, `core/fs.zig` +(host access, mounts and resolution), `core/Core.zig` (the core's state +and its entries) and `core/draw.zig` (the frame), with one file per thing +beside them (`edit.zig`, `normal.zig`, `look.zig`, `exec.zig`, +`mouse.zig`, ...). `core/ninep/` is the control tree, `core/tape.zig` the +tape, `core/replica.zig` the replica engine (a client's `Replica` and +`Link`, a session's `Peers`), `runtime/daemon.zig` the per-user daemon and +a terminal's stub, `abi/wire.zig` the replica stream's frames, `core/lsp/` +the language-server client; `test/` holds harnesses, goldens and helix +cases, `build/` the build script's parts. + +== The loops <loops> + +A session runs `runtime/session.zig`'s `Loop`, a client +`runtime/client.zig`'s, each over the frontend it is given (comptime: no +vtable). The terminal's and the window's own frontend (`Own` in each) and +their client frontends (`Tty`, the window's `Client`) give the calls; +what a loop holds and its order are written once. + +- The session's loop holds its allocators and workers, its core (new, + from a dump, or an Upgrade's), the prompt files its shells start with, + the 9P listener and its clients (`Peers`). A turn is a `pump`, the step's + unit to the clients (`Peers.boundary`), the frontend's `sent`, an + Upgrade or a Restore between steps, and the daemon's notes. Its parts end + in one order: the listener, the clients, the frontend's devices, the + prompt files, the core, the workers, the allocators. The devices (ptys, + their readers, watched files, the jobs, the queue they post to) are + still each frontend's (`open`, `start`, `close`). +- A client's loop holds what it keeps across joins (`client.Start`: its + allocators, the addons it distrusts, its frame timings, the blobs it + keeps when far) and runs its joins: the reader thread, a pass at a time, + and a join again after a divergence or an Upgrade. A pass: the + frontend's own work (`own`), the predicted echo's frame, a draw or the + frontend's own motion (`again`), the wait (`deadline`, `wait`), then the + session's units settled, and a yank, paste or link its view asked for + done on this machine (`copy`, `paste`, `open`). An input is sent to the + session before it is applied here. +- The soak, `zig build replicas` (`test/replicas.zig`), runs both: its + session is `session.Loop` over a frontend whose host is the soak's + delayed network, every client a `client.Loop`, so what it tests is what + a session and a client run. The core's own unit tests stand a session in + with `replica.Authority`. + +== The tape <tape> + +The tape (`core/tape.zig`) records what a step takes in: the entry a host +called and its arguments, and every answer of the machine inside the step. +A session records its steps; a client replays the session's and records +its own speculations, to compare. + +- An entry is written once: a private body and, directly under it, its + public name made by `tape.taped` + (`pub const update = pardes.tape.taped(updateInner);`); the tape's + `Input` variant and the replay come from the body's parameters. The few + written by hand (`init`, `deinit`, `pump`, `render`, ...) each say why. +- The tape is the handle a step is given, as an allocator is: a core + holds it (`p.tape`, never null), and a function handed no core takes + `tape: *Tape`. A step's question of the machine goes through it + (`p.tape.value`, `p.tape.site`, `p.tape.authorityOnly`): the session + records the answer, a replay reads it. So far the kinds and addons, a + directory's listing, the file system, the core's own files and the + smaller ones ask it so; beside the field, the process's `tape.on` still + says which core is being stepped. +- A pane's and a view's slot are types where they cross the core's edge + (an entry's argument or answer, an event, an effect, a host call, the + wire's welcome): `Pane.Id` and `View.Id`, each an `enum(u8)` of its own. + The core's own loops keep their integers. +- The session's facts, its home, default shell and directory, are the + core's state (`session_home`, `session_shell`, `session_dir`), read once + at its start through the tape and carried in its dump: a far client's + `~`, #word("Shell") and a word run in the session's directory are the + session's. + +== What may wait <may-wait> + +A client applies its own input at once; a step that needs the session's +machine stops its speculation, and the input waits a round trip for the +session's unit (`tape.hostCall`). The user's line: motions, edits and +layout are instant; what has a side effect on the system may wait. Two +lists say which, each row with why: + +- `keeps_stopping` (`core/tape.zig`): the Host entries that return nothing + and still stop a speculation (`pty_write`, `spawn`, `write_file`, ...). + A client records any other such call as made and goes on; an entry that + answers stops by nature, the answer being the session's. +- `may_wait` (`core/replica.zig`): each word, key or gesture that may wait, + on a kind of pane, and where it stops. A test walks every word of the + registry, every key (and every key after each prefix) and the gestures + between panes, on a file's, a kind's and a shell's pane: a stop not + listed fails it, and a row nothing stopped at is stale. The soak judges + its stops by name against the same list. + +== The checks <core-checks> + +At the end of `core/root.zig`, run by `core-test`, `shell-test` and +`unit-test`: + +- *No process globals:* every container-level `var` in `core/` is on + `allowed_vars`, with why it is not a core's. +- *What the core asks of the machine:* every line of `core/` naming libc, + `std.posix`, `getenv`, a `std.Io` file, directory or socket, `dev` or + `runtime` is counted, a file at a time, against `machine_lines`, with why. +- *What is kept out of the digest:* every field kept out of the digest and + the dump (`.local`, `.derived`) is on `kept_out`, with who writes it and + why a step's read of it is the step's. + +Beside them, `core/draw.zig`'s test "a frame changes nothing a step reads" +steps a core that draws after every input and one that never draws, and +their digests agree after every step. == Threads @@ -311,7 +488,7 @@ would change a pane parks (`Status.again`) and is retried when the editor rests. 9P requests are not events: they enter through `Pardes.serveFs`, and only one that changes a pane costs a frame. Language-server and selection-pipe workers post completions through a bounded mailbox; a -`host_io.Lsp.Job` owns copies of the source, path and arguments, never +`Lsp.Job` (`dev/Lsp.zig`) owns copies of the source, path and arguments, never reading the live core, and a request id, the pane's serial and (for an edit) the file's revision reject a stale reply. A process that never calls `turn.start` (the tests) has no second thread. diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 8ed70b10..732e66a7 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -101,8 +101,8 @@ {"name": "Togglettymode", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Switch this terminal between raw program input and normal editor mode."}, {"name": "TreeContext", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show the declarations enclosing the top row at the pane's head, on or off."}, {"name": "Tutor", "leader": "SPC h t", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the tutor, a document to work through."}, - {"name": "Unattach", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Unattach a pane from the pane it answers for: it stays where it is, a pane of its own, and the next search from that pane opens another under it."}, {"name": "Undo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Undo and Redo: step the pane's body back or forward through its edits, from a tag, a pane ctl or exec."}, + {"name": "Undock", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Undock a pane from the pane it answers for: it stays where it is, a pane of its own, and the next search from that pane opens another under it."}, {"name": "Unfollow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Take this pane out of its Follow chain: it stays, a Zerox twin with the scroll it has, and the chain closes up behind it."}, {"name": "Unmount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Unmount the 9P tree mounted under /n/<name>."}, {"name": "Up", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane above, and from a column's top pane to its tag."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index aa95d9a6..0a074c44 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -95,8 +95,8 @@ {"name": "Togglettymode", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Switch this terminal between raw program input and normal editor mode."}, {"name": "TreeContext", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show the declarations enclosing the top row at the pane's head, on or off."}, {"name": "Tutor", "leader": "SPC h t", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the tutor, a document to work through."}, - {"name": "Unattach", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Unattach a pane from the pane it answers for: it stays where it is, a pane of its own, and the next search from that pane opens another under it."}, {"name": "Undo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Undo and Redo: step the pane's body back or forward through its edits, from a tag, a pane ctl or exec."}, + {"name": "Undock", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Undock a pane from the pane it answers for: it stays where it is, a pane of its own, and the next search from that pane opens another under it."}, {"name": "Unfollow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Take this pane out of its Follow chain: it stays, a Zerox twin with the scroll it has, and the chain closes up behind it."}, {"name": "Unmount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Unmount the 9P tree mounted under /n/<name>."}, {"name": "Up", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane above, and from a column's top pane to its tag."}, diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 2562c91b..4c193e0f 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -1179,8 +1179,12 @@ of it is laid out by `view` and drawn by `paint`. handed (the last allocation the answer); one asked before an #word("Addon") `reload` answers into nothing, and the old library stays until its last such job has answered. -- A client of the session runs no addon's code: a pane of a kind it lacks - shows the session's frames of it, and its keys go to the session. +- A client of the session runs a kind whose state is plain (`PA_PLAIN`: + the games, the picture, the PDF) from its own addons, as the session + does, and draws its pictures itself. A pane of a plain kind it lacks, or + one that broke its promise there, shows a line saying so; a kind whose + state is not plain runs in the session alone, and its pane in a client + shows a line saying that. The session sends no pictures to a client. - #word("Addon") `load <path>` (relative to the pane's directory) loads one; `unload <name>` lets one go, refused while a pane of its kind is @@ -1230,8 +1234,10 @@ of it is laid out by `view` and drawn by `paint`. pane whose file changes on disk opens again from it, its record kept for its `load` (a PDF stays on its page). - An addon runs in pardes's process. A load is marked on disk while it - runs; a start that finds the mark of one that never finished skips that - library, listed so, until #word("Addon") `load` asks for it again. A + runs, with the loading process's pid; a start that finds the mark of a + load whose process is gone (it never finished) skips that library, + listed so, until #word("Addon") `load` asks for it again. Another + pardes's load still under way is no crash. A crash inside one says `in addon <file>, <call>` in the crash record. - `pardes --addon-test <lib> <script>` runs a script of keys, clicks, words and ticks (its clock starts at 1 s), `focus` and `blur`, `size C diff --git a/docs/typ/running.typ b/docs/typ/running.typ index 7e0d16d4..1500845e 100644 --- a/docs/typ/running.typ +++ b/docs/typ/running.typ @@ -9,10 +9,11 @@ A running pardes is up to four kinds of process. Which of them there are, and what each holds, depends only on how it was started. -// daemon.zig:8-16 (nobody's parent; dups; hands terminals, windows, -// replicas); replica.zig:1-19, :730-769 (a client's core from the dump); -// host_io.zig:2176-2179 (the shells are the session's children); -// 9p_io.zig:57 (the socket); daemon.zig:546-698 (the stub). +// runtime/daemon.zig:8-16 (nobody's parent; dups; hands terminals, +// windows, replicas); core/replica.zig:1-19, :747-794 (a client's core +// from the dump); dev/host_io.zig:548-551 (the shells are the session's +// children); runtime/9p_io.zig:57 (the socket); runtime/daemon.zig:546-698 +// (the stub). #pairs( [*session*], [the process with the truth: the one core every other copy follows, the shells' pty masters (the shells are its children) and the 9P socket. There is one a session, always.], [*client*], [any further terminal or window on a session: a process of its own, with a copy of the session's core (a replica) loaded from the session's dump and kept in step with the session's tape. It has its own view (columns, focus, cursors, scroll) and draws it. It holds no shells and no 9P socket. A client on another machine is *far*.], @@ -20,9 +21,9 @@ and what each holds, depends only on how it was started. [*stub*], [the process your shell waits on when the session is not it. It holds nothing: it passes signals on, and ends when the session leaves its terminal.], ) -// tui.zig:588 (a session's terminal: one or none); gui.zig:2381-2384 (the -// window, or none while detached); daemon.zig:901-905 ("a session shows one -// frontend of its own"). +// dev/tui/tui.zig:590 (a session's terminal: one or none); +// dev/gui/gui.zig:2433-2436 (the window, or none while detached); +// runtime/daemon.zig:901-905 ("a session shows one frontend of its own"). A *frontend* is what draws: the terminal (`pardes`), the window (`pardes-gui`), or the Mac's own build. A session draws at most one frontend of its own: the one it was started with, or one attached to it @@ -40,10 +41,11 @@ travels on it. #run-terminal() -// main.zig:1538-1563, daemon.zig:663-698 (the fork, setsid, the stub); -// daemon.zig:550-559, :567-616 (what the stub forwards and how it ends); -// tui.zig:1697-1721 (the terminal's end: detached while kept, else the -// end); daemon.zig:305-314 (kept: the daemon answered and is still there). +// runtime/main.zig:1570-1595, runtime/daemon.zig:663-698 (the fork, +// setsid, the stub); runtime/daemon.zig:550-559, :567-616 (what the stub +// forwards and how it ends); dev/tui/tui.zig:1685-1709 (the terminal's +// end: detached while kept, else the end); runtime/daemon.zig:305-314 +// (kept: the daemon answered and is still there). `pardes` forks the session off and stays as its stub. The session runs in a POSIX session of its own, so it can outlive the job your shell waits on. It reads the keys from the terminal and draws on it itself; the stub only @@ -58,9 +60,9 @@ daemon, or after the daemon has died, it ends the session and its shells. #run-window() -// main.zig:1536-1537 (registered, no fork); gui.zig:1775-1788 (the -// window's close); next-daemon.md "Phase 3 notes", known gaps (a terminal's -// job). +// runtime/main.zig:1568-1569 (registered, no fork); +// dev/gui/gui.zig:1830-1843 (the window's close); next-daemon.md "Phase 3 +// notes", known gaps (a terminal's job). The process you started is the session; there is no stub. Closing the window ends the session and its shells, unless the session has clients and a daemon: then only the window closes, and the session runs on, detached. @@ -71,17 +73,18 @@ terminal hangs up. #run-detach() -// main.zig:1502-1520 (no fork; 160x50); main.zig:1535-1537 (registered -// detached, or with no daemon not at all); tui.zig:596-603 and :1700 -// (a hangup taken, nothing to leave); 9p_io.zig:704-729 (the hangup's -// default handler in a window's process). +// runtime/main.zig:1517-1552 (no fork; 160x50); runtime/main.zig:1567-1569 +// (registered detached, or with no daemon not at all); +// dev/tui/tui.zig:598-605 and :1688 (a hangup taken, nothing to leave); +// runtime/9p_io.zig:704-729 (the hangup's default handler in a window's +// process). The process you started is the session: nothing is forked, so the `&` that puts it in the background is yours to type (`pardes new --detach=work` is the same). It draws nothing and is 160×50 until an attach or the root #file("ctl")'s `size` sizes it. Until something attaches, 9P is the only way in (#doc("scripting")). -// main.zig, the --detach branch (the exec of the pardes beside it). +// runtime/main.zig, the --detach branch (the exec of the pardes beside it). `pardes-gui --detach` runs the `pardes` installed beside it in its place: a detached session draws nothing, and a window's binary would start a GPU device and its fonts for it. So every detached session is a terminal's @@ -96,9 +99,10 @@ reaches it. #run-attach-detached() -// main.zig:1780-1810 (attachTo); daemon.zig:883-897 (handed on); -// tui.zig:1373-1401 (the terminal entered as the first was); -// gui.zig:3271-3289, :2534-2547 (the window opened again). +// runtime/main.zig:1812-1842 (attachTo); runtime/daemon.zig:883-897 +// (handed on); dev/tui/tui.zig:1354-1382 (the terminal entered as the +// first was); dev/gui/gui.zig:3384-3402, :2588-2601 (the window opened +// again). For a terminal's session, `pardes attach work` hands its terminal and a pipe to the session through the daemon, and stays as the stub. For a window's, `pardes-gui attach work` asks, then exits, and the session opens @@ -106,7 +110,7 @@ its own window again. Either way the frontend is the session's own again, in the process that has been the session all along: what happens when it closes is what the first two sections say. -// daemon.zig:901-972 (find: the bare attach, and `other`). +// runtime/daemon.zig:901-972 (find: the bare attach, and `other`). The kind has to match. A terminal's session attached from `pardes-gui`, or a window's from `pardes`, is joined as a client (the next section). Bare, `pardes attach` takes the one detached session of its kind; with @@ -118,14 +122,15 @@ spelling of `attach work`. #run-attach-client() -// main.zig:1812-1818 (crossAttach); daemon.zig:974-1008 (the hello, the -// same build, handed on); replica.zig:1-19 (speculation and rollback); -// replica.zig:2013-2023, views.zig:31, Core.zig:1110-1153 (four views, the -// session's own among them); replica.zig:2111-2133 (a client leaving); -// replica.zig initDump, Addon.zig plainOps (a plain kind's code runs in -// the client that has it; another's in the session alone); gui.zig:2147-2161 -// (a client's notch: whole rows sent), :3544 (glideFrame: the picture on -// the client's clock); gui.zig:580-608 (a client's font: the session's +// runtime/main.zig:1844-1850 (crossAttach); runtime/daemon.zig:974-1008 +// (the hello, the same build, handed on); core/replica.zig:1-19 +// (speculation and rollback); core/replica.zig:2204-2214, core/views.zig:31, +// core/Core.zig:1163-1203 (four views, the session's own among them); +// core/replica.zig:2303-2325 (a client leaving); core/replica.zig initDump, +// core/Addon.zig plainOps (a plain kind's code runs in the client that has +// it; another's in the session alone); dev/gui/gui.zig:2200-2214 (a +// client's notch: whole rows sent), :3673 (glideFrame: the picture on the +// client's clock); dev/gui/gui.zig:595-623 (a client's font: the session's // request, by the face's name on this machine). Measured 2026-11-17 // (.scratch/sketch/reports/pardes-measure.md sections A, C and E): a // client's notch glides as the session's window does (5 frames, 0 to @@ -140,12 +145,28 @@ loads the session's dump into its own core, applies its own keys at once, and takes the session's tape (each step as the session took it) as the truth, rolling back when the session ordered things differently. +// core/replica.zig:5316-5395 (may_wait: what a client waits for, each +// row's why); core/tape.zig:1163-1193 (keeps_stopping); core/Core.zig:1763-1778 +// (readSessionFacts: the session's home, shell, directory); +// runtime/client.zig:245-261 (asks: a client's yank, paste and link, here). +What a client applies at once is what changes the editor alone: typing, +motions, edits, the layout (a pane dragged, collapsed or closed, a column +made), a yank. What touches the session's machine waits a round trip for +the session's step: a save, a shell's keys or its closing, a file read +from its disk, a program run, a kind whose state is the session's +(#doc("building", section: "may-wait") lists each, with why). The +session's machine is the one a client's words read: `~`, the default +shell and the directory a word runs in are the session's. The client's +machine is the one its view acts on: a yank to the system clipboard fills +the clipboard here, #word("ClipPaste") pastes it, and a link looked at +opens here. + A session takes three clients: four views at once, its own among them. A client's #word("Detach"), or its terminal or window closing, ends that client only; the last client of a detached session leaves its layout as the session's, for the next one to find. In a client, an addon whose state -is plain (`PA_PLAIN`: the games) runs in the client that shows it, from -that client's own addons, its keys applied at once; one the client lacks +is plain (`PA_PLAIN`: the games, the picture, the PDF) runs in the client +that shows it, from that client's own addons; one the client lacks shows a line saying so, and any other addon's panes show a line saying it runs in the session alone. A window client's wheel glides as the session's own window does: whole rows @@ -160,11 +181,11 @@ part. #run-far() -// main.zig:1498-1500, :1687-1772 (HOST:NAME, ssh -L, PARDES_SSH, -// PARDES_REMOTE_RUNTIME, a path with '/'); tui.zig:678-685 (far: blobs by -// hash, zstd); replica.zig:2516-2640 (Have: the disk cache); -// tui.zig:819-828, replica.zig:3012-3024 (no reconnect; a rejoin only -// after a divergence or an Upgrade). +// runtime/main.zig:1513-1515, :1719-1804 (HOST:NAME, ssh -L, PARDES_SSH, +// PARDES_REMOTE_RUNTIME, a path with '/'); runtime/client.zig:74-87 (far: +// blobs by hash, zstd); core/replica.zig:2709-2845 (Have: the disk cache); +// runtime/client.zig:168-177, core/replica.zig:3262-3274 (no reconnect; a +// rejoin only after a divergence or an Upgrade). `pardes attach box:work` runs `ssh -L` from a socket here to box's replica socket and is a client through it. `PARDES_SSH` replaces `ssh`; `PARDES_REMOTE_RUNTIME` names box's runtime directory when it is not the @@ -181,12 +202,12 @@ of the session or a divergence of its own. `pardes attach /run/x.sock:work` #run-no-daemon() -// daemon.zig:52-61 (PARDES_DAEMON, PARDES_TEST), :34 (Linux and FreeBSD -// only); main.zig:1544-1560 (no daemon reached: no fork); tui.zig:1352-1353, -// gui.zig:2483, host_io.zig:227 (Detach and Adopt refused); -// replica.zig:1900-1905 (a client only through the daemon); -// core/root.zig:117 (can_attach); runtime/main.zig:1498-1500 (a far attach needs no -// daemon here). +// runtime/daemon.zig:52-61 (PARDES_DAEMON, PARDES_TEST), :34 (Linux and +// FreeBSD only); runtime/main.zig:1576-1592 (no daemon reached: no fork); +// dev/tui/tui.zig:1333-1334, dev/gui/gui.zig:2537, dev/host_io.zig:85 +// (Detach and Adopt refused); core/replica.zig:2087-2092 (a client only +// through the daemon); core/root.zig:118 (can_attach); +// runtime/main.zig:1513-1515 (a far attach needs no daemon here). With `PARDES_DAEMON=off`, in a window under test (`PARDES_TEST`), where none could start, and in the Mac's own build, the session is the process you started, with no stub. #word("Detach") and #word("Adopt") refuse, no @@ -198,9 +219,10 @@ client. = At a glance <run-glance> -// The rows' sources are the sections above; `ps`: daemon.zig:241-245 -// (the daemon is whichever binary started it), main.zig:1727 (ssh's -// arguments), upgrade.zig:5-8 (an upgraded session's command line). +// The rows' sources are the sections above; `ps`: +// runtime/daemon.zig:241-245 (the daemon is whichever binary started it), +// runtime/main.zig:1759 (ssh's arguments), runtime/upgrade.zig:5-8 (an +// upgraded session's command line). #{ set text(size: 0.85em) set par(justify: false) @@ -225,13 +247,14 @@ started it. After an #word("Upgrade"), a session's command line starts with = What survives what <run-survives> -// replica.zig:2111-2133 (a client leaving); daemon.zig:485-502, -// 9p_io.zig:704-729, tui.zig:949-961 (TERM, HUP, INT: the shells go); -// daemon.zig:755-765, :770-789 (killed outright: kept for Adopt; `kill`: -// not); tui.zig:596-598 (a HUP kept by a daemon is a terminal's end, not -// the session's); daemon.zig:397, main.zig:1534-1561 (registered at the start and at -// an Upgrade only); upgrade.zig:1-15, replica.zig:2178-2201, :2787-2807 -// (Upgrade); Db.zig:1-17, :385-410 (the state file: Recent, the dumps). +// core/replica.zig:2303-2325 (a client leaving); runtime/daemon.zig:485-502, +// runtime/9p_io.zig:704-729, dev/tui/tui.zig:928-940 (TERM, HUP, INT: the +// shells go); runtime/daemon.zig:755-765, :770-789 (killed outright: kept +// for Adopt; `kill`: not); dev/tui/tui.zig:598-600 (a HUP kept by a daemon +// is a terminal's end, not the session's); runtime/daemon.zig:397, +// runtime/main.zig:1566-1593 (registered at the start and at an Upgrade +// only); runtime/upgrade.zig:1-15, core/replica.zig:2370-2393, :2988-3008 +// (Upgrade); core/Db.zig:1-17, :385-410 (the state file: Recent, the dumps). #{ set text(size: 0.85em) set par(justify: false) @@ -269,15 +292,18 @@ The code says these words too, each for one thing of its own (the older notes, `docs/next-daemon.md` among them, still say `remote` for a client and `headless` for detached): -// replica.zig:1-19 (authority); replica.zig:1832-1876, :2812 (Peers, Link, -// Joining); tui.zig:1189, gui.zig:2379 (Shell); Core.zig:269-271, -// replica.zig:1850-1852 (unattended against detached); daemon.zig:283, -// :363, :799 (the daemon's attached and detached), main.zig:1616 (`ps` -// says "has a frontend"). +// core/replica.zig:1-19 (authority); core/replica.zig:2006-2062, :3013 +// (Peers, Link, Joining); dev/tui/tui.zig:1162, dev/gui/gui.zig:2431 +// (Shell); core/Core.zig:313-315, core/replica.zig:2028-2030 (unattended +// against detached); runtime/daemon.zig:283, :363, :799 (the daemon's +// attached and detached), runtime/main.zig:1647 (`ps` says "has a +// frontend"); runtime/session.zig:1-30, runtime/client.zig:1-35 (the +// loops and what a frontend gives each). #pairs( [`authority`], [the session's core, inside the replica engine; `replica`, a client's core], [`Peers`, `Peer`; `Link`, `Joining`, `Joined`], [a session's clients, seen from the session; a client's connection, seen from the client], - [`Shell`], [a frontend's host object (`tui.zig`, `gui.zig`); elsewhere the user's shell], + [`Shell`], [a frontend's host object (`dev/tui/tui.zig`, `dev/gui/gui.zig`); elsewhere the user's shell], + [`session.Loop`, `client.Loop`], [the one loop a terminal's or a window's session runs and the one a client runs (`runtime/session.zig`, `runtime/client.zig`), each over the frontend that draws it: `Own` for a session's own terminal or window, `Tty` and `Client` for a client's; the Mac's own build keeps its own], [`unattended`], [a detached session with no client either: nobody looks, so a message goes on the clock], [`attached` in #file("/sessions")], [the daemon's word for a session with a frontend of its own; `pardes ps` says "has a frontend"], ) diff --git a/docs/zstbi-fp-contract.md b/docs/zstbi-fp-contract.md new file mode 100644 index 00000000..95c067fd --- /dev/null +++ b/docs/zstbi-fp-contract.md @@ -0,0 +1,66 @@ +# stb_image_resize: a downscale's pixels depend on the CPU's fused multiply-add + +A report for upstream (https://github.com/zig-gamedev/zstbi, which vendors +nothings/stb's `stb_image_resize.h` v0.97), against the commit pardes pins +(6b9bea1f, `build.zig.zon`). pardes patches its fetched copy at build time +(build/patches.zig, `zstbi_cut`) until it is fixed there, if upstream wants +it fixed. + +## What happens + +pardes downscales a kitty graphics PNG over 1280 pixels with zstbi's +`stbir_resize_uint8` (core/term/TerminalImages.zig, `decodePng`). The +resize is plain C on floats, with no SIMD of its own, and clang compiles C +with `-ffp-contract=on`: where the target has a fused multiply-add, +`a * b + c` becomes one instruction that rounds once instead of twice. +aarch64 always has one; the x86-64 targets pardes builds for here do not +use one. The aarch64 macOS binary has 66 `fmadd`/`fmla` in +`stbir__resize_arbitrary` and 32 in `stbir__resample_horizontal_downsample`; +the x86-64 Linux and FreeBSD binaries have no `vfmadd` anywhere. So the same +PNG downscales to pixels a step apart on an Apple silicon Mac. + +pardes meets it because a client of a session runs its own emulator on the +pty's bytes: a Mac client of a Linux session must end with the session's +terminal, and a join compares the snapshot (which holds each image's +pixels) of the two. + +## Measured + +Three PNGs sent by direct data (`f=100`): 1601x1203 (downscaled to +1280x961), 700x2001 (to 447x1280) and 333x257 (not downscaled). On Linux +x86-64 (SIMD on and off) and FreeBSD 15.1 amd64 the three images' pixels +were the same; on the Mac (Darwin 25.6, arm64) the two downscaled ones +differed and the third was the same, as were two 1024x768 images sent as +raw RGBA (`f=32`). pardes's per-unit digest does not cover images, so only +the snapshot differed. + +## The fix + +Contraction off for the whole translation unit, at the top of zstbi's C file: + +```diff +--- a/src/zstbi.c ++++ b/src/zstbi.c +@@ -1,3 +1,4 @@ + #include <stdlib.h> ++#pragma STDC FP_CONTRACT OFF +``` + +(`-ffp-contract=off` in zstbi's build flags is the same.) With it the Mac +binary has no fused multiply-add in `stbir_*`, and the Mac's pixels are +Linux's: the three images, and the snapshot (with the page fix of +docs/ghostty-page-size.md, every stream's). + +## What it costs + +A multiply and an add where there was one instruction, in a resize made +once per image sent (a 1601x1203 picture's), on aarch64 only: not +measured, as nothing else of pardes runs it. + +## Upstream today + +Not read beyond what is on this machine (no network): no copy of zstbi or +stb is in `~/05-genizah`. The three zstbi copies in `zig-pkg/` (the pin and +two others) all vendor `stb_image_resize.h` v0.97 with no pragma. stb's own +successor, `stb_image_resize2.h`, has SIMD paths of its own; moving to it +would be another question of the same kind, not a fix of this one. diff --git a/runtime/macos.zig b/runtime/macos.zig index 408915da..dc12a6fb 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -103,7 +103,7 @@ pub const Image = extern struct { paper_bg: u32, }; -pub const Runtime = extern struct { +pub const Callbacks = extern struct { userdata: ?*anyopaque = null, wakeup: ?*const fn (?*anyopaque) callconv(.c) void = null, set_clipboard: ?*const fn (?*anyopaque, [*]const u8, usize) callconv(.c) void = null, @@ -250,7 +250,7 @@ const State = struct { io: std.Io, core: *pardes.Pardes, started: bool = false, - runtime: Runtime, + runtime: Callbacks, tag_cells: [pardes.MAX_TAG_LAYERS][]Cell = @splat(&.{}), layer_cells: [pardes.MAX_PANES][]Cell = @splat(&.{}), cells: []Cell = &.{}, @@ -290,7 +290,7 @@ const State = struct { var state: ?State = null; -export fn pardes_init(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) c_int { +export fn pardes_init(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) c_int { if (state != null) return 1; // already up; deinit first initCore(runtime, cols_arg, rows_arg) catch |err| { log.err("init failed: {t}", .{err}); @@ -302,7 +302,7 @@ export fn pardes_init(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) c_ /// The shell's gpa in a Debug build, as std.start's is for the others. var debug_gpa: std.heap.DebugAllocator(.{}) = .init; -fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { +fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void { // The allocator every other shell gets from std.start: a DebugAllocator // in Debug, libc's malloc otherwise. libc's measured at least as fast as // std.heap.smp_allocator everywhere and faster on MuPDF's page-sized @@ -359,7 +359,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { core.settings.workspace_tag = if (std.c.getenv("PARDES_WORKSPACE_TAG")) |v| std.mem.eql(u8, std.mem.span(v), "1") else - @import("pardes_config").workspace_tag; + @import("pardes_options").workspace_tag; core.view().frontend.native_images = true; var prompt_rcs = host_io.Shell.prepare(); @@ -2461,7 +2461,7 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@sizeOf(c.pardes_image_s), @sizeOf(Image)); inline for (@typeInfo(Image).@"struct".field_names) |name| try expectEqual(@offsetOf(c.pardes_image_s, name), @offsetOf(Image, name)); - try expectEqual(@sizeOf(c.pardes_runtime_s), @sizeOf(Runtime)); + try expectEqual(@sizeOf(c.pardes_callbacks_s), @sizeOf(Callbacks)); try expectEqual(@as(u32, c.PARDES_COLOR_DEFAULT), color_default); try expectEqual(@as(u32, c.PARDES_COLOR_INDEXED), color_indexed); diff --git a/runtime/main.zig b/runtime/main.zig index 2b600d63..448dfa57 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -753,7 +753,7 @@ const Word = struct { /// Its group: the first key after the leader, else what it is. fn group(w: Word) []const u8 { if (std.mem.indexOf(u8, w.doc, " (addon ") != null and std.mem.endsWith(u8, w.doc, ")")) return "addon"; - if (pardes.config.Runtime.find(w.name) != null) return "setting"; + if (pardes.config.Settings.find(w.name) != null) return "setting"; if (std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name)) |b| if (pardes.config.leader_path.get(b)) |p| switch (p[0]) { 'f' => return "file", 'c' => return "column", diff --git a/runtime/root.zig b/runtime/root.zig index ec89e734..930f3389 100644 --- a/runtime/root.zig +++ b/runtime/root.zig @@ -22,9 +22,9 @@ test { _ = ninep; // main.zig's test block collected the crash file's: a shell's build // (shell-test); the core without a terminal (core-test) never compiled it. - if (comptime @import("term_options").terminal) _ = crash; + if (comptime @import("pardes_options").terminal) _ = crash; // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. - if (comptime @import("term_options").terminal and @import("pardes_config").platform == .gui) _ = @import("dev").gui; + if (comptime @import("pardes_options").terminal and @import("pardes_options").platform == .gui) _ = @import("dev").gui; } diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig index 77928dd0..2a8d6edf 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -80,9 +80,9 @@ pub fn noticeNewer(core: *pardes.Pardes) void { if (newer()) core.setMessage(.at(core.view().active), pardes.newer_build_words); } -/// Whether to say a newer build is installed now (`noticeNewer`): the -/// tty's Host answers the core's focus step with it, so its replica -/// clients take the line from the tape. +/// Whether to say a newer build is installed now (`noticeNewer`): asked +/// by a session's own frontend at its focus-in, between steps; the line is +/// an input (setMessage) its replica clients take from the tape. pub fn newer() bool { const was = started_inode orelse return false; const now = inodeOf(exe() orelse return false) orelse return false; diff --git a/test/behaviour/panes.zig b/test/behaviour/panes.zig index 67155776..dcde9c4d 100644 --- a/test/behaviour/panes.zig +++ b/test/behaviour/panes.zig @@ -888,7 +888,7 @@ test "panes: truncating body empties it, and a stat says the length after" { } test "panes: a rename colours a source its new name's language names, its text unchanged" { - if (!@import("pardes_config").syntax_highlighting) return error.SkipZigTest; + if (@import("pardes_options").grammars == .disabled) return error.SkipZigTest; var s = try Session.initFile(std.testing.allocator, "fn check() void {}\n"); defer s.deinit(); const n = try s.focused(); diff --git a/test/behaviour/settings.zig b/test/behaviour/settings.zig index 66cd97df..cacee701 100644 --- a/test/behaviour/settings.zig +++ b/test/behaviour/settings.zig @@ -37,7 +37,7 @@ test "settings: Pet is the window's: a terminal's view refuses it; a window take defer s.deinit(); // Which build, from its options, not from the answer: a terminal's view // taking Pet must fail here, not pass as a window. - if (comptime @import("pardes_config").platform == .gui) { + if (comptime @import("pardes_options").platform == .gui) { try std.testing.expectEqualStrings("Pet off", try setting(&s, "Pet")); try s.write("/ctl", "Pet cat\n"); try std.testing.expectEqualStrings("Pet cat", try setting(&s, "Pet")); @@ -106,7 +106,7 @@ test "settings: a bad setting value is quoted, so two different bad values log a test "settings: a setting this frontend cannot show says GUI-only, never run as a command, and DumpDir reads back" { var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); - if (comptime @import("pardes_config").platform != .gui) { + if (comptime @import("pardes_options").platform != .gui) { _ = try s.refused("/ctl", "GripWidth 120\n"); try std.testing.expectEqualStrings("GripWidth is GUI-only, invalid here \"GripWidth\"", s.said); // A builtin the GUI alone has, written to a ctl or an exec, never @@ -158,7 +158,7 @@ test "settings: Back and Forward written to exec keep to the focused file" { }); } -const syntax = @import("pardes_config").syntax_highlighting; +const syntax = @import("pardes_options").grammars != .disabled; /// The style /screen draws the cell `into` cells into the first place /// `text` is drawn. @@ -314,7 +314,7 @@ test "settings: the user's startup file loads clean, every word of it known and const ctl = try s.read("/ctl"); for ([_][]const u8{ "Theme monokai_pro_classic\n", "CallstackDepth 64\n", "InactiveDim 5\n", "Shell fish\n", "JumpTrail on\n", "LocationsConfig context:4 tscontext:on tslocations:on layout:stacked\n" }) |line| try expectHas(ctl, line); // The window's words, which a terminal's view leaves to the window. - const window = @import("pardes_config").platform == .gui; + const window = @import("pardes_options").platform == .gui; for ([_][2][]const u8{ .{ "GripWidth", "110" }, .{ "CursorBlink", "off" }, .{ "WindowOpacity", "100" }, .{ "TaglineSize", "80" }, .{ "Pet", "frog" } }) |w| try expectHas(ctl, if (window) s.at("\n{s} {s}\n", .{ w[0], w[1] }) else s.at("\n# {s} unsupported\n", .{w[0]})); } diff --git a/test/macos_e2e.swift b/test/macos_e2e.swift index 74a03200..38d27808 100644 --- a/test/macos_e2e.swift +++ b/test/macos_e2e.swift @@ -51,7 +51,7 @@ private struct ScriptError: Error { } /// What the three C callbacks reach through `userdata`. A class, because a C -/// function pointer cannot capture: a pointer the runtime struct carries is the +/// function pointer cannot capture: a pointer the callbacks struct carries is the /// only way back into Swift state. private final class Host { /// Set by `wakeup`, which runs on a pty reader thread. Nothing else in the @@ -168,7 +168,7 @@ private final class Driver: PardesViewDelegate { message: "the view measured \(got.cols)x\(got.rows) cells, not the \(cols)x\(rows) the script asked for") } - var runtime = pardes_runtime_s( + var runtime = pardes_callbacks_s( userdata: Unmanaged.passUnretained(host).toOpaque(), wakeup: { ud in // A pty reader thread. One flag and out — see Host.woke. diff --git a/test/output.zig b/test/output.zig index 38e8ba0d..c5ddddd5 100644 --- a/test/output.zig +++ b/test/output.zig @@ -549,7 +549,7 @@ test "a window's setting builtins (TaglineSize, Font) reach the report DumpConfi defer font_arena.deinit(); var chosen_font: ?[]const u8 = null; var buf: [512]u8 = undefined; - for (config.Runtime.settings) |setting| { + for (config.Settings.settings) |setting| { // The view's own (a terminal's takes no window's words). if (!setting.enabled(builtins.viewCapabilities(p))) continue; const command: []const u8 = switch (setting.action) { @@ -786,7 +786,7 @@ test "identical result refresh keeps warm content caches without allocation" { const index = try panes.File.lineIndex(p.gpa, file); const styles = try std.testing.allocator.dupe(u8, file.highlights); defer std.testing.allocator.free(styles); - if (@import("pardes_config").syntax_zig_grammar) try std.testing.expect(styles.len > 0); + if (@import("pardes_options").grammars != .disabled) try std.testing.expect(styles.len > 0); const revision = file.revision; const saved_revision = file.saved_revision; const body_ptr = file.content.ptr; diff --git a/test/process/tty_boot.zig b/test/process/tty_boot.zig index a5f42074..741f6260 100644 --- a/test/process/tty_boot.zig +++ b/test/process/tty_boot.zig @@ -300,6 +300,9 @@ fn restore(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // when it comes up. Both headers used to run the word under the PRESS, on // the press, so a sweep of `echo SWEPT-COL` ran a bare `echo`. A right sweep // looks for what it swept the same way, and the other button cancels. +// What a sweep ran is waited for in its pane's tag, `(echo SW''EPT-COL) exit +// 0`, which stays: the echo's line shows in the pane's one body row only +// until `exit 0` follows it, and a loaded machine draws both in one frame. fn headersweep(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var t = try Tty.init(gpa, exe, "headersweep"); defer t.deinit(); @@ -321,7 +324,7 @@ fn headersweep(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.style("col-sweeping"); try t.drag("middle", "@echo+16", 2); try t.release("middle", "@echo+16", 2); - try t.wait(8000, "SWEPT-COL"); + try t.wait(8000, "EPT-COL) exit 0"); try t.stable(700, 15000); try t.snap("col-swept"); // the workspace tag, the same @@ -335,7 +338,7 @@ fn headersweep(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.press("middle", "@echo", 1); try t.drag("middle", "@echo+15", 1); try t.release("middle", "@echo+15", 1); - try t.wait(8000, "SWEPT-WS"); + try t.wait(8000, "EPT-WS) exit 0"); try t.stable(700, 15000); try t.snap("ws-swept"); // a right sweep over part of a word looks for the part: `hay.txt` opens, @@ -399,7 +402,7 @@ fn headersweep_restored(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.style("col-sweeping"); try t.drag("middle", "@echo+19", 2); try t.release("middle", "@echo+19", 2); - try t.wait(8000, "RESTORED-COL"); + try t.wait(8000, "-COL) exit 0"); try t.stable(700, 15000); try t.snap("col-swept"); try t.press("left", "118", 1); @@ -415,7 +418,7 @@ fn headersweep_restored(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.style("ws-sweeping"); try t.drag("middle", "@echo+18", 1); try t.release("middle", "@echo+18", 1); - try t.wait(8000, "RESTORED-WS"); + try t.wait(8000, "-WS) exit 0"); try t.stable(700, 15000); try t.snap("ws-swept"); try t.done(); @@ -869,6 +872,10 @@ fn winch(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.start(31, 100, &.{ "-n", "3" }); try t.stable(700, 20000); try t.key("c-b"); + // Its shell at its prompt after its `ls` (a row of the 50-column pane + // holding `$` alone): typed into earlier, a loaded machine's bash echoed + // the line before its readline was up, or ran it before the `ls`. + try t.wait(20000, "\n $" ++ @as([47]u8, @splat(' '))); try t.stable(600, 8000); try t.send("for i in $(seq 600); do kill -WINCH $PPID; done; echo SUR''VIVED"); try t.key("enter"); diff --git a/test/process/tty_editing.zig b/test/process/tty_editing.zig index b5f0495c..63c75512 100644 --- a/test/process/tty_editing.zig +++ b/test/process/tty_editing.zig @@ -783,6 +783,12 @@ fn grep(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try t.key("g"); try t.stable(400, 5000); try t.send("zzqq"); + // Its count once the search is over (`0`): `0+` is while it still + // counts (its pause on the clock, then the worker), which a quiet + // machine's frame shows and a loaded one's not. The query typed in + // first: the pane's empty query counts `0` too. + try t.wait(10000, "Grep zzqq"); + try t.wait(10000, "+Search 0 "); try t.stable(700, 10000); try t.snap("nomatch"); try t.key("esc"); diff --git a/test/process/window.zig b/test/process/window.zig index 687b9000..00450a9b 100644 --- a/test/process/window.zig +++ b/test/process/window.zig @@ -426,8 +426,11 @@ fn corpus(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try d.mouse("wheel", -3, cell_w * 40, cell_h * 12); try k.keep(&d, from, "11 a wheel's glide, every frame", true); from = try k.mark(&d); - try d.mouse("down", 1, cell_w * 20, cell_h * 10); - try d.mouse("up", 1, cell_w * 20, cell_h * 10); + // The press and its release in one write (Detached.mouse's events), + // so the window reads them in one pass: written apart, a loaded + // machine let it read the press alone and draw a frame between, one + // more kept frame than the base's (78) and every one after shifted. + try d.typeKeys(f.at("\x1b]777;mouse;down;1;{d};{d}\x07\x1b]777;mouse;up;1;{d};{d}\x07", .{ cell_w * 20, cell_h * 10, cell_w * 20, cell_h * 10 })); try k.keep(&d, from, "11 a click moves the caret, every frame", true); from = try k.mark(&d); try d.typeKeys("gg"); diff --git a/test/replicas.zig b/test/replicas.zig index 91a68861..ffe82790 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -53,6 +53,10 @@ const gpa = std.heap.c_allocator; pub const std_options: std.Options = .{ .log_level = .warn }; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; +/// `--bytes`: its clients are replicas of the bytes kind, each terminal fed +/// the pty's bytes its units carry into an emulator of its own, joined from +/// a dump with every emulator whole (core/replica.zig `Peers.bytes`). +var bytes_kind = false; /// The PDF the soak opens (`--pdf`), absolute. var pdf_path: ?[]const u8 = null; const frame_us = 16_667; @@ -791,6 +795,9 @@ const Soak = struct { /// encoding cost. framed: bool = false, encode_ns: u64 = 0, + /// The session's pty told the answer to the program's kitty query + /// (`questions`): once, whatever the clients. + kitty_answers: u32 = 0, /// A Peer's queue, swapped out as its writer swaps it (the Peers' /// allocator's). sending: std.ArrayListUnmanaged(u8) = .empty, @@ -809,6 +816,9 @@ const Soak = struct { fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { const pane = id.index(); const s = of(ctx); + // Only the session's emulator answers its program: a client's + // answers are its tape's, never written (`questions`). + if (std.mem.indexOf(u8, bytes, "\x1b_Gi=31;OK") != null) s.kitty_answers += 1; s.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } @@ -873,6 +883,7 @@ const Soak = struct { pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; l.peers.threads = false; + l.peers.bytes = bytes_kind; l.peers.flushed = .{ .ctx = s, .f = flushed }; const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; l.core.host = host; @@ -939,6 +950,9 @@ const Soak = struct { const at: u64 = switch (c) { 0, 1 => s.random.uintLessThan(u64, 100_000), 2 => 1_200_000, + // One joins in the middle of the flood, its emulators loaded + // whole and every other side's reloaded. + 3 => if (bytes_kind) flood_at + 100_000 else 2_300_000, else => 2_000_000 + c * 100_000, }; try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); @@ -1410,6 +1424,11 @@ const Soak = struct { } const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; + // Its terminals its own emulators, fed what the units carry. + if (bytes_kind) { + rp.t.screen_state = false; + rp.core().echo = null; + } rp.stats.samples = true; rp.t.local_files = true; rp.echo.now = m.at * 1000; @@ -1447,6 +1466,11 @@ const Soak = struct { totals.flood_us += s.flood_end -| flood_at; for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); + if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + if (bytes_kind and s.kitty_answers != 1) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: the program's kitty query was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, s.kitty_answers }); + } for (s.clients, 1..) |*cl, id| { totals.resizes += cl.resizes; totals.wakes += cl.wakes; @@ -1558,7 +1582,11 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // flood of `yes`, read 4 KB at a time as a pty gives it. const tui = try screen_state.tuiStream(gpa); defer gpa.free(tui); - const shell_session = try screen_state.shellStream(gpa); + const session_only = try screen_state.shellStream(gpa); + defer gpa.free(session_only); + const asked = if (bytes_kind) try questions(dir) else ""; + defer if (bytes_kind) gpa.free(asked); + const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, asked }); defer gpa.free(shell_session); const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes); @@ -1582,6 +1610,23 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { if (soak.err) |err| return err; } +/// What the shell's program asks its terminal at the end of its session +/// (`--bytes`): device attributes, the cursor's place, the cell's size in +/// pixels, a kitty query; then a kitty image by direct data, shown, and one +/// by a file of the session's machine, stored (a=t), which no client loads +/// (P32): absent there, as every live terminal's image is under screen +/// state. Shown (a=T) it would move the session's cursor past it and not a +/// client's: a divergence until the file's bytes are taped (a later step). +fn questions(dir: []const u8) ![]u8 { + var path_buf: [300]u8 = undefined; + const path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/pixels.rgb", .{dir}, 0); + try writeText(path, &@as([12]u8, @splat(0x7f))); + var b64: [400]u8 = undefined; + const name = std.base64.standard.Encoder.encode(&b64, path); + return std.fmt.allocPrint(gpa, "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n" ++ + "\x1b_Ga=T,i=5,f=24,s=2,v=2;AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=t,i=6,t=f,f=24,s=2,v=2;{s}\x1b\\\r\n$ ", .{name}); +} + /// A typist: keys 50-200 ms apart, a pause now and then. fn typistGap(random: std.Random) u64 { return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000); @@ -2720,6 +2765,10 @@ pub fn main(init: std.process.Init) !void { echo_mode = true; continue; } + if (std.mem.eql(u8, name, "--bytes")) { + bytes_kind = true; + continue; + } if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; @@ -2785,7 +2834,9 @@ pub fn main(init: std.process.Init) !void { defer stop_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; + pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); + if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000 }); const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 6c3bc950..4825d1dc 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -30,7 +30,7 @@ |32: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Del |33: 1 beta body == snap promoted grid=120x41 cursor=7,33 -|22: +Search 2/3 Save Unattach Del +|22: +Search 2/3 Save Undock Del |32: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Term Collapse Follow Del == snap nomatch grid=120x41 cursor=11,14 |13: ^ +Search 0 Del @@ -43,7 +43,7 @@ == snap cancel grid=120x41 cursor=7,3 |13: |14: -|22: +Search 2/3 Save Unattach Del +|22: +Search 2/3 Save Undock Del |23: Find zqm |24: zqmark-alpha.txt |25: sub/ZQMARK-beta.txt diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index e923cb58..71a9900a 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -71,7 +71,7 @@ |8: 6 MARK b |9: ^ +Search 2/3 Del == snap landed grid=180x31 cursor=10,8 -|9: +Search 2/3 Save Unattach Del +|9: +Search 2/3 Save Undock Del == snap n grid=180x31 cursor=10,8 |7: 9 l9 |8: 10 MARK c diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 30c8612c..52633372 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -36,10 +36,10 @@ |14: 1 deep |15: 2 TARGET inside sub == snap opened-hit grid=180x31 cursor=12,15 -|9: +Search 3/3 Save Unattach Del +|9: +Search 3/3 Save Undock Del |13: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Term Collapse Follow Del == snap nomatch grid=180x31 cursor=11,15 -|14: ^ +Search 0+ Del +|14: ^ +Search 0 Del |15: Grep zzqq == snap esc grid=180x31 cursor=12,15 |14: 1 deep diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 92b619e4..c677fb8f 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -69,7 +69,7 @@ |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#3c614a, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-149 #f5f7ee,#0d1410, == snap hit1 grid=150x31 cursor=17,15 -|21: +Search 2/2 Save Unattach Del +|21: +Search 2/2 Save Undock Del |22: /NEEDLE |23: r.txt:7:4 gg NEEDLE gg |24: r.txt:8:6 hhhh NEEDLE diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 44b16309..42c378d1 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -26,5 +26,5 @@ |19: /tmp/pardes-snap/lsp-client/cwd/+Preview Del |20: 1 == snap gr-opened grid=100x25 cursor=21,6 -|13: +Search 2/3 Save Unattach Del +|13: +Search 2/3 Save Undock Del == snap gr-back grid=100x25 cursor=21,7 diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 36f411ef..964f0286 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -29,7 +29,7 @@ | 1 == snap abslook grid=100x35 cursor=21,27 |3: 1 const shade = @import("../shade.zig"); -|16: +Search 1/2 Save Unattach Del +|16: +Search 1/2 Save Undock Del |26: /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Term Collapse Follow TreeContext Def Refs Del |27: 1 pub const Shade = enum { |28: 2 verdigris, @@ -103,7 +103,7 @@ | 1 == snap sublook grid=100x35 cursor=20,28 |3: 1 const tint = @import("inner/tint.zig"); -|16: +Search 1/2 Save Unattach Del +|16: +Search 1/2 Save Undock Del |26: /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Term Collapse Follow TreeContext Def Refs |27: Del |28: 1 pub const Tint = enum { diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index 1b7d3245..9af17689 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -84,5 +84,5 @@ |18: 0-0 d,#608269, 1-149 d,#0d1410, |22: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-46 #d3b0d9,#1d2824, 47-149 #b2c3b8,#1d2824, == snap blank-opened grid=150x31 cursor=7,23 -|12: +Search 1/1 Save Unattach Del +|12: +Search 1/1 Save Undock Del |22: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Term Collapse Follow Del diff --git a/test/terminal.zig b/test/terminal.zig index e6c530d5..b7b9cd33 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -34,7 +34,6 @@ const prompt = Term.prompt; const scroll = Term.scroll; const scrollback = Term.scrollback; const commandOutput = Term.commandOutput; -const petscii = Term.petscii; const filterOf = emu.filterOf; const filterPalette = emu.filterPalette; const keyedRgb = emu.keyedRgb; @@ -892,7 +891,7 @@ test "a terminal's image is a placement whatever the frontend draws, and the Pet try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); defer restored.deinit(); - try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); + try std.testing.expect(restored.panes[0].?.term_petscii); try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); @@ -904,12 +903,12 @@ test "a new terminal draws its program's images as pixels, and one without image const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); - try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); + try std.testing.expect(!p.panes[0].?.term_petscii); // A pane without images says nothing of them. try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); const id = p.freeSlot().?; const fresh = try p.newShell(id, ""); - try std.testing.expectEqual(false, petscii(fresh.terminal).?); + try std.testing.expect(!fresh.term_petscii); } test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { |
