From 0ff1fc99eb870f8a1e714a71c1a853066737c822 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 4 Nov 2026 20:54:21 -0300 Subject: rename: the terminal frontend is the tui (-Dplatform=tui, src/tui/tui.zig, --tui with --tty kept as its old spelling, the process tests' backend .tui and --backend=tui, docs/typ/builtins-tui.json, the Settings report's platform), and the builtin Tty is Term (its registry entry, SPC n t, every default tag, the docs, tests and snap scripts), Tty still run as Term through exec.acme_words, Tty+fish too on a tag and a ctl; tty as a pane's raw mode and as the OS's terminal unchanged Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- .agents/skills/pardes-9p/SKILL.md | 2 +- .agents/skills/pardes/SKILL.md | 2 +- README.md | 2 +- build.zig | 36 +- build/snap.zig | 2 +- docs/effects.md | 4 +- docs/helix-keys.md | 4 +- docs/macos.md | 8 +- docs/next-daemon.md | 22 +- docs/next-pdfrender.md | 2 +- docs/next-tests.md | 6 +- docs/render-pipeline.md | 10 +- docs/shared-libs.md | 2 +- docs/site/README | 4 +- docs/typ/README | 14 +- docs/typ/building.typ | 16 +- docs/typ/builtins-gui.json | 2 +- docs/typ/builtins-tty.json | 144 -- docs/typ/builtins-tui.json | 144 ++ docs/typ/builtins.typ | 2 +- docs/typ/cheatsheet.typ | 12 +- docs/typ/guide.typ | 12 +- docs/typ/install.typ | 2 +- docs/typ/reference.typ | 17 +- docs/typ/style.typ | 12 +- docs/typ/themes.typ | 4 +- docs/ui-review.md | 10 +- src/builtins.zig | 14 +- src/builtins_json.zig | 6 +- src/colors.zig | 2 +- src/config.zig | 24 +- src/crash.zig | 2 +- src/daemon.zig | 2 +- src/detached/wire.zig | 4 +- src/draw.zig | 8 +- src/dump.zig | 2 +- src/effect_sources.zig | 12 +- src/esp32p4.zig | 10 +- src/exec.zig | 25 +- src/file_watch.zig | 6 +- src/fonts.zig | 2 +- src/fs.zig | 2 +- src/gui/gui.zig | 10 +- src/host_io.zig | 6 +- src/lsp/lsp_client.zig | 2 +- src/main.zig | 29 +- src/ninep/cols.zig | 24 +- src/ninep/ctl.zig | 53 +- src/ninep/pane.zig | 2 +- src/ninep/pty.zig | 2 +- src/ninep/tree.zig | 4 +- src/panes.zig | 6 +- src/pardes.zig | 84 +- src/replica.zig | 6 +- src/selection_pipe.zig | 2 +- src/surface.zig | 2 +- src/tagline.zig | 4 +- src/tape.zig | 2 +- src/terminal.zig | 4 +- src/themes/acme.zig | 2 +- src/tty/panel_compositor.zig | 706 ------ src/tty/tty.zig | 4017 ----------------------------------- src/tui/panel_compositor.zig | 706 ++++++ src/tui/tui.zig | 4017 +++++++++++++++++++++++++++++++++++ src/tutor.txt | 10 +- test/agent_session.py | 2 +- test/appearance_gallery.py | 4 +- test/behaviour/columns_and_tags.zig | 16 +- test/behaviour/look_and_exec.zig | 4 +- test/behaviour/modes.zig | 6 +- test/behaviour/mouse.zig | 2 +- test/behaviour/tags.zig | 24 +- test/column_tags.py | 34 +- test/daemon.py | 14 +- test/e2e_harness.zig | 4 +- test/fs.py | 2 +- test/gui_golden.py | 4 +- test/image_harness.zig | 2 +- test/kitty.zig | 2 +- test/kitty_harness.zig | 4 +- test/monkey.zig | 2 +- test/monkey9p.zig | 10 +- test/output.zig | 2 +- test/pdf_scroll_bench.zig | 6 +- test/perf.zig | 4 +- test/process.zig | 16 +- test/process/builtins.zig | 8 +- test/process/flags.zig | 32 +- test/process/look_and_exec.zig | 6 +- test/process/mounts.zig | 6 +- test/process/repls.zig | 4 +- test/process/root_ctl.zig | 12 +- test/process/terminals.zig | 20 +- test/process/tree.zig | 2 +- test/process_test.zig | 2 +- test/record_casts.py | 8 +- test/record_demos.py | 6 +- test/replicas.zig | 4 +- test/rollback_bench.zig | 2 +- test/selfmount.py | 6 +- test/snapshot.zig | 4 +- test/snapshots/images.snap | 8 +- test/snapshots/look-fd-deep.snap | 2 +- test/snapshots/look-file-1col.snap | 2 +- test/snapshots/ttyclick.snap | 4 +- test/snapshots/ttyonly.snap | 4 +- test/soak.py | 6 +- test/tag_cleanup.py | 4 +- test/ui_review.py | 8 +- test/window_opacity.py | 2 +- test/yazi_preview.py | 2 +- tools/gen_builtins_json.zig | 2 +- tools/shared_libs_check.zig | 2 +- 113 files changed, 5339 insertions(+), 5311 deletions(-) delete mode 100644 docs/typ/builtins-tty.json create mode 100644 docs/typ/builtins-tui.json delete mode 100644 src/tty/panel_compositor.zig delete mode 100644 src/tty/tty.zig create mode 100644 src/tui/panel_compositor.zig create mode 100644 src/tui/tui.zig diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 2b80c975..0c51394e 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -100,5 +100,5 @@ Keep `SHELL` (bash or fish): without it the terminals run `/bin/sh`, which gets no OSC 133 prompt marks, and `pty/run` answers `error no prompt marks`. -To test a change, build with `-Dplatform=tty` (it installs into +To test a change, build with `-Dplatform=tui` (it installs into `zig-out`): a bare `zig build` installs over `~/.local/bin`. diff --git a/.agents/skills/pardes/SKILL.md b/.agents/skills/pardes/SKILL.md index d49f8e50..6e2f2eff 100644 --- a/.agents/skills/pardes/SKILL.md +++ b/.agents/skills/pardes/SKILL.md @@ -101,7 +101,7 @@ Addresses are sam's (`#n /re/ ?re? $ a,b`). | Common words | | |---|---| | `Save` `Del` `Get` `Undo` `Edit` | pane; Del/Exit/Restore refuse once over unsaved text, again discards | -| `New` `Tty` `Tty+bash` `Newcol` `Delcol` | panes and columns | +| `New` `Term` `Term+bash` `Newcol` `Delcol` | panes and columns | | `Find name` `Grep text` `Recent` | listings in a `+Search` | | `Kill make` `Repl python` `Filter` `Mode` | terminals and commands | | `Dump` `Restore` `Config` `DumpConfig` `Theme x` | workspace and settings | diff --git a/README.md b/README.md index 4ad49cc6..81511c11 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ over 9P, that any program can drive. Get the source with `git clone https://git.sr.ht/~gbrls/pardes && cd pardes` (also at https://git.0x4200.cafe/pardes). Install with Zig 0.17: -`zig build -Dplatform=tty --prefix ~/.local` for +`zig build -Dplatform=tui --prefix ~/.local` for `pardes` in a terminal, or `-Dplatform=gui` for the `pardes-gui` window. The terminal should report the mouse; Shift-Esc (the Esc a terminal pane's program gets) needs the kitty keyboard protocol, and images need kitty graphics (else they are drawn as PETSCII diff --git a/build.zig b/build.zig index 05bc59b7..b790f57d 100644 --- a/build.zig +++ b/build.zig @@ -25,7 +25,7 @@ const deps_text = blk: { break :blk text; }; -pub const Platform = enum { tty, gui, web, macos, esp32p4 }; +pub const Platform = enum { tui, gui, web, macos, esp32p4 }; const PerfBuild = struct { compiler: []const u8, @@ -71,8 +71,8 @@ const gui_shaders = [_][]const u8{ }; pub fn build(b: *std.Build) void { - const requested_platform = b.option(Platform, "platform", "which shell to build (tty, gui, web, macos, esp32p4); absent builds the tty cli and the SDL gui together"); - const platform = requested_platform orelse .tty; + const requested_platform = b.option(Platform, "platform", "which shell to build (tui, gui, web, macos, esp32p4); absent builds the tui cli and the SDL gui together"); + const platform = requested_platform orelse .tui; const also_gui = requested_platform == null; // A bare `zig build` also copies the binaries into ~/.local/bin. Zig // 0.17 keeps the prefix in the maker process, out of this script's @@ -97,7 +97,7 @@ pub fn build(b: *std.Build) void { .os_version_min = .{ .semver = macos_min_version }, } else .{}, .esp32p4 => esp32p4_target, - .tty, .gui, .web => .{ + .tui, .gui, .web => .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu, @@ -225,13 +225,13 @@ pub fn build(b: *std.Build) void { if (is_web and !is_web_target) return failBuild(b, web_step, "-Dplatform=web requires -Dtarget=wasm32-freestanding"); if (!is_web and (is_web_target or target.result.os.tag == .emscripten)) return failBuild(b, web_step, "wasm browser targets require -Dplatform=web"); if (platform == .web and dump_path == null) return failBuild(b, web_step, "-Dplatform=web requires -Ddump= (the browser has no ptys; state replays from an embedded dump)"); - if (enable_mupdf and is_web) return failBuild(b, web_step, "-Dmupdf=true is supported only by the native tty/Kitty and gui/SDL backends"); + if (enable_mupdf and is_web) return failBuild(b, web_step, "-Dmupdf=true is supported only by the native tui/Kitty and gui/SDL backends"); // The board's target is pinned (`target` above), so what is asked of // -Dtarget is checked, not what was resolved: another arch is refused, // not silently built for the board anyway. const requested_board = requested_target.result.cpu.arch == .riscv32 and requested_target.result.os.tag == .freestanding; if (is_esp32p4 and !requested_board) return failBuild(b, web_step, "-Dplatform=esp32p4 requires -Dtarget=riscv32-freestanding (ESP32-P4 firmware)"); - if (enable_mupdf and is_esp32p4) return failBuild(b, web_step, "-Dmupdf=true is supported only by the native tty/Kitty and gui/SDL backends"); + if (enable_mupdf and is_esp32p4) return failBuild(b, web_step, "-Dmupdf=true is supported only by the native tui/Kitty and gui/SDL backends"); if (is_esp32p4 and requested_grammars != null and requested_grammars.? != .disabled) return failBuild(b, web_step, "-Dplatform=esp32p4 has no tree-sitter: the grammars' parse tables are megabytes and the flash partition is 1.5 MiB (-Dtree-sitter=disabled)"); // build-time IO: slurps the grammars' highlights.scm queries, and reads @@ -249,7 +249,7 @@ pub fn build(b: *std.Build) void { .web => "src/web.zig", .macos => "src/macos.zig", .esp32p4 => "src/esp32p4.zig", - .tty, .gui => "src/main.zig", + .tui, .gui => "src/main.zig", }), .link_libc = !freestanding_core, }); @@ -260,7 +260,7 @@ pub fn build(b: *std.Build) void { .link_libc = true, }); - const isolated_mod: ?*std.Build.Module = if (platform == .tty) b.createModule(.{ + const isolated_mod: ?*std.Build.Module = if (platform == .tui) b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/main.zig"), @@ -901,7 +901,7 @@ pub fn build(b: *std.Build) void { \\ ; // And its event queue: a pop that makes room woke one blocked - // writer, and only on the pop from full. The tty has two writers + // writer, and only on the pop from full. The tui has two writers // (a pane's pty reader, and the input reader posting the frame // ack's wake), so when the loop emptied a full queue in one batch // the writer not woken waited on for good: under `yes` the pane @@ -1041,10 +1041,10 @@ pub fn build(b: *std.Build) void { // docs/typ/builtins-.json: every builtin, from the registry and the Help // rows (src/builtins_json.zig), rewritten in the source tree so a plain // `typst compile` reads it too; a unit test fails when it is stale. - // A terminal build writes builtins-tty.json and a window build + // A terminal build writes builtins-tui.json and a window build // builtins-gui.json; style.typ merges the two into one glossary. - const builtins_json_step = b.step("builtins-json", "rewrite docs/typ/builtins-.json from the builtin registry (-Dplatform=tty or gui)"); - if (requested_platform == .tty or requested_platform == .gui) { + const builtins_json_step = b.step("builtins-json", "rewrite docs/typ/builtins-.json from the builtin registry (-Dplatform=tui or gui)"); + if (requested_platform == .tui or requested_platform == .gui) { const gen = b.addExecutable(.{ .name = "pardes-gen-builtins-json", .root_module = b.createModule(.{ .target = target, .optimize = optimize, @@ -1057,7 +1057,7 @@ pub fn build(b: *std.Build) void { update.addCopyFileToSource(json, b.fmt("docs/typ/builtins-{s}.json", .{@tagName(platform)})); builtins_json_step.dependOn(&update.step); for (doc_renders) |r| if (r) |run| run.step.dependOn(&update.step); - } else builtins_json_step.dependOn(&b.addFail("builtins-json writes one build's list: pass -Dplatform=tty or -Dplatform=gui").step); + } else builtins_json_step.dependOn(&b.addFail("builtins-json writes one build's list: pass -Dplatform=tui or -Dplatform=gui").step); const gui_shell_mod: ?*std.Build.Module = gui_mod orelse if (platform == .gui) root_mod else null; @@ -1409,13 +1409,13 @@ pub fn build(b: *std.Build) void { } const run_image_harness = b.addRunArtifact(image_harness); run_image_harness.addArtifactArg(exe); - run_image_harness.addArg(if (platform == .gui) "gui" else "tty"); + run_image_harness.addArg(if (platform == .gui) "gui" else "tui"); run_image_harness.has_side_effects = true; b.step("image-harness", "exercise native Kitty/SDL image rendering end to end").dependOn(&run_image_harness.step); // Kitty graphics through a terminal pane, end to end: a client in // the pane's bash (and kitten icat, chafa when installed), a kitty - // terminal outside (tty) or the GPU capture (gui). test/kitty.zig + // terminal outside (tui) or the GPU capture (gui). test/kitty.zig // is the same protocol at the core. const kitty_client = b.addExecutable(.{ .name = "pardes-kitty-client", @@ -1443,7 +1443,7 @@ pub fn build(b: *std.Build) void { const run_kitty_harness = b.addRunArtifact(kitty_harness); run_kitty_harness.addArtifactArg(exe); run_kitty_harness.addArtifactArg(kitty_client); - run_kitty_harness.addArg(if (platform == .gui) "gui" else "tty"); + run_kitty_harness.addArg(if (platform == .gui) "gui" else "tui"); run_kitty_harness.has_side_effects = true; b.step("kitty-harness", "kitty graphics through a terminal pane end to end (a client inside, a kitty terminal or the GPU capture outside)").dependOn(&run_kitty_harness.step); @@ -1451,7 +1451,7 @@ pub fn build(b: *std.Build) void { if (enable_mupdf) { const run_pdf_harness = b.addRunArtifact(image_harness); run_pdf_harness.addArtifactArg(exe); - run_pdf_harness.addArg(if (platform == .gui) "gui" else "tty"); + run_pdf_harness.addArg(if (platform == .gui) "gui" else "tui"); run_pdf_harness.addArg("pdf"); run_pdf_harness.has_side_effects = true; pdf_harness_step.dependOn(&run_pdf_harness.step); @@ -1968,7 +1968,7 @@ pub fn build(b: *std.Build) void { unit_step.dependOn(&run_deck_test.step); if (unit_match) |check| check.addArtifactArg(deck_test); - if (platform == .tty or platform == .gui) { + if (platform == .tui or platform == .gui) { const shell_test = b.addTest(.{ .root_module = root_mod, .filters = test_filters }); if (test_nonce) |nonce| shell_test.root_module.addImport("test_rebuild_nonce", nonce); test_build.dependOn(&shell_test.step); diff --git a/build/snap.zig b/build/snap.zig index 75e578bf..544144d9 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -64,7 +64,7 @@ pub fn addTty(b: *std.Build, opts: struct { } const run_process_test = b.addRunArtifact(process_test); run_process_test.addArtifactArg(opts.exe); - run_process_test.addArg(if (opts.gui) "--backend=gui" else "--backend=tty"); + run_process_test.addArg(if (opts.gui) "--backend=gui" else "--backend=tui"); run_process_test.addPassthruArgs(); run_process_test.has_side_effects = true; b.step("process-test", "run the process tests: real sessions driven over their sockets (-- [filter])").dependOn(&run_process_test.step); diff --git a/docs/effects.md b/docs/effects.md index 894bd75d..1c1a9cac 100644 --- a/docs/effects.md +++ b/docs/effects.md @@ -266,13 +266,13 @@ it does in a pixel shell. | # | effect | switch | state | review material | verdict | |---|---|---|---|---|---| -| T2 | cursor jump trail | `JumpTrail on\|off` (off) | a jump of three cells or more leaves 3 to 5 cells of trail behind the cursor, their ground drawn toward the text's colour in OKLab, most beside it, fading in 120 ms; truecolor terminals (vaxis's answer or COLORTERM); never the cursor's cell, a selection or outside the focused body; off under Motion off; a few cells a frame | .scratch/render/tty/trail/ (pyte replay of a real tty session at 60 fps: trail-forge.mp4, zooms) | pending | +| T2 | cursor jump trail | `JumpTrail on\|off` (off) | a jump of three cells or more leaves 3 to 5 cells of trail behind the cursor, their ground drawn toward the text's colour in OKLab, most beside it, fading in 120 ms; truecolor terminals (vaxis's answer or COLORTERM); never the cursor's cell, a selection or outside the focused body; off under Motion off; a few cells a frame | .scratch/render/tty/trail/ (pyte replay of a real tui session at 60 fps: trail-forge.mp4, zooms) | pending | | T1 chip shadow | `ChipShadow on\|off` (off) | a notice chip casts a shadow a cell right and down in its body: half blocks (▌ ▀ ▘) in a darker ground on blank cells, the ground 35% darker (OKLab) under text; never the cursor, a selection, a tag or another chip; truecolor only | .scratch/render/tty/shadow/ (forge, acme; zooms) | pending | | T4 ordered swap | `PanelDissolve` (off) | the terminal's dissolve swaps each changed cell once at its place in a 4x4 Bayer matrix (shifted per pane), an even patterned screen instead of noise; hit-testing follows the same order | .scratch/render/tty/dissolve/ (ordered-swap-sim: the matrix applied to two real frames; see note) | pending | | T7 thumb flash | `ThumbFlash on\|off` (off) | a pane whose view moves has its scroll thumb drawn toward the text's colour, 60% at once and back over 250 ms (quadratic); the thumb only, never a focus indicator; truecolor only; a few cells a frame while it fades | .scratch/render/tty/thumb-flash.mp4, thumb-flash-strip.png (pyte replay, forge) | pending | | T3 wipe | `PanelCurtain` (off) | the curtain becomes a wipe, left to right: new grid behind the head, old ahead, and a soft edge of two columns whose ink and ground sit 2/3 and 1/3 of the way to the old ground (OKLab; a palette colour steps at the half); only the head's columns change a frame; the head's cells are not hit-testable until settled | .scratch/render/tty/wipe/ (curtain-gui.mp4, curtain-edge-zoom.png) | pending | -Note on T4's material: a pane opening in a tty session recorded through +Note on T4's material: a pane opening in a tui session recorded through pyte did not animate (PanelSlide did not either there), so the review material applies the same matrix to two real frames of that session; the unit test holds the order (a 4x4 block reveals exactly t x 16 cells). diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 04aa60dd..b172caab 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -133,7 +133,7 @@ language-backend queries, and the shell pipe. | `Alt-c` | move active terminal to a fresh column (outside raw tty) | helix `Alt-c` is change-noyank; the pardes window op wins (do-not-touch contract). `Alt-d` + `i` covers the behavior | waived (`alt-c-window-op`) | | `Space` (normal, body) | starts the pardes LEADER: a key path runs the same builtin words used by tags and the topbar. The main groups are `f` files, `h` docs, `c` columns, `t` toggles/effects, `a` panel animations, `s` session, `j` jumps, `l` language, and `w` directional focus; `SPC ?` lists every path and ` ?` lists one group in `+Help`. Neither `Exit` (quits the editor, acme's Exit) nor `Kill` (stops the commands pardes typed into terminals, acme's Kill) has a leader path: both are the topbar's and the root `ctl`'s. The pending path appears on the active pane's transient body/message row. Esc or an unmapped key abandons it. Paths, Help rows, and dispatch are all generated from the builtin registry at comptime; the leader applies only to a BODY in normal mode because tags and tty programs own their input | pardes-specific; helix spends Space on pickers/LSP (section C), while pardes uses acme-style executable words | | `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the same as `"+y`, `"+p`, `"+P`, `"+R`: register `+` (and `*`) IS the desktop's clipboard, the only register that reaches it. `SPC y` writes `+` alone, as helix's does, not the default register too. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. The clipboard holds one text, so N values go out joined by newlines, as helix sends them. On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | -| a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tty shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | +| a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tui shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | | `/` (a text) | a query pane under the pane (`src/Query.zig`): a `+Search` whose line 1 is the query, typed into; helix's regex with smart case, every match tinted and ticked on the rail as you type (the pane's places, `src/Places.zig`), the first after the cursor selected (helix's incremental preview). `Ctrl-n`/`Ctrl-p` step while typing; Enter lands, fills `/` and keeps the rows as text; Esc while typing restores the text and closes the pane. Line 1's first word names the source (`/`, `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All`, `Refs`, `Def`, `Impl`, `Diagnostics`), helix's pickers as one pane. A terminal's and a PDF's `/` keep the notice-band prompt and its `+Search` | helix's `/` semantics (regex, smart case, preview); the pane is pardes' | pardes-specific | | `n` / `N` | next / previous match of the text's places when a query pane fed them (a `/`, a list's places in this text: refs, diagnostics, a Grep's hits), round the ends without a message; else the last search register's regex in the current text, as before; counts repeat | only the primary selection is replaced; in select mode each match is added and becomes primary. Named registers work. `*` sets the pattern from selections with word boundaries (`Alt-*` without) and seeds the text's query pane with it, the keyboard staying. The former Look ring is `LookNext` / `LookPrev`, `SPC j n` / `SPC j p`. PDFs retain their location-result navigation | helix-verified | @@ -341,7 +341,7 @@ text. | `Ctrl-u` | kill to line start | | helix-verified (phase 5) | | `Ctrl-k` | kill to line end | | helix-verified (phase 5) | | `Ctrl-h` | delete prev char (Backspace alias) | | helix-verified (phase 5) | -| `Ctrl-d` / `Delete` | delete next char; at line end joins the next line up | `Key.delete` (0xF0009) added + `mapKey` in tty.zig/gui.zig (vaxis + SDLK) + `forwardKey` sends `ESC[3~` in tty mode | helix-verified (phase 5) | +| `Ctrl-d` / `Delete` | delete next char; at line end joins the next line up | `Key.delete` (0xF0009) added + `mapKey` in tui.zig/gui.zig (vaxis + SDLK) + `forwardKey` sends `ESC[3~` in tty mode | helix-verified (phase 5) | | `Ctrl-j` | insert newline (Enter alias) | | helix-verified (phase 5) | | `Home` / `End` | line start / line end past-the-last-char (`goto_line_end_newline`) | file panes (terminal insert cursor rides its run, as before) | helix-verified (phase 5) | | `PageUp` / `PageDown` | cursor page up / down, col kept (clamped to line) | file panes | helix-verified (phase 5) | diff --git a/docs/macos.md b/docs/macos.md index 3ee55d0a..ddd7eee1 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -77,7 +77,7 @@ fourteen are filled in (`src/macos.zig:1761`). The machine-local half of those methods is no longer this file's. `forkShell`, `writeFileBytes` and `writeFd` live in `src/host_io.zig` and are shared with -the tty shell, the SDL shell and the detached daemon; `src/macos.zig` calls +the tui shell, the SDL shell and the detached daemon; `src/macos.zig` calls them (`:1807`, `:1823`, `:1848`, `:1863`) and its own copies, together with the four `extern "c"` declarations they needed (`forkpty`, `execv`, `chdir`, `_exit`), are gone. Two `extern "c"` declarations remain here: `setenv`, and @@ -473,7 +473,7 @@ has none: between fork and exec can deadlock on the heap a pty reader thread was holding. Every pane is emulated by the bundled VT, so the value describes pardes and never the terminal pardes was started from; `-Dplatform=gui` and - the tty shell take the same path, where the difference is only that their + the tui shell take the same path, where the difference is only that their launcher usually happened to set something. The names come from `config.child_term` / `child_colorterm` / `child_term_program`, and `TERM` is deliberately `xterm-256color` rather than a name with no installed @@ -586,7 +586,7 @@ theme it cannot. showed *nothing at all*: with `native_images` false the core assumes a terminal that cannot draw pixels and degrades a document to counted page turns, and this host never set it. It does now — this shell draws pixels, which is a fact -rather than a question (the tty backend has to ask the terminal about +rather than a question (the tui backend has to ask the terminal about kitty-graphics support; the SDL one just says yes, as we do). The transport is `pardes_image_s`, walked with `pardes_frame_images` / @@ -1122,7 +1122,7 @@ used for the table and is not folded into the direct-path claim. ## Not implemented - **The `lsp` effect.** Needs a worker plus a snapshot of the pane's path and - content taken *before* it starts, as `LspJob` in `tty.zig` does; the core + content taken *before* it starts, as `LspJob` in `tui.zig` does; the core keeps editing while a query is in flight. Until then every query is answered with an EMPTY `lsp_resp` rather than dropped — dropping one leaves the keystroke that asked (insert-mode Tab after a dot) waiting forever, and dead diff --git a/docs/next-daemon.md b/docs/next-daemon.md index 5537bf1a..9865e315 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -448,7 +448,7 @@ microseconds. Gates, on the line rebased onto main's screen-state terminals (mnlwlpvk): -- `zig build replay -Dplatform=tty`: 113 snapshot scripts pass (the 110, +- `zig build replay -Dplatform=tui`: 113 snapshot scripts pass (the 110, views.snap, views-term.snap and views-pan.snap), their 131 tapes replay in all three replicas (393 runs, 29,436 digests); 20 monkey seeds at one view (60 runs, 14,004 digests) and 20 at three views (60 runs, 9,666 @@ -488,9 +488,9 @@ Everything of ours lives in `/root/pardes-test`, nothing outside it. ```sh export PATH=$HOME/.local/bin:$PATH E='env -u PARDES_PID -u PARDES_PANE -u PARDES_9P' - $E zig build -Dplatform=tty -Dtarget=x86_64-freebsd.15.0 >log 2>&1 + $E zig build -Dplatform=tui -Dtarget=x86_64-freebsd.15.0 >log 2>&1 # zig-out/bin/pardes-freebsd-x86_64 - $E zig build test-install -Dplatform=tty -Dtarget=x86_64-freebsd.15.0 >log 2>&1 + $E zig build test-install -Dplatform=tui -Dtarget=x86_64-freebsd.15.0 >log 2>&1 # zig-out/test/{main,panes,kitty,9p,fonts,...}, named for their root files ``` @@ -760,7 +760,7 @@ thread start in the render). ## Tty throughput notes -Found and fixed 2026-10-29 (`src/tty/tty.zig`, `waitInput`). +Found and fixed 2026-10-29 (`src/tui/tui.zig`, `waitInput`). - **What the 1 GB `yes` cell measures is mostly the kernel.** A pty's output processing (ONLCR, a `\n` made `\r\n`) costs the writer about @@ -907,7 +907,7 @@ against that tty, is the Tty throughput notes' keystroke-to-present. tapes, plus real vim, nvim, htop, less and btop sessions recorded through a pty. Its corpus and recorder are in `.scratch/daemon/term`. - **Numbers** (ReleaseFast: `PARDES_SCREEN_STATE= zig build core-test - -Dplatform=tty -Doptimize=ReleaseFast -Dtest-filter=screen_state`, which + -Dplatform=tui -Doptimize=ReleaseFast -Dtest-filter=screen_state`, which runs under std.testing's checking allocator): - Encode, 200x60, every row new: p50 250 us, p99 487 us, 29.8 KB. - Encode, 200x60, nothing new: p50 71 us, p99 139 us, 534 bytes. That @@ -2180,7 +2180,7 @@ scripts are in `.scratch/daemon/remote/t2/`. `terminal.cellAt` (the final gate's notes, at the end). The gates, once at the end (Debug unless said): -- `zig build unit-test -Dplatform=tty` passes, its perf gate too; +- `zig build unit-test -Dplatform=tui` passes, its perf gate too; `-Dplatform=gui` 1563 of 1575, 10 skipped, and the two that fail on main already (`tagline pointer mapping...`, `a tag caret past its row's end...`). @@ -2800,7 +2800,7 @@ The hook for the remote client (its `Replica` and stream as they are): Measured. -- **The harness** (`zig build replicas -Dplatform=tty -- --echo`): one +- **The harness** (`zig build replicas -Dplatform=tui -- --echo`): one authority and one replica over part A's delayed, jittered link, the authority's pty a shell played in the harness (`FakeShell`): a line editor at a prompt with pardes's marks and Tab completion, and the @@ -2885,7 +2885,7 @@ The gates: rendered otherwise than predicted; it passes at 20 seeds, Debug and ReleaseFast. `zig build replicas` passes at 20 seeds, ReleaseFast (and 4 in Debug). -- Unit tests tty (`zig build unit-test -Dplatform=tty`, its perf gate +- Unit tests tty (`zig build unit-test -Dplatform=tui`, its perf gate too), the full `core-test`, and the 113 snapshot scripts pass; the GUI build's echo tests pass (`core-test -Dplatform=gui`). @@ -2957,7 +2957,7 @@ the installed (ReleaseSafe) binaries through the suites that start a real pardes. Gates, Debug unless said: -- `core-test`, `unit-test -Dplatform=tty` (its perf gate too), `snap` +- `core-test`, `unit-test -Dplatform=tui` (its perf gate too), `snap` (113/113), `replay`, `replicas` (no divergence, no wrong delta at 30/80/207 ms), `9p-io-test`, `fs-test`, `test/daemon.py` (20 cycles), `test/daemon.py --upgrade`, `test/fs.py`: all pass. @@ -3209,7 +3209,7 @@ Gates (Debug unless said; scripts and logs in `.scratch/daemon/amort/`): - **Suites**, once at the end: `core-test` (its run beside the box measurements had the 9P failure above; again, all pass), `unit-test - -Dplatform=tty` (its perf gate, and shared-libs-check, which now refuses + -Dplatform=tui` (its perf gate, and shared-libs-check, which now refuses a second zstd too), `snap` 113 of 113, `replay` (113 scripts, 20 monkey seeds, none panicked or diverged), `replicas`, `9p-io-test`, `fs-test`, `test/daemon.py` 20 cycles (its far clients included), `--upgrade` @@ -3521,7 +3521,7 @@ Gates (Debug unless said; scripts and logs in `.scratch/daemon/guirep/`): cycles, a second window detached alone): pass, Debug and ReleaseSafe (SDL's offscreen driver). - **Suites**, once at the end (before the tests' fix and the rebase below): - `core-test -Dplatform=tty`, `unit-test -Dplatform=tty` (its perf gate), + `core-test -Dplatform=tui`, `unit-test -Dplatform=tui` (its perf gate), `snap` 113 of 113, `replay` (113 scripts, 20 monkey seeds, none panicked or diverged), `replicas`, `9p-io-test`, `fs-test`, `test/daemon.py` 20 cycles, `--window-clients`, `--upgrade` (unstamped Debug to stamped), diff --git a/docs/next-pdfrender.md b/docs/next-pdfrender.md index e006aa48..4c8565d8 100644 --- a/docs/next-pdfrender.md +++ b/docs/next-pdfrender.md @@ -217,7 +217,7 @@ Look. `mupdf-check` (25, the lanes test among them); unit filters `PDF`, `pdf`, `off the loop`, `kept pages`, `page sizes off the loop`, `watch`, `JumpScope`, `Back`, `jump`, `Jump`, `Recent`, `a PDF's jumps`: green. The -snapshot suite (`zig build snap -Dplatform=tty`): all 110 scripts. The tty +snapshot suite (`zig build snap -Dplatform=tui`): all 110 scripts. The tty compiles (the suite builds it). The two baseline failures were not run. ## Open questions and positions diff --git a/docs/next-tests.md b/docs/next-tests.md index a3f298ff..a16a7cf9 100644 --- a/docs/next-tests.md +++ b/docs/next-tests.md @@ -52,7 +52,7 @@ agent's survey. The `e2e` line (kbdin, mousein) is its first step. Each backend's own (2026-11-04, the user: an effect's test is the backend's): - - **`zig build process-test -Dplatform=tty` drives `pardes`, `-Dplatform=gui` + - **`zig build process-test -Dplatform=tui` drives `pardes`, `-Dplatform=gui` drives `pardes-gui`,** hidden (PARDES_TEST, SDL_VIDEO_DRIVER=offscreen, no display of the user's) on a pty of its own and a 160x50 grid. `Detached.frame()` waits for the window to say it is idle and reads its @@ -168,7 +168,7 @@ What the M left need, most first: a host performs the effect. A Session option that performs saves (and keeps pty writes) unlocks a group in each area. - **A real host (T2):** terminals' output and shells, command panes - finishing, Tty and pty/ctl exec, a missing interpreter. + finishing, Term and pty/ctl exec, a missing interpreter. - **Image panes:** they need the decoder worker Session does not start. - **LSP:** a fake language server. - **Not reached yet:** jumps and Back/Forward, Zerox, Get, Restore, @@ -193,7 +193,7 @@ Traps the migrators found in Session, each now in its tests' code: `p.panes[`, `.file.?`, `p.rects` and the like. 2. Migrate, in the order the code is to be rewritten: ninep/ctl.zig (its checks only), test/pdf.zig (step 3 of the pane-kinds plan), - pardes.zig and test/panes.zig, replica, the gui and tty shells, + pardes.zig and test/panes.zig, replica, the gui and tui shells, host_io. A migrated test must fail on a build broken on purpose. 3. Gaps: a test for each documented behaviour with none. 4. Delete the M and X tests the new ones cover. diff --git a/docs/render-pipeline.md b/docs/render-pipeline.md index 9d41f7fa..ba5d131e 100644 --- a/docs/render-pipeline.md +++ b/docs/render-pipeline.md @@ -27,7 +27,7 @@ Ticks (`Event.tick`) are produced by six different clocks: | shell | who ticks | cadence | |---|---|---| -| tty | `tickWatch` thread: nanosleep 16 ms **after** the wait asked, then `postEvent(.tick)` (tty.zig:1513) | 16 ms + frame time: drifts slow, worse over ssh | +| tty | `tickWatch` thread: nanosleep 16 ms **after** the wait asked, then `postEvent(.tick)` (tui.zig:1513) | 16 ms + frame time: drifts slow, worse over ssh | | gui | `AnimationClock.due` in `postPresent` re-arms `now+16ms` (gui.zig:203, 221, 4095) | a tick only once ≥16 ms have passed since the re-arm: at 144 Hz every 3rd frame (20.8 ms) → animations ~25% slow; at 120 Hz every 2nd; a slow frame slows them further | | gui grid mode | every `poll_frame` while active (gui.zig ~4114) | as fast as the loop | | web | JS rAF fixed-step bank, capped (app.mjs:566) | correct average rate, always ticking | @@ -38,7 +38,7 @@ So the same animation runs at different speeds per shell. Everything counts 16 ms frames (`layout.Animation.frame_ms`, layout.zig:2041). Acknowledgement is also per shell: tty `postPresent` acks the tracks it drew -(tty.zig:1187), GUI acks then ticks (`finishPresentedAnimationFrame`), grid mode +(tui.zig:1187), GUI acks then ticks (`finishPresentedAnimationFrame`), grid mode acks `&.{}`, macOS acks via `pardes_frame_presented`, **web never acks**. ### 1.2 Core render (`Pardes.render`, pardes.zig:5950), in code order @@ -83,7 +83,7 @@ set `cell.hover`, 378-385 — a side channel for macOS glass). ### 1.4 Shells -- **tty** (tty.zig:1100): `panel_compositor.compose` rewrites cells for +- **tty** (tui.zig:1100): `panel_compositor.compose` rewrites cells for slide/zoom/dissolve/vertical → `paintCells` (win.clear + every cell) → kitty images (hidden while geometry moves) → cursor → `vx.render` (vaxis diffs against its last screen, wraps in sync 2026). Layers are ignored. @@ -698,8 +698,8 @@ character effects (ascii…typewriter) → not a GUI effect (terminal track). ### 9.2 Terminal track (tty, cell-native; separate, smaller) -Where: presentation-only cell rewrites in the tty shell after the canonical -grid (`tty/panel_compositor.zig` grows into the tty compositor), never in the +Where: presentation-only cell rewrites in the tui shell after the canonical +grid (`tui/panel_compositor.zig` grows into the tty compositor), never in the canonical grid, so 9P/goldens stay clean with effects off. Gated on truecolor (vaxis caps / COLORTERM) — static effects may quantise to 256, animated ones turn off below truecolor. Safe glyph set by default (░▒▓ ▀▄▌▐ ▖▗▘▝); diff --git a/docs/shared-libs.md b/docs/shared-libs.md index ce0c7d3f..0a78f207 100644 --- a/docs/shared-libs.md +++ b/docs/shared-libs.md @@ -13,7 +13,7 @@ The policy (2026-09-24): would clobber a patch made in zig-pkg. - **This file lists what is shared, and where the policy could not be met.** -`zig build shared-libs-check -Dplatform=tty|gui` (it also runs with every +`zig build shared-libs-check -Dplatform=tui|gui` (it also runs with every `unit-test`) reads the linked binary's ELF symbol table. It fails when a family the build chose against is linked again: stb_image's PNG, JPEG or inflate beside wuffs, a second stb_image, stb_image_write's deflate, a second zlib, or diff --git a/docs/site/README b/docs/site/README index 41804163..2a9989ff 100644 --- a/docs/site/README +++ b/docs/site/README @@ -15,13 +15,13 @@ docs/site: the pardes website, built from docs/typ is true it shows placeholder.svg instead. casts/casts.toml the terminal recordings (asciicast v2), in order: name, title, caption, cols, rows, ready; casts/N.cast each. - test/record_casts.py records them from a tty pardes + test/record_casts.py records them from a tui pardes and writes this file. Build (from the repo root): typst compile --root . --format bundle --features bundle,html docs/site/site.typ OUT - zig build site -Dplatform=tty --prefix DIR # DIR/share/doc/pardes/site/ + zig build site -Dplatform=tui --prefix DIR # DIR/share/doc/pardes/site/ Every page sits at the top of OUT and every link is relative, so the site works from file:// and from any static server. The only prose of the diff --git a/docs/typ/README b/docs/typ/README index 9d3913c0..d246c3ed 100644 --- a/docs/typ/README +++ b/docs/typ/README @@ -26,10 +26,10 @@ the topics, since the book and the HTML hold them all. Build (from the repo root): typst compile --ignore-system-fonts docs/typ/cheatsheet-a4.typ - zig build cheatsheet -Dplatform=tty --prefix DIR # DIR/share/doc/pardes/cheatsheet.pdf + zig build cheatsheet -Dplatform=tui --prefix DIR # DIR/share/doc/pardes/cheatsheet.pdf typst compile --root . --ignore-system-fonts docs/typ/book.typ typst compile --root . --format bundle --features bundle,html docs/site/site.typ OUT - zig build site -Dplatform=tty --prefix DIR # DIR/share/doc/pardes/site/ + zig build site -Dplatform=tui --prefix DIR # DIR/share/doc/pardes/site/ (--root . because book and HTML read the tutor from src/tutor.txt.) The contract for content files @@ -45,7 +45,7 @@ new function instead. word(w) a builtin or tag word, drawn as a chip on the tag's ground; a builtin links to its entry in the Builtins chapter wherever that chapter is in the same output. - #word("Save") #word("Tty+bash") + #word("Save") #word("Term+bash") key(k) one press, or a sequence of presses separated by spaces, drawn as one pill (Ctrl + w, g › g). Modifiers: Ctrl-, Alt-, Shift-. @@ -59,7 +59,7 @@ new function instead. #chord("B2", "B1") #chord("B1", "B2", "B3") tag(words, path:) a whole default tagline; words must be a default tag. - #tag("Save Tty Collapse Del", path: "/home/me/notes.txt") + #tag("Save Term Collapse Del", path: "/home/me/notes.txt") addr(a) a look address. #addr("file:12:5") file(p) a 9P path. #file("pane/N/addr") cmd(c) a shell line, as a block. #cmd("echo Save > $m/pane/$n/ctl") @@ -102,12 +102,12 @@ new function instead. Builtins -------- -builtins-tty.json and builtins-gui.json are every builtin of the terminal +builtins-tui.json and builtins-gui.json are every builtin of the terminal and the window build (name, leader, Help's other shortcuts, arg, scope, -setting, choices, doc), written by `zig build builtins-json -Dplatform=tty` +setting, choices, doc), written by `zig build builtins-json -Dplatform=tui` and `-Dplatform=gui` from the registry and the Help rows (src/builtins_json.zig). style.typ merges them, marking each word "both", -"tty" or "gui". The doc steps refresh their build's file first, and each +"tui" or "gui". The doc steps refresh their build's file first, and each build's unit-test fails when its file is stale. #word takes a name from either file. builtins.typ draws it as the glossary; `everyday`, `internals` and `builtin-groups` in style.typ say diff --git a/docs/typ/building.typ b/docs/typ/building.typ index c6ca4e36..24229f08 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -17,7 +17,7 @@ builds MuPDF and is on by default (`-Dmupdf=false` drops it). 9P over QUIC #pairs( [`zig build`], [the terminal shell and the SDL window together, *installed into `~/.local/bin`* (`pardes` and `pardes-gui`)], - [`zig build -Dplatform=tty`], [the terminal shell alone], + [`zig build -Dplatform=tui`], [the terminal shell alone], [`zig build -Dplatform=gui`], [the SDL3 window alone], [`zig build web -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=`], [a freestanding wasm core plus vanilla JavaScript (`docs/web.md`)], [`zig build -Dplatform=macos`], [an AppKit and CoreText app over a static `libpardes.a` (`docs/macos.md`)], @@ -45,7 +45,7 @@ there; its namespace is in `src/esp32p4_gpio.zig`. `zig build --help` lists the options for the selected platform. #pairs( - [`-Dplatform`], [`tty`, `gui`, `web`, `macos`, `esp32p4`; absent: the tty and SDL shells together, installed into `~/.local`], + [`-Dplatform`], [`tui`, `gui`, `web`, `macos`, `esp32p4`; absent: the tui and SDL shells together, installed into `~/.local`], [`-Dstatic`], [bool, `false`], [`-Dquic`], [bool, `false`: 9P over QUIC with system OpenSSL 3.6+], [`-Dmupdf`], [bool; on natively, off for web and esp32p4], @@ -75,7 +75,7 @@ zig build core-test core tests without native shell tests zig build pane-test pane, output, PDF and namespace integration tests zig build kitty-test kitty graphics conformance of terminal panes, at the core zig build kitty-harness kitty graphics through a pane end to end (a fake kitty - terminal outside on the tty, the GPU capture on the gui; + terminal outside on the tui, the GPU capture on the gui; kitten icat and chafa too when installed) zig build syntax-test tree-sitter tests without building the editor zig build syntax deterministic per-byte highlighting snapshots @@ -104,7 +104,7 @@ zig build cheatsheet render the cheatsheet PDF (needs typst) reading its diff, never all), `snap -- --no-retry` makes the first failure decisive. Snapshot scripts can use `snap9p` to capture core cells through 9P. -- `zig build monkey -Dplatform=tty -- [steps] [--from=N] [--out=DIR] [--keep]` writes one random script per seed and keeps any +- `zig build monkey -Dplatform=tui -- [steps] [--from=N] [--out=DIR] [--keep]` writes one random script per seed and keeps any that panics; a seed always makes the same script. Each crash found gets a fix and a regression script in `test/snapshots/`. - The tutor's practice blocks (`# keys:`, `# before`, `# after` in @@ -126,10 +126,10 @@ zig build cheatsheet render the cheatsheet PDF (needs typst) == Release gates -A release passes all of these first: `unit-test` with `-Dplatform=tty` and +A release passes all of these first: `unit-test` with `-Dplatform=tui` and with `-Dplatform=gui`, `core-test`, `behaviour-test`, `process-test`, `snap`, the GUI goldens (`python3 -B test/gui_golden.py `, a hidden window), -`web`, and the ReleaseSafe tty and ReleaseFast gui builds. The committed +`web`, and the ReleaseSafe tui and ReleaseFast gui builds. The committed `docs/typ/cheatsheet-a4.pdf` is rendered again when the docs change. = Sending patches @@ -142,7 +142,7 @@ Mail patches to the list `~gbrls/inbox@lists.sr.ht`; it is the preferred way to = The core and its shells -One core, five shells (tty, gui, web, macos, esp32p4). The core owns +One core, five shells (tui, gui, web, macos, esp32p4). 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. @@ -165,7 +165,7 @@ effects such as spawning processes. that the tests use. Comptime decides what a build has (`pardes.platform`, `hosted`, `can_attach`, `terminal_panes`, `pdf_enabled`); the vtable decides who serves it. -- The root module is chosen by platform: `main.zig` (tty, gui), +- The root module is chosen by platform: `main.zig` (tui, gui), `web.zig`, `macos.zig`, `esp32p4.zig`. The web and macOS shells are libraries whose host owns `main()`. - `memory.limits` is the one home for capacities that differ on the ESP32-P4 diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index c7553186..a78c2af0 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -137,6 +137,7 @@ {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, {"name": "Tagbottom", "leader": "SPC t b", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Each pane's tag goes at its foot rather than its head, on or off."}, {"name": "TaglineSize", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Scale the tag font, a percentage."}, + {"name": "Term", "leader": "SPC n t", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "A shell in the calling pane's directory, raw from the first frame."}, {"name": "TermImages", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "real, petscii", "doc": "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art."}, {"name": "Theme", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Switch to the named theme."}, {"name": "ThemeFile", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Load a theme from a file."}, @@ -145,7 +146,6 @@ {"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": "TreeContextTagStyle", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A pane's TreeContext rows draw in the tag's style, on or off."}, - {"name": "Tty", "leader": "SPC n t", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "A shell in the calling pane's directory, raw from the first frame."}, {"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."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json deleted file mode 100644 index 613627a7..00000000 --- a/docs/typ/builtins-tty.json +++ /dev/null @@ -1,144 +0,0 @@ -[ - {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, - {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, - {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, - {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, - {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, - {"name": "Callers", "leader": "SPC l c", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the callers of the function under the cursor."}, - {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, - {"name": "CallstackCorners", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "rounded, square", "doc": "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query."}, - {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, - {"name": "CallstackLayout", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "inline, stacked", "doc": "Callstack snippets below their locations (stacked, the default) or beside them (inline); bare, it switches layouts. Applies to the next Callstack query."}, - {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, - {"name": "ChipShadow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a notice chip casts a cell's shadow right and down, on or off."}, - {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, - {"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."}, - {"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."}, - {"name": "ClipYank", "leader": "SPC y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Copy the selection to the system clipboard."}, - {"name": "ClipYankMain", "leader": "SPC Y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "helix `Y`: the PRIMARY selection alone, where `SPC y` joins every cursor's."}, - {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor."}, - {"name": "Collapse", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Fold a pane to its tag, or restore its share of the column."}, - {"name": "Colors", "leader": "SPC t c", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Syntax colours in text panes, on or off."}, - {"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init`, in a pane: its pane when it is open, else the file, else a pane of that name for Save to make it and its directory."}, - {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, - {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, - {"name": "Del", "leader": "SPC d", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane."}, - {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, - {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, - {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, - {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes --attach` (or `pardes-gui --attach`) takes it back."}, - {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, - {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, - {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, - {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, - {"name": "Down", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, - {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, - {"name": "DumpConfig", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the settings in effect, each a word to click, and the startup file's path."}, - {"name": "DumpDir", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The directory Dump writes to and a relative Restore reads from; bare, the default."}, - {"name": "DumpThemes", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the bundled themes into the config directory's themes, to edit."}, - {"name": "Edit", "leader": null, "also": [], "arg": true, "scope": "both", "setting": false, "choices": null, "doc": "acme's Edit: sam's command language over the open text panes, from a tag, a pane ctl or exec, starting in the pane's body."}, - {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, - {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, - {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, - {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them."}, - {"name": "Find", "leader": "SPC f f", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the files below this pane's directory whose names hold its argument, in a +Search."}, - {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, - {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, - {"name": "Get", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Get: the pane's file read again, its unsaved edits refused once as Del refuses them."}, - {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches the LINES of those files, on the disk engine's worker."}, - {"name": "Help", "leader": "SPC ?", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the help: every key and every builtin."}, - {"name": "Hover", "leader": "SPC l k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Ask the language server about the symbol under the cursor."}, - {"name": "InactiveDim", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off."}, - {"name": "Incl", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "acme's Incl, for the session: `Incl dir ...` adds directories a look at a name found nowhere else is tried in (`stdio.h`, ``), bare lists them, `Incl -` empties the list."}, - {"name": "Joincol", "leader": "SPC c j", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Fold the active pane's column into the one on its right, keeping its panes."}, - {"name": "JumpScope", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "file, all", "doc": "What Back and Forward keep to: file, the focused pane's file until it runs out that way, or all, every place in order."}, - {"name": "JumpTrail", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a jump of the cursor leaves a short trail that fades, on or off."}, - {"name": "Jumplist", "leader": "SPC j l", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the places jumped from, each a place to go."}, - {"name": "Kill", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "acme's Kill: stop the commands pardes started -- the lines it typed into a terminal, from an exec, a middle click or a pty/run, while their shell says they run (C mark to D)."}, - {"name": "Last", "leader": "SPC j j", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Go back to the last place jumped from in another pane."}, - {"name": "Left", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the left."}, - {"name": "LocationsConfig", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Set how location rows are drawn, or show how they are when bare."}, - {"name": "Look", "leader": null, "also": ["enter", "right-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Look at its argument: open the file or address it names, else find the word, as a right click does."}, - {"name": "LookNext", "leader": "SPC j n", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the next Look location across panes; Enter opens it."}, - {"name": "LookPrev", "leader": "SPC j p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the previous Look location across panes; Enter opens it."}, - {"name": "LookWord", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "search, list", "doc": "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search."}, - {"name": "Lspinfo", "leader": "SPC l i", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show which language servers serve this file and their state."}, - {"name": "Lspwhy", "leader": "SPC l w", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Explain how the last language server request was answered, step by step."}, - {"name": "MessageAnimation", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A message falls into its row and dissolves out of it, on or off."}, - {"name": "MessageDissolve", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "How long, in milliseconds, a message takes to dissolve."}, - {"name": "MessageFall", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "How long, in milliseconds, a message takes to fall into its row."}, - {"name": "MessageLinger", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "How long, in milliseconds, a message stays after what dismisses it."}, - {"name": "Messages", "leader": "SPC h m", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the messages shown so far."}, - {"name": "Mini", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Open a minimap of the file in braille dots."}, - {"name": "Mode", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Cycle the pane's input modes: terminals add raw tty mode to normal/insert."}, - {"name": "More", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "A query pane's Grep stopped at its 2000 lines goes on for 2000 more."}, - {"name": "Motion", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "off, crisp, smooth, bouncy, playful", "doc": "How animations move: off, crisp, smooth, bouncy or playful."}, - {"name": "Mount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Mount another pardes's 9P tree under /n/, given its dial address."}, - {"name": "Msg", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show its argument on this pane's message row."}, - {"name": "New", "leader": "SPC f n", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Open an empty scratch pane, /+New, in this pane's directory."}, - {"name": "Newcol", "leader": "SPC c n", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "An empty column right of the keyboard's, its tag taking the keyboard."}, - {"name": "NextColor", "leader": "SPC t n", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Switch to the next bundled theme."}, - {"name": "Pager", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pardes, off", "doc": "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it."}, - {"name": "PagerColor", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A +Pager keeps its program's colours, on or off; for the next text paged."}, - {"name": "Palette", "leader": "SPC t l", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "the C64 palette or the terminal's own 16"}, - {"name": "PanelAscii", "leader": "SPC a a", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close through a scatter of ASCII, on or off."}, - {"name": "PanelCurtain", "leader": "SPC a c", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close like a curtain, on or off."}, - {"name": "PanelDissolve", "leader": "SPC a d", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes dissolve in and out as they open and close, on or off."}, - {"name": "PanelEdges", "leader": "SPC a e", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close from their edges, on or off."}, - {"name": "PanelFall", "leader": "SPC a f", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes fall into place as they open, on or off."}, - {"name": "PanelScramble", "leader": "SPC a r", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close through scrambled text, on or off."}, - {"name": "PanelSlide", "leader": "SPC a s", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes slide in and out as they open and close, on or off."}, - {"name": "PanelType", "leader": "SPC a t", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes type themselves in as they open, on or off."}, - {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, - {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, - {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, - {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, - {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, - {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, - {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."}, - {"name": "Petscii", "leader": "SPC t p", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "glyph art over the host's pixels: an image pane's picture, or the kitty graphics a terminal's program placed (yazi's previews)"}, - {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, - {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, - {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, - {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, - {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, - {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, - {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run."}, - {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, - {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, - {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, - {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, - {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, - {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, - {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, - {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, - {"name": "Shell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The shell new terminals run; bare, $SHELL if it is executable, else /bin/sh."}, - {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, - {"name": "Supertypes", "leader": "SPC l t", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the supertypes of the type under the cursor."}, - {"name": "Symbols", "leader": "SPC l s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's symbols from the language server."}, - {"name": "SyntaxBold", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Keywords and the like are drawn bold, on or off."}, - {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, - {"name": "Tagbottom", "leader": "SPC t b", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Each pane's tag goes at its foot rather than its head, on or off."}, - {"name": "TermImages", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "real, petscii", "doc": "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art."}, - {"name": "Theme", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Switch to the named theme."}, - {"name": "ThemeFile", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Load a theme from a file."}, - {"name": "Themes", "leader": "SPC t t", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the themes in a pane, each a word to click."}, - {"name": "ThumbFlash", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a pane's scroll thumb brightens as it scrolls and fades back, on or off."}, - {"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": "TreeContextTagStyle", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A pane's TreeContext rows draw in the tag's style, on or off."}, - {"name": "Tty", "leader": "SPC n t", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "A shell in the calling pane's directory, raw from the first frame."}, - {"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": "Unmount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Unmount the 9P tree mounted under /n/."}, - {"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."}, - {"name": "Upgrade", "leader": "SPC s U", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Move this session onto the pardes installed since it started, in place: its text, undo, views, terminals with their running shells, and its terminals and windows come along."}, - {"name": "Verbose", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A builtin says its own name on the message row as it runs, on or off."}, - {"name": "Window", "leader": "SPC w", "also": ["C-w"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Window mode: h/j/k/l move an outline between the panes; Enter or Esc focuses the outlined pane, `:` its tag, the letter shown on a pane that one; d is Del on it (then k or j between two), c Collapse."}, - {"name": "Wrap", "leader": "SPC t w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Long lines wrap onto the next row, on or off."}, - {"name": "WsDiagnostics", "leader": "SPC l D", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the workspace's diagnostics from the language server."}, - {"name": "WsSymbols", "leader": "SPC l S", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search the workspace's symbols for its argument."}, - {"name": "Zerox", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Zerox: a second pane on this pane's file, the same text, undo and unsaved state, with a scroll and a cursor of its own (File.zerox)."} -] diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json new file mode 100644 index 00000000..7592a745 --- /dev/null +++ b/docs/typ/builtins-tui.json @@ -0,0 +1,144 @@ +[ + {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, + {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, + {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, + {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, + {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, + {"name": "Callers", "leader": "SPC l c", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the callers of the function under the cursor."}, + {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, + {"name": "CallstackCorners", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "rounded, square", "doc": "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query."}, + {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, + {"name": "CallstackLayout", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "inline, stacked", "doc": "Callstack snippets below their locations (stacked, the default) or beside them (inline); bare, it switches layouts. Applies to the next Callstack query."}, + {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, + {"name": "ChipShadow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a notice chip casts a cell's shadow right and down, on or off."}, + {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, + {"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."}, + {"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."}, + {"name": "ClipYank", "leader": "SPC y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Copy the selection to the system clipboard."}, + {"name": "ClipYankMain", "leader": "SPC Y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "helix `Y`: the PRIMARY selection alone, where `SPC y` joins every cursor's."}, + {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor."}, + {"name": "Collapse", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Fold a pane to its tag, or restore its share of the column."}, + {"name": "Colors", "leader": "SPC t c", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Syntax colours in text panes, on or off."}, + {"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init`, in a pane: its pane when it is open, else the file, else a pane of that name for Save to make it and its directory."}, + {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, + {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, + {"name": "Del", "leader": "SPC d", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane."}, + {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, + {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, + {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, + {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal or window, leaving the session running: `pardes --attach` (or `pardes-gui --attach`) takes it back."}, + {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, + {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, + {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, + {"name": "Down", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, + {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, + {"name": "DumpConfig", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the settings in effect, each a word to click, and the startup file's path."}, + {"name": "DumpDir", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The directory Dump writes to and a relative Restore reads from; bare, the default."}, + {"name": "DumpThemes", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the bundled themes into the config directory's themes, to edit."}, + {"name": "Edit", "leader": null, "also": [], "arg": true, "scope": "both", "setting": false, "choices": null, "doc": "acme's Edit: sam's command language over the open text panes, from a tag, a pane ctl or exec, starting in the pane's body."}, + {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, + {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, + {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, + {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them."}, + {"name": "Find", "leader": "SPC f f", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the files below this pane's directory whose names hold its argument, in a +Search."}, + {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, + {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, + {"name": "Get", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Get: the pane's file read again, its unsaved edits refused once as Del refuses them."}, + {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches the LINES of those files, on the disk engine's worker."}, + {"name": "Help", "leader": "SPC ?", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the help: every key and every builtin."}, + {"name": "Hover", "leader": "SPC l k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Ask the language server about the symbol under the cursor."}, + {"name": "InactiveDim", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off."}, + {"name": "Incl", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "acme's Incl, for the session: `Incl dir ...` adds directories a look at a name found nowhere else is tried in (`stdio.h`, ``), bare lists them, `Incl -` empties the list."}, + {"name": "Joincol", "leader": "SPC c j", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Fold the active pane's column into the one on its right, keeping its panes."}, + {"name": "JumpScope", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "file, all", "doc": "What Back and Forward keep to: file, the focused pane's file until it runs out that way, or all, every place in order."}, + {"name": "JumpTrail", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a jump of the cursor leaves a short trail that fades, on or off."}, + {"name": "Jumplist", "leader": "SPC j l", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the places jumped from, each a place to go."}, + {"name": "Kill", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "acme's Kill: stop the commands pardes started -- the lines it typed into a terminal, from an exec, a middle click or a pty/run, while their shell says they run (C mark to D)."}, + {"name": "Last", "leader": "SPC j j", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Go back to the last place jumped from in another pane."}, + {"name": "Left", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the left."}, + {"name": "LocationsConfig", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Set how location rows are drawn, or show how they are when bare."}, + {"name": "Look", "leader": null, "also": ["enter", "right-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Look at its argument: open the file or address it names, else find the word, as a right click does."}, + {"name": "LookNext", "leader": "SPC j n", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the next Look location across panes; Enter opens it."}, + {"name": "LookPrev", "leader": "SPC j p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the previous Look location across panes; Enter opens it."}, + {"name": "LookWord", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "search, list", "doc": "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search."}, + {"name": "Lspinfo", "leader": "SPC l i", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show which language servers serve this file and their state."}, + {"name": "Lspwhy", "leader": "SPC l w", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Explain how the last language server request was answered, step by step."}, + {"name": "MessageAnimation", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A message falls into its row and dissolves out of it, on or off."}, + {"name": "MessageDissolve", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "How long, in milliseconds, a message takes to dissolve."}, + {"name": "MessageFall", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "How long, in milliseconds, a message takes to fall into its row."}, + {"name": "MessageLinger", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "How long, in milliseconds, a message stays after what dismisses it."}, + {"name": "Messages", "leader": "SPC h m", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the messages shown so far."}, + {"name": "Mini", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Open a minimap of the file in braille dots."}, + {"name": "Mode", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Cycle the pane's input modes: terminals add raw tty mode to normal/insert."}, + {"name": "More", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "A query pane's Grep stopped at its 2000 lines goes on for 2000 more."}, + {"name": "Motion", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "off, crisp, smooth, bouncy, playful", "doc": "How animations move: off, crisp, smooth, bouncy or playful."}, + {"name": "Mount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Mount another pardes's 9P tree under /n/, given its dial address."}, + {"name": "Msg", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show its argument on this pane's message row."}, + {"name": "New", "leader": "SPC f n", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Open an empty scratch pane, /+New, in this pane's directory."}, + {"name": "Newcol", "leader": "SPC c n", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "An empty column right of the keyboard's, its tag taking the keyboard."}, + {"name": "NextColor", "leader": "SPC t n", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Switch to the next bundled theme."}, + {"name": "Pager", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pardes, off", "doc": "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it."}, + {"name": "PagerColor", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A +Pager keeps its program's colours, on or off; for the next text paged."}, + {"name": "Palette", "leader": "SPC t l", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "the C64 palette or the terminal's own 16"}, + {"name": "PanelAscii", "leader": "SPC a a", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close through a scatter of ASCII, on or off."}, + {"name": "PanelCurtain", "leader": "SPC a c", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close like a curtain, on or off."}, + {"name": "PanelDissolve", "leader": "SPC a d", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes dissolve in and out as they open and close, on or off."}, + {"name": "PanelEdges", "leader": "SPC a e", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close from their edges, on or off."}, + {"name": "PanelFall", "leader": "SPC a f", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes fall into place as they open, on or off."}, + {"name": "PanelScramble", "leader": "SPC a r", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close through scrambled text, on or off."}, + {"name": "PanelSlide", "leader": "SPC a s", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes slide in and out as they open and close, on or off."}, + {"name": "PanelType", "leader": "SPC a t", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes type themselves in as they open, on or off."}, + {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, + {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, + {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, + {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, + {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, + {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."}, + {"name": "Petscii", "leader": "SPC t p", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "glyph art over the host's pixels: an image pane's picture, or the kitty graphics a terminal's program placed (yazi's previews)"}, + {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, + {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, + {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, + {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, + {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, + {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run."}, + {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, + {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, + {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, + {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, + {"name": "Shell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The shell new terminals run; bare, $SHELL if it is executable, else /bin/sh."}, + {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, + {"name": "Supertypes", "leader": "SPC l t", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the supertypes of the type under the cursor."}, + {"name": "Symbols", "leader": "SPC l s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's symbols from the language server."}, + {"name": "SyntaxBold", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Keywords and the like are drawn bold, on or off."}, + {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, + {"name": "Tagbottom", "leader": "SPC t b", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Each pane's tag goes at its foot rather than its head, on or off."}, + {"name": "Term", "leader": "SPC n t", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "A shell in the calling pane's directory, raw from the first frame."}, + {"name": "TermImages", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "real, petscii", "doc": "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art."}, + {"name": "Theme", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Switch to the named theme."}, + {"name": "ThemeFile", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Load a theme from a file."}, + {"name": "Themes", "leader": "SPC t t", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the themes in a pane, each a word to click."}, + {"name": "ThumbFlash", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a pane's scroll thumb brightens as it scrolls and fades back, on or off."}, + {"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": "TreeContextTagStyle", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A pane's TreeContext rows draw in the tag's style, 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": "Unmount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Unmount the 9P tree mounted under /n/."}, + {"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."}, + {"name": "Upgrade", "leader": "SPC s U", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Move this session onto the pardes installed since it started, in place: its text, undo, views, terminals with their running shells, and its terminals and windows come along."}, + {"name": "Verbose", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A builtin says its own name on the message row as it runs, on or off."}, + {"name": "Window", "leader": "SPC w", "also": ["C-w"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Window mode: h/j/k/l move an outline between the panes; Enter or Esc focuses the outlined pane, `:` its tag, the letter shown on a pane that one; d is Del on it (then k or j between two), c Collapse."}, + {"name": "Wrap", "leader": "SPC t w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Long lines wrap onto the next row, on or off."}, + {"name": "WsDiagnostics", "leader": "SPC l D", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the workspace's diagnostics from the language server."}, + {"name": "WsSymbols", "leader": "SPC l S", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search the workspace's symbols for its argument."}, + {"name": "Zerox", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Zerox: a second pane on this pane's file, the same text, undo and unsaved state, with a scroll and a cursor of its own (File.zerox)."} +] diff --git a/docs/typ/builtins.typ b/docs/typ/builtins.typ index 8375d5de..be069823 100644 --- a/docs/typ/builtins.typ +++ b/docs/typ/builtins.typ @@ -1,5 +1,5 @@ // Every builtin: the words you click in a tag (Exec runs them) or type as -// commands. The entries come from docs/typ/builtins-tty.json and +// commands. The entries come from docs/typ/builtins-tui.json and // builtins-gui.json, which // `zig build builtins-json` writes from the registry and the Help rows, // so this chapter and Help cannot drift. diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index a70b56e2..0e984efe 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -25,10 +25,10 @@ One button: Alt/Option-click is #btn("B2"), Cmd/Super-click #btn("B3"), sweeps t == Tags #tag("Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit") -#tag("New Tty Find Grep Joincol Delcol") -#tag("Save Tty Collapse Del", path: "/home/me/notes.txt") -#tag("Tty+bash Save Mode Filter Collapse Del", path: "/home/me/src") -#tag("Tty PdfSections PdfTint PdfFit Collapse Del", path: "manual.pdf [1/12]") +#tag("New Term Find Grep Joincol Delcol") +#tag("Save Term Collapse Del", path: "/home/me/notes.txt") +#tag("Term+bash Save Mode Filter Collapse Del", path: "/home/me/src") +#tag("Term PdfSections PdfTint PdfFit Collapse Del", path: "manual.pdf [1/12]") - #word("Del") over unsaved text refuses once; again discards. #word("Del") `j`: rows below. #key("SPC d") between two panes takes #key("k") (rows above) or #key("j") (below), asking only if you pause. - #word("Undo") #word("Redo") #word("Edit") #word("Mode") work typed anywhere. #doc("tags") @@ -91,7 +91,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla key("SPC s s"), [declarations], key("SPC f c"), word("Config"), key("SPC d"), word("Del"), - key("SPC n t"), word("Tty"), + key("SPC n t"), word("Term"), key("SPC w"), word("Window"), key("SPC j j"), word("Last"), key("SPC j l"), word("Jumplist"), @@ -111,7 +111,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla ) == Terminals and commands -- #key("Ctrl-b"): raw (`$`) or normal. #word("Mode") cycles raw, normal, insert. #word("Filter"), #word("Tty+bash"). +- #key("Ctrl-b"): raw (`$`) or normal. #word("Mode") cycles raw, normal, insert. #word("Filter"), #word("Term+bash"). - #btn("B2") on a non-builtin line runs it in a *command pane*: #tag("Kill Save Collapse Del", path: "/home/me/src (make) exit 0") - #word("Kill") `make` stops it; #word("Exit") quits. #word("Repl") `python`: `.py` clicks go to it. diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 74a0df86..d45f5cc5 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -32,7 +32,7 @@ Each pane keeps its own mode. The box left of its tag shows it. #pairs( [#mode-box(" ") normal], [keys move and select; an edit acts on the selection. File and PDF panes start here, and so does a terminal from #key("Alt-n").], [#mode-box("^") insert], [keys type. #keys("i", "a", "o") and the rest enter it.], - [#mode-box("$") raw, terminals only], [keys go to the program. A terminal from #word("Tty"), the shell a bare `pardes` starts with, and a command pane start here.], + [#mode-box("$") raw, terminals only], [keys go to the program. A terminal from #word("Term"), the shell a bare `pardes` starts with, and a command pane start here.], ) #key("Ctrl-b") switches a terminal between raw and normal. In normal, @@ -93,8 +93,8 @@ the registers. #key("SPC y") and #key("SPC p") use the system clipboard. = Tags #tag("Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit") -#tag("New Tty Find Grep Joincol Delcol") -#tag("Save Tty Collapse Del", path: "/home/me/notes.txt") +#tag("New Term Find Grep Joincol Delcol") +#tag("Save Term Collapse Del", path: "/home/me/notes.txt") A tag is text with undo. Type `make` into one and #word("Exec") it, or delete the words you never use. Any word runs from any tag: #word("Exit") @@ -227,10 +227,10 @@ do nothing. = Terminals -#tag("Tty+bash Save Mode Filter Collapse Del", path: "/home/me/src") +#tag("Term+bash Save Mode Filter Collapse Del", path: "/home/me/src") -- #word("Tty") opens a terminal in the pane's directory, #key("Alt-n") one in - the session's directory; #word("Tty+bash") picks the shell. +- #word("Term") opens a terminal in the pane's directory, #key("Alt-n") one in + the session's directory; #word("Term+bash") picks the shell. - #word("Del") closes a terminal and its shell at once, running or not, and a shell that exits closes its pane. - #word("Save") writes the scrollback to a path it asks for. diff --git a/docs/typ/install.typ b/docs/typ/install.typ index d97d30f7..7489d069 100644 --- a/docs/typ/install.typ +++ b/docs/typ/install.typ @@ -20,6 +20,6 @@ With Zig 0.17 (the build fetches everything else; once that is downloaded, a first build from a clean cache took 62 seconds on 16 cores): -#cmd("# pardes, in a terminal\nzig build -Dplatform=tty --prefix ~/.local") +#cmd("# pardes, in a terminal\nzig build -Dplatform=tui --prefix ~/.local") #cmd("# pardes-gui, its own window\nzig build -Dplatform=gui --prefix ~/.local") Then run `pardes` or `pardes FILE`. diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index b272306c..0669780a 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -39,7 +39,7 @@ tagexec a word clicked in the workspace tag @co col/ the columns @columns-and-tags / column ; rmdir closes it when empty @columns-and-tags tag its tag - ctl its builtins (Delcol Joincol New Tty) + ctl its builtins (Delcol Joincol New Term) exec a word clicked in its tag pane/ the panes @panes new open it to make a pane; read answers the serial @panes @@ -291,6 +291,7 @@ A line written to #file("exec") is #word("Exec"): `Abort`) are refused, `invalid: acme's Snarf is not a pardes builtin: ...`, never run as commands. So is a GUI-only builtin (#word("Fonts")) on another frontend. +- `Tty` is #word("Term")'s old name, run as it, `Tty+fish` too. - Anything else is a command line (a typo ends `exit 127`), at most 1024 bytes, run as the guide says (#doc("tags", section: "command-panes")): typed into a terminal idle at an empty prompt, else run in a command pane. #file("exec") reads back @@ -399,7 +400,7 @@ Writes take settings and session builtins (`scope = .session` in rows (`size: too small for the panes, each its tag and 2 rows`). A bad `size` is refused quoting the value it got (`"5 2"`). -A word that takes its argument after a `+` (#word("Tty+bash")) works on a ctl as +A word that takes its argument after a `+` (#word("Term+bash")) works on a ctl as in a tag. A write is refused whole, before anything runs, in Plan 9's words: `unknown control message "X"`, `wrong #args in control message "X"`, `bad value in control message ...`, or a word of the other ctl: `not a session control message "Undo": write it to pane//ctl`, `... "Delcol": write it to col//ctl`, `not a window control message "X": write it to /ctl`. A builtin that would open a prompt (#word("Save") on a scratch) @@ -431,7 +432,7 @@ word clicked in a tag does. The same lines go in the startup file [#word("LookWord") `search|list`], [`search`: a word given to #word("Look") selects its next place, or lists all in `+Search`], [#word("DirLook") `pane|terminal`], [`pane`: #word("Look") on a directory opens a pane listing it, as acme's directory window (#doc("reference", section: "from-acme")); `terminal` types `ls` into a terminal idle there, else opens one], [#word("JumpScope") `file|all`], [`file`: #word("Back") and #word("Forward") keep to the focused pane's file, that pane's places first, then the file's in another pane, and go to another file only when the file has no place left that way; from a terminal or a pane with no file they step through every place; `all`: every place, in the order it was jumped to], - [#word("TermImages") `real|petscii`], [`real`: a new terminal draws its program's kitty graphics (yazi's previews) as pixels where the shell can; #word("Petscii") flips one terminal; a tty under a terminal without kitty graphics draws them as glyph art either way], + [#word("TermImages") `real|petscii`], [`real`: a new terminal draws its program's kitty graphics (yazi's previews) as pixels where the shell can; #word("Petscii") flips one terminal; a tui under a terminal without kitty graphics draws them as glyph art either way], [#word("Shell") ``], [`$SHELL` when it is executable, else `/bin/sh`: the shell the next terminal and command pane run; a bare name is searched for in the usual bin directories, not `$PATH`; bare #word("Shell"): `$SHELL` if it is executable, else `/bin/sh`], [#word("DumpDir") ``], [`$XDG_DATA_HOME/pardes`, else `~/.local/share/pardes`: where #word("Dump") writes, an absolute or `~` path to a directory that may be written (made if missing); a relative one, or one under a directory that may not be written, is refused; bare returns to the default], [#word("TreeContext")], [off: sticky declaration headers in a source pane (per pane, dumped)], @@ -500,7 +501,7 @@ and leave one under its tag and two rows (`Newcol: no space for a column: the pa alone and uses up no column serial. #file("/col//ctl") takes #word("Delcol"), #word("Joincol"), -#word("New") and #word("Tty") for that column; #file("/col//exec") is +#word("New") and #word("Term") for that column; #file("/col//exec") is a click in its tag; `rmdir /col/` closes an empty column (one with panes: ENOTEMPTY). Closing a column's last pane leaves it empty (the keyboard goes to its tag, #file("focus") reads empty, the log says only @@ -534,7 +535,7 @@ tag would (#doc("fs", section: "placement")): in the active column, filling it if empty, else the bottom half of its last pane. A session holds 64 panes (`no space for a pane: 64 max`), and every pane keeps its tag and 2 rows (`no space for a pane in that column: each keeps its tag and 2 rows`); both are ENOSPC, for this open and for #word("Look"), #word("Exec"), -#word("New") or #word("Tty") alike. A #file("pane/new") whose column is +#word("New") or #word("Term") alike. A #file("pane/new") whose column is full takes its rows from a pane in another column that has them, last column first, as acme does, and is refused only when no pane anywhere can give them. `rmdir /pane/` closes the pane, unsaved or not. @@ -608,7 +609,7 @@ takes: below), #word("Save") `[path]` (bare, on a `+`-named pane that is no output, such as `+Tutor`, it asks for a path; making the directories the file goes in first, whichever name it writes), #word("Collapse"), #word("Undo")/#word("Redo") - (256 steps each), #word("Find") `pat`, #word("Edit") `...`, #word("Tty") `[shell]` (a new terminal + (256 steps each), #word("Find") `pat`, #word("Edit") `...`, #word("Term") `[shell]` (a new terminal in its directory), #word("Delcol") for its column, and #word("Left")/#word("Right")/#word("Up")/#word("Down"), which give the keyboard to the pane beside it that way, up from a column's top pane to @@ -988,7 +989,7 @@ asked, else the active column (last typed or left-clicked in, dropped into, its tag given the keyboard, or given the last new pane), never a new column. An empty column it takes whole; #word("New") and #file("pane/new") take the bottom half of the column's last pane; a pane -opened from a pane's text (#word("Look"), #word("Tty"), #key("Alt-n")) goes under +opened from a pane's text (#word("Look"), #word("Term"), #key("Alt-n")) goes under the pane with the most blank rows, or halves the biggest. #word("New") in a pane's tag names its `+New` in that pane's directory and column; from a column tag, in that column and the session's directory. A command pane @@ -1162,7 +1163,7 @@ with Client(sys.argv[1]) as c: # a socket path, or (ip, port) [`Font`, `Send`, `ID`], [#word("Font"); #word("Repl") and #word("Exec"); `$winid`], [acme's other builtins], [refused: `Sort`, `Local`, `Abort` (plan9port's debugging word)], [Edit], [every acme command but `B ` command changes nothing, where acme puts in what it wrote (#doc("fs", section: "edit"))], - [`win`], [#word("Tty") is a VT terminal pane; #file("pty/run") runs a line at its prompt and answers `exit N` and the output; with #word("Repl") bound, #word("Exec") on a source pane types the text into it], + [`win`], [#word("Term") is a VT terminal pane; #file("pty/run") runs a line at its prompt and answers `exit N` and the output; with #word("Repl") bound, #word("Exec") on a source pane types the text into it], [a directory window], [as acme's: a text pane named `dir/` (#file("index") kind `text`, #file("ctl") isdir 1), its entries in columns sorted bytewise, dotfiles shown, a directory's marked `/`; blanks pad the columns where acme's tabs do; a #word("Look") at an entry is from that directory, `Get` or a look at it again reads it again, and an edit is kept until then rather than lost to a resize; never dirty, #word("Save") refuses it; #word("DirLook") `terminal` types `ls` into a terminal there instead], [the plumber], [none: #word("Look") on an `http://` or `https://` URL runs `xdg-open` (`open` on macOS); files, addresses and directories follow built-in rules], [#key("Esc") selects what was typed], [#key("Esc") leaves insert mode, or goes back a pane (#doc("tags", section: "modes"))], diff --git a/docs/typ/style.typ b/docs/typ/style.typ index b5c2ff85..e2eafc87 100644 --- a/docs/typ/style.typ +++ b/docs/typ/style.typ @@ -186,16 +186,16 @@ /// Every builtin of either build, written by `zig build builtins-json` /// from the registry and the Help rows (src/builtins_json.zig), a file per /// build: name, leader, also (Help's other shortcuts), arg, scope, setting, -/// choices, doc. Merged here, each with `platforms`: "both", "tty" (the +/// choices, doc. Merged here, each with `platforms`: "both", "tui" (the /// terminal only) or "gui" (the window only). #let builtin-data = { - let tty = json("builtins-tty.json") + let tui = json("builtins-tui.json") let gui = json("builtins-gui.json") - let in-tty = tty.map(b => b.name) + let in-tui = tui.map(b => b.name) let in-gui = gui.map(b => b.name) - let all = (tty + gui.filter(b => b.name not in in-tty)).sorted(key: b => b.name) + let all = (tui + gui.filter(b => b.name not in in-tui)).sorted(key: b => b.name) all.map(b => { - b.insert("platforms", if b.name in in-tty and b.name in in-gui { "both" } else if b.name in in-tty { "tty" } else { "gui" }) + b.insert("platforms", if b.name in in-tui and b.name in in-gui { "both" } else if b.name in in-tui { "tui" } else { "gui" }) b }) } @@ -367,7 +367,7 @@ /// The newcomer's words, first in the glossary; every other builtin goes /// under its group below. Each must be in builtins.json. #let everyday = ("Look", "Exec", "Save", "Undo", "Redo", "New", "Newcol", "Del", "Delcol", - "Tty", "Kill", "Find", "Grep", "Recent", "Dump", "Restore", "Exit", "Help", "Tutor", "Themes", "Config") + "Term", "Kill", "Find", "Grep", "Recent", "Dump", "Restore", "Exit", "Help", "Tutor", "Themes", "Config") /// Debugging and developer words, last whatever their leader path. #let internals = ("Debug", "EffectCode", "Lspwhy", "Messages", "DumpConfig", "DumpThemes") diff --git a/docs/typ/themes.typ b/docs/typ/themes.typ index edfaa7ad..6dc92b3b 100644 --- a/docs/typ/themes.typ +++ b/docs/typ/themes.typ @@ -39,7 +39,7 @@ syntax identity but are not exact ports; their sources are in pane's and column's tags shift tone on tone rather than invert: dark palettes keep dark tags, light ones light tags. The file name in a pane's path, and `+Search` and the like, take a distinct hue at the same -brightness as the tag text; a terminal's tag tints its #word("Tty") word +brightness as the tag text; a terminal's tag tints its #word("Term") word instead. Every native palette sets its own ANSI colours, so a terminal's indexed @@ -110,7 +110,7 @@ take `null`, so older files stay valid: #pairs( [`tag_active_bg`, `tag_active_fg`], [the focused pane's tag; a ground closer than 1.25:1 to `tag_bg` is pushed further the way it leans, as far as its text keeps its contrast. Absent: `tag_bg`, `tag_fg`], - [`tag_name_fg`, `tag_active_name_fg`], [the file name's or a terminal's #word("Tty") tint, in normal and focused tags. Absent: the tag's foreground], + [`tag_name_fg`, `tag_active_name_fg`], [the file name's or a terminal's #word("Term") tint, in normal and focused tags. Absent: the tag's foreground], [`column_box`, `column_box_dim`], [a column's grip held (and its drag rail), and at rest. Absent: `num`; a mix of `column_box` and `tag_bg`], [`border`], [quiet separators, lifted to 1.6:1 when under 1.5:1 off the page. Absent: `scroll_track`], [`empty_col`], [a column with no pane, under its tag (acme: white). Absent: `border`], diff --git a/docs/ui-review.md b/docs/ui-review.md index 2d785ed8..5c15e950 100644 --- a/docs/ui-review.md +++ b/docs/ui-review.md @@ -41,7 +41,7 @@ sent to the user's session. ## Compact rails, classic palettes and workspace pets `New` now belongs to column tags only. Pane tags keep their local save, -terminal and close actions: `Tty` opens a terminal, and `Mode` +terminal and close actions: `Term` opens a terminal, and `Mode` cycles raw input, normal editing and insert mode. Historical default pane tails upgrade during Restore; explicitly customized text remains owned by the user. @@ -83,7 +83,7 @@ the native contrast tests. ## PDF and terminal tag cleanup -PDFs now use `filename.pdf [page/total] Tty Del PdfSections PdfTint PdfFit Collapse`, +PDFs now use `filename.pdf [page/total] Term Del PdfSections PdfTint PdfFit Collapse`, keeping sections and tint commands visible without the long generated control/status prefix. Terminal tags include `Mode`, which cycles the body mode even when invoked from an edited tag. Ctrl-B keeps its two-way toggle. @@ -101,10 +101,10 @@ The follow-up adds editable workspace and column command rows, compact pane tags, staged buffer-name edits, and caret reveal for long tags. See [editable tags](typ/guide.typ) for the exact interaction and save-target rules. -`test/column_tags.py` exercises isolated SDL and TTY sessions against the same +`test/column_tags.py` exercises isolated SDL and TUI sessions against the same Agave source. It sends actual host input bytes while observing through 9P: header typing and selection replacement, UTF-8 deletion, inactive-column -`New`/`Tty`, pane-tail edits, filename cancellation, terminal input, and +`New`/`Term`, pane-tail edits, filename cancellation, terminal input, and custom-tag Dump/Restore. Source bytes remain unchanged. Input goes through the host PTY parser; compact SDL pixel coordinates are covered separately by round-trip mapping tests, not claimed as physical SDL mouse automation. @@ -175,7 +175,7 @@ python3 -B test/ui_review.py zig-out/ui-review/bin/pardes-gui \ For subsequent palette captures, add `--skip-lsp`. To repeat LSP work without rebuilding dependencies, use `--cargo-target /path/to/previous/cargo-target`. Cargo runs offline and stores build output in that isolated directory. -For the TTY pass, use the TTY binary and add `--tty`. The script requires +For the TUI pass, use the TUI binary and add `--tty`. The script requires Find/Grep results and observed terminal output, fails missing or malformed SDL captures, and writes `report.json` with the actual outcomes. LSP absence or failure is recorded separately rather than passing as a successful popup. diff --git a/src/builtins.zig b/src/builtins.zig index dc50b85c..55253f02 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -23,7 +23,7 @@ pub const frontend: config.Runtime.Capabilities = .{ .scene_shaders = pardes.platform == .gui or pardes.platform == .macos, // The tty's font belongs to its emulator, and the P4 firmware's belongs to // whatever terminal is on the other end of the serial line. - .tagline_font_size = pardes.platform != .tty and pardes.platform != .esp32p4, + .tagline_font_size = pardes.platform != .tui and pardes.platform != .esp32p4, .window_opacity = pardes.platform == .gui or pardes.platform == .macos, .window_blur = pardes.platform == .macos, // Only the SDL shell shapes with HarfBuzz and honours the setting. macOS @@ -37,7 +37,7 @@ pub const frontend: config.Runtime.Capabilities = .{ /// GUI replica notes"): each has the other's words, which a view takes as /// 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 == .tty or pardes.platform == .gui; +pub const desktop = pardes.platform == .tui or pardes.platform == .gui; const window_capabilities: config.Runtime.Capabilities = .{ .font_picker = true, .panel_transitions = true, .scene_shaders = true, .tagline_font_size = true, .window_opacity = true, .window_blur = false, .ligatures = true, .lift = true }; const terminal_capabilities: config.Runtime.Capabilities = .{ .font_picker = false, .panel_transitions = true, .scene_shaders = false, .tagline_font_size = false, .window_opacity = false, .window_blur = false, .ligatures = false, .lift = false }; @@ -54,7 +54,7 @@ pub fn viewCapabilities(p: *const Pardes) config.Runtime.Capabilities { /// The live view's frontend, by name (the Settings report's platform). pub fn viewPlatform(p: *const Pardes) []const u8 { if (comptime !desktop) return @tagName(pardes.platform); - return if (p.windowed) "gui" else "tty"; + return if (p.windowed) "gui" else "tui"; } /// Where a builtin acts: at the pane it runs from, or on the editor as a @@ -225,7 +225,7 @@ pub const registry = struct { } /// Whether the word takes its argument joined by a `+` as one word a - /// tag can hold and a click take whole (`Tty+fish`). Only a builtin + /// tag can hold and a click take whole (`Term+fish`). Only a builtin /// that says `pub const plus_arg = true;`: others have arguments a `+` /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { @@ -1465,8 +1465,8 @@ pub const DelBelow = struct { /// A shell in the calling pane's directory, raw from the first frame. On every /// pane's tagline: the fast path from wherever you are to a prompt there. /// A terminal below the caller in its directory: the configured shell, or -/// the one named, `Tty fish`, as a terminal's own tag word `Tty+fish` says. -pub const Tty = struct { +/// the one named, `Term fish`, as a terminal's own tag word `Term+fish` says. +pub const Term = struct { pub const takes_arg = true; pub const plus_arg = true; pub fn run(c: Ctx) void { @@ -1478,7 +1478,7 @@ pub const Tty = struct { // The authority's lookup, taped, as Shell's (exec.zig). if (pardes.tape.value(.shell, @import("host_io.zig").Shell.refusal, .{ arg[0..@min(arg.len, 200)], &why })) |refused| { var said: [340]u8 = undefined; - return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Tty: {s}", .{refused}) catch "Tty: no such shell"); + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Term: {s}", .{refused}) catch "Term: no such shell"); } }; const pane = exec.spawnTty(c.p, c.id) orelse return; diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 3402b2ee..f5543dba 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -1,4 +1,4 @@ -//! Every builtin as JSON, for the docs' glossary (docs/typ/builtins-tty.json +//! Every builtin as JSON, for the docs' glossary (docs/typ/builtins-tui.json //! and builtins-gui.json, a build's list each; style.typ merges them): //! the rows the `Help` builtin draws (pardes.builtin_rows: the leader path //! and the other shortcuts) with what /commands says of each word (its doc @@ -24,7 +24,7 @@ pub fn write(w: *std.Io.Writer) !void { var len: usize = 0; // This build's own frontend's words (a desktop build has the other's // too, which a view of its kind takes: builtins.zig `here`). - for (pardes.builtin_rows, 0..) |row, i| if (pardes.builtins.registry.hereFor(row.cmd, pardes.builtins.frontend, pardes.platform != .tty)) { + for (pardes.builtin_rows, 0..) |row, i| if (pardes.builtins.registry.hereFor(row.cmd, pardes.builtins.frontend, pardes.platform != .tui)) { all[len] = .{ .name = @tagName(row.cmd), .row = i }; len += 1; }; @@ -77,7 +77,7 @@ test "docs/typ/builtins-.json is what the registry says now" { // Linux builds' lists if (comptime @import("builtin").os.tag != .linux) return error.SkipZigTest; const file = switch (pardes.platform) { - .tty => "builtins-tty.json", + .tui => "builtins-tui.json", .gui => "builtins-gui.json", else => return error.SkipZigTest, }; diff --git a/src/colors.zig b/src/colors.zig index cc417ccb..141e0b0e 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -331,7 +331,7 @@ pub const Theme = struct { // editor palettes keep working; ChromeTheme resolves their legacy defaults. tag_active_bg: ?[3]u8 = null, tag_active_fg: ?[3]u8 = null, - /// Filename/output-name accent, also used by the Tty command. + /// Filename/output-name accent, also used by the Term command. tag_name_fg: ?[3]u8 = null, /// Active tint; absence preserves the shared name tint or active tag ink. tag_active_name_fg: ?[3]u8 = null, diff --git a/src/config.zig b/src/config.zig index 603e51f2..4f2802cc 100644 --- a/src/config.zig +++ b/src/config.zig @@ -100,7 +100,7 @@ pub const leader_path = paths: { .ClipReplace = "R", .Save = "fs", .New = "fn", - .Tty = "nt", + .Term = "nt", .Find = "ff", .Recent = "fr", .Grep = "fg", @@ -341,23 +341,23 @@ pub const child_term_program = "pardes"; pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit"; -pub const pane_builtins_str = "Tty Collapse Del"; -pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint PdfFit Collapse Del"; -pub const file_pane_builtins_str = "Save Tty Collapse Del"; +pub const pane_builtins_str = "Term Collapse Del"; +pub const pdf_pane_builtins_str = "Term PdfSections PdfTint PdfFit Collapse Del"; +pub const file_pane_builtins_str = "Save Term Collapse Del"; /// After a file's, on one a language server speaks for. pub const lsp_pane_builtins_str = "Def Refs"; /// A diff's (a .diff, a .patch, a +Pager holding one): Diff. -pub const diff_pane_builtins_str = "Save Tty Diff Collapse Del"; +pub const diff_pane_builtins_str = "Save Term Diff Collapse Del"; /// A +Pager's (`pardes -`): Filter, as a terminal's. -pub const pager_pane_builtins_str = "Save Tty Filter Collapse Del"; +pub const pager_pane_builtins_str = "Save Term Filter Collapse Del"; /// A +Pager holding a diff (`git show`): Diff too. -pub const pager_diff_pane_builtins_str = "Save Tty Filter Diff Collapse Del"; +pub const pager_diff_pane_builtins_str = "Save Term Filter Diff Collapse Del"; /// A +Diff's: Diff again, the diff it stacks as text. -pub const diff_view_builtins_str = "Save Tty Diff Collapse Del"; -pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; +pub const diff_view_builtins_str = "Save Term Diff Collapse Del"; +pub const terminal_pane_builtins_str = "Term Save Mode Filter Collapse Del"; pub const command_pane_builtins_str = "Kill Save Collapse Del"; /// A directory pane's (Dir.zig): Get reads it again, as acme's does. -pub const dir_pane_builtins_str = "Get Tty Collapse Del"; +pub const dir_pane_builtins_str = "Get Term Collapse Del"; // Each mode badge is one codepoint. pub const tag_normal = " "; @@ -1965,7 +1965,7 @@ pub const Runtime = struct { var defaults: Runtime = .{}; var defaults_context = context; defaults_context.startup_config_path = null; - defaults_context.platform = "tty"; + defaults_context.platform = "tui"; defaults_context.hover_delay_frames = null; defaults_context.native_images = false; defaults_context.capabilities = .{ @@ -2316,7 +2316,7 @@ test "docs/typ names only words, keys and default tags that exist" { var found: [3]std.ArrayList([]const u8) = @splat(.empty); // The arena's: gone with this test, so no later test reads it. defer doc_typ.other_build = ""; - for ([_][]const u8{ "builtins-tty.json", "builtins-gui.json" }) |f| { + for ([_][]const u8{ "builtins-tui.json", "builtins-gui.json" }) |f| { const text = dir.readFileAlloc(io, f, gpa, .limited(1 << 20)) catch continue; doc_typ.other_build = try std.mem.concat(gpa, u8, &.{ doc_typ.other_build, text }); } diff --git a/src/crash.zig b/src/crash.zig index a432fb87..054feda3 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -1,7 +1,7 @@ //! The crash file: what a panic leaves behind for the human who has to report it. //! //! stderr is where a panic has always gone, and stderr is the worst place this -//! program has. In the tty shell stderr IS the screen — the trace lands on the +//! program has. In the tui shell stderr IS the screen — the trace lands on the //! grid the terminal is being reset out of, and the next redraw or the next //! `clear` takes it with it. The GUI and the AppKit shells have no terminal at //! all, so it goes to a console nobody has open. A detached session's goes diff --git a/src/daemon.zig b/src/daemon.zig index 2a70c772..eb2b7eed 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -375,7 +375,7 @@ pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detache } pub const Note = union(enum) { - /// A terminal for a detached tty session (`pardes --attach`), and the + /// A terminal for a detached tui session (`pardes --attach`), and the /// stub's pipe; for a window session, both -1: open a window. attach: struct { tty: c_int, stub: c_int }, adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize }, diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 337211b7..f73dee13 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -28,7 +28,7 @@ pub const version: u16 = 19; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { - .tty, .gui => "desktop", + .tui, .gui => "desktop", else => @tagName(config.platform), }; @@ -269,7 +269,7 @@ pub fn helloVersion(payload: []const u8) Error!u16 { } /// Frontend -> core, decoded. The `Event`'s slices BORROW the payload buffer, -/// exactly like the pty chunks the tty host hands to `update`: valid for that +/// exactly like the pty chunks the tui host hands to `update`: valid for that /// one call and no longer. pub const ClientMsg = union(enum) { hello: Hello, diff --git a/src/draw.zig b/src/draw.zig index 8503197c..4f238942 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -1057,7 +1057,7 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { // `tag` is the first row; a prefix longer than it ran to a second. var words = std.mem.tokenizeAny(u8, tag[@min(prefix_len, tag.len)..], " \t\r\n"); while (words.next()) |word| { - if (!std.mem.eql(u8, word, "Tty") and !std.mem.startsWith(u8, word, "Tty+")) continue; + if (!std.mem.eql(u8, word, "Term") and !std.mem.startsWith(u8, word, "Term+")) continue; const lo = @intFromPtr(word.ptr) - @intFromPtr(tag.ptr); return .{ .lo = lo, .hi = lo + word.len }; } @@ -1513,12 +1513,12 @@ test "a grip's four states, focused or not and clean or dirty, are each its own pane.file.?.revision = pane.file.?.saved_revision; } -test "every theme draws a file's name, a +Errors and a Tty word in a tint, never the tag's plain ink" { +test "every theme draws a file's name, a +Errors and a Term word in a tint, never the tag's plain ink" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 120, .rows = 40, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("text\n"); - try std.testing.expect(p.executeBuiltinLine(0, "Tty+sh")); + try std.testing.expect(p.executeBuiltinLine(0, "Term+sh")); const terminal = p.active; p.acknowledgeShell(terminal, "/bin/sh", false); try @import("Output.zig").openErrors(p, 0, try gpa.dupe(u8, "oops\n")); @@ -1529,7 +1529,7 @@ test "every theme draws a file's name, a +Errors and a Tty word in a tint, never if (pane.file) |f| if (std.mem.endsWith(u8, f.path, "+Errors")) break id; } else return error.NoErrorsPane; const Probe = struct { id: usize, word: []const u8 }; - const probes = [_]Probe{ .{ .id = 0, .word = "test.txt" }, .{ .id = terminal, .word = "Tty+sh" }, .{ .id = errors, .word = "+Errors" } }; + const probes = [_]Probe{ .{ .id = 0, .word = "test.txt" }, .{ .id = terminal, .word = "Term+sh" }, .{ .id = errors, .word = "+Errors" } }; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); for (pardes.themes, 0..) |theme, index| { diff --git a/src/dump.zig b/src/dump.zig index 5f5f5870..9ceaa600 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -403,7 +403,7 @@ fn loadAndRevive(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, previ }; try reviveSession(p, previous, kept != null); // What another build's dump could not give, said where the user looks - // (stderr is a tty session's screen). + // (stderr is a tui session's screen). if (notes.items.len > 0) { const first = notes.items[0 .. std.mem.indexOfScalar(u8, notes.items, '\n') orelse notes.items.len]; var buf: [320]u8 = undefined; diff --git a/src/effect_sources.zig b/src/effect_sources.zig index f45bf293..36d62774 100644 --- a/src/effect_sources.zig +++ b/src/effect_sources.zig @@ -21,8 +21,8 @@ pub const Backend = @TypeOf(build_config.platform); pub const backend: Backend = build_config.platform; pub const files = switch (backend) { - .tty => [_]filesystem.Source{ - .{ .path = "src/tty/panel_compositor.zig", .contents = @embedFile("tty/panel_compositor.zig") }, + .tui => [_]filesystem.Source{ + .{ .path = "src/tui/panel_compositor.zig", .contents = @embedFile("tui/panel_compositor.zig") }, }, .gui => [_]filesystem.Source{ .{ .path = "src/gui/gui.zig", .contents = @embedFile("gui/gui.zig") }, @@ -50,7 +50,7 @@ pub const files = switch (backend) { pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { return switch (setting.action) { .transition => switch (backend) { - .tty => &.{ "src/layout.zig", "src/pardes.zig", "src/tty/panel_compositor.zig" }, + .tui => &.{ "src/layout.zig", "src/pardes.zig", "src/tui/panel_compositor.zig" }, .gui => &.{ "src/layout.zig", "src/pardes.zig", "src/gui/gui.zig", ui_vertex_path, ui_fragment_path, image_vertex_path, image_fragment_path }, .macos => &.{ "src/layout.zig", "src/pardes.zig", "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, .web, .esp32p4 => null, @@ -63,7 +63,7 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { .grain => &.{ "src/gui/Post.zig", "src/gui/gui.zig", post_vertex_path, post_grain_path }, }, .macos => &.{ "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, - .tty, .web, .esp32p4 => null, + .tui, .web, .esp32p4 => null, }, else => null, }; @@ -73,7 +73,7 @@ test "EffectCode paths resolve uniquely to this backend's archived inputs" { if (!@import("memory.zig").limits.embedded_sources) return error.SkipZigTest; for (config.Runtime.settings) |setting| { const available = switch (setting.action) { - .transition => backend == .tty or backend == .gui or backend == .macos, + .transition => backend == .tui or backend == .gui or backend == .macos, .scene => backend == .gui or backend == .macos, else => false, }; @@ -94,7 +94,7 @@ test "EffectCode paths resolve uniquely to this backend's archived inputs" { }; try std.testing.expectEqual(@as(usize, 1), matches); } - try std.testing.expectEqual(backend == .tty, filesystem.sourceBytes("src/tty/panel_compositor.zig") != null); + try std.testing.expectEqual(backend == .tui, filesystem.sourceBytes("src/tui/panel_compositor.zig") != null); try std.testing.expectEqual(backend == .gui, filesystem.sourceBytes("src/gui/gui.zig") != null); try std.testing.expectEqual(backend == .macos, filesystem.sourceBytes("src/macos/Sources/PardesView.swift") != null); } diff --git a/src/esp32p4.zig b/src/esp32p4.zig index 683d19e1..074ca6b3 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -386,8 +386,8 @@ fn drainInput(c: *pardes.Pardes, force: bool) void { } else esc_held_at = null; } -/// One parsed vaxis event applied to the core. Mirrors the tty shell's `apply` -/// (`src/tty/tty.zig:926-985`), minus everything that needs an OS. +/// One parsed vaxis event applied to the core. Mirrors the tui shell's `apply` +/// (`src/tui/tui.zig:926-985`), minus everything that needs an OS. fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { switch (ev) { .key_press => |key| if (in_paste) { @@ -466,7 +466,7 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { } }, // The only way this platform learns its size, and the one place a 384 KiB heap shows through - // to the user. Two things happen here that the tty shell does not need. + // to the user. Two things happen here that the tui shell does not need. // // CLAMPED, because the grids do not fit an arbitrary terminal: vaxis keeps a `Screen` and an // `InternalScreen`, pardes keeps its own `Surface` and `previous_cells`, so every cell is @@ -595,9 +595,9 @@ fn gpioToggle(_: ?*anyopaque, pin: u16, was: *u8, now: *u8) bool { return f(out_ctx, pin, was, now); } -/// The canonical surface -> the wire. Same shape as the tty shell's (`src/tty/tty.zig:1096`) minus +/// The canonical surface -> the wire. Same shape as the tui shell's (`src/tui/tui.zig:1096`) minus /// the panel compositor and the kitty image path: neither has a reason to exist on a board with no -/// pixels. Where the tty shell hands every cell to vaxis and lets it diff, this diffs against the +/// pixels. Where the tui shell hands every cell to vaxis and lets it diff, this diffs against the /// Surface itself and can then emit the ANSI directly - see `direct_emit`. fn present(_: ?*anyopaque, surface: *const pardes.Surface) void { const t0 = cycles(); diff --git a/src/exec.zig b/src/exec.zig index ad051c32..a1894b7f 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -398,7 +398,7 @@ fn askWrite(p: *Pardes, id: usize, serial: u32, path: []const u8) void { } }); } -/// Tty: a shell in the caller's directory, raw from the first frame, +/// Term: a shell in the caller's directory, raw from the first frame, /// stacked below the caller like Alt-n's new shell. pub fn spawnTty(p: *Pardes, from: usize) ?*Pane { // No pane asking (an empty window's tag): the session's directory, as @@ -409,26 +409,26 @@ pub fn spawnTty(p: *Pardes, from: usize) ?*Pane { const dir = p.execDir(from); if (missingDir(p, dir)) { var said: [pardes.memory.limits.host_path_cap + 48]u8 = undefined; - p.reportFailure(from, std.fmt.bufPrint(&said, "Tty: {s}: no such directory", .{dir}) catch "Tty: no such directory"); + p.reportFailure(from, std.fmt.bufPrint(&said, "Term: {s}: no such directory", .{dir}) catch "Term: no such directory"); return null; } const free = p.freeSlot() orelse { - p.reportError(from, "Tty", error.NoPaneSlots); + p.reportError(from, "Term", error.NoPaneSlots); return null; }; const nt = p.newShell(free, dir) catch |err| { if (err == error.PathTooLong) { - p.reportFailure(from, std.fmt.comptimePrint("Tty: its directory is longer than a path may be ({d} bytes)", .{pardes.memory.limits.host_path_cap})); + p.reportFailure(from, std.fmt.comptimePrint("Term: its directory is longer than a path may be ({d} bytes)", .{pardes.memory.limits.host_path_cap})); return null; } - p.reportError(from, "Tty", err); + p.reportError(from, "Term", err); return null; }; nt.greet = true; nt.body.mode = .tty; placeNew(p, from, from, free, .shell); if (refusedPlacement(p, free)) { - p.reportError(from, "Tty", error.NoPaneRoom); + p.reportError(from, "Term", error.NoPaneRoom); return null; } return nt; @@ -786,7 +786,7 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // its own to reuse. const src = p.panes[from]; const dir = p.execDir(from); - // A directory that is not there runs nothing, as Tty makes nothing + // A directory that is not there runs nothing, as Term makes nothing // there: no pane, and the write fails ENOENT. if (missingDir(p, dir)) { var said: [pardes.memory.limits.host_path_cap + 48]u8 = undefined; @@ -931,9 +931,11 @@ pub fn namesBuiltin(txt: []const u8) bool { /// acme's words, run by their pardes names (Put is Save; Delete is a Del /// that does not ask), or refused, never run as a shell command: a Put that -/// exited 127 looked like a save that worked. +/// exited 127 looked like a save that worked. Tty, Term's old name, as +/// saved dumps and users' tags still hold it, is here too. pub const acme_words = [_]struct { acme: []const u8, pardes: ?[]const u8, hint: []const u8 = "" }{ .{ .acme = "Put", .pardes = "Save" }, + .{ .acme = "Tty", .pardes = "Term" }, .{ .acme = "Delete", .pardes = "Del" }, .{ .acme = "Snarf", .pardes = null, .hint = ": y yanks the selection" }, .{ .acme = "Cut", .pardes = null, .hint = ": d deletes the selection into a register" }, @@ -951,7 +953,8 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { const raw = commandText(txt); if (raw.len == 0 or p.exec_depth >= max_exec_depth) return false; if (isComment(raw)) return true; - const word_end = std.mem.indexOfAny(u8, raw, " \t") orelse raw.len; + // `+` too, so an old `Tty+fish` is renamed as `Tty fish` is. + const word_end = std.mem.indexOfAny(u8, raw, " \t+") orelse raw.len; var renamed: [1024 + 16]u8 = undefined; const cmd = for (acme_words) |w| { if (!std.mem.eql(u8, raw[0..word_end], w.acme)) continue; @@ -966,7 +969,7 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { }; break std.fmt.bufPrint(&renamed, "{s}{s}", .{ now, raw[word_end..] }) catch raw; } else raw; - // `Word arg`, or for a word that says so, `Word+arg` (`Tty+fish`). + // `Word arg`, or for a word that says so, `Word+arg` (`Term+fish`). const plus = std.mem.indexOfScalar(u8, cmd, '+'); var sp = std.mem.indexOfAny(u8, cmd, " \t"); if (sp == null) if (plus) |at| if (std.meta.stringToEnum(Builtin, cmd[0..at])) |head| { @@ -1378,7 +1381,7 @@ fn pardesDoc(p: *Pardes, from_id: usize, free: usize) void { layout.columnFitsHalves(p, from_id, 100) and layout.splitColumn(p, from_id, free, true)) return; // Without room for a first-document column, split the Look origin - // just like Tty. Never displace (or evict) a top-left bystander. + // just like Term. Never displace (or evict) a top-left bystander. belowParent(p, src_id orelse from_id, free); } diff --git a/src/file_watch.zig b/src/file_watch.zig index f640fa5f..89d0fdaf 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -100,7 +100,7 @@ const wake_ident: usize = std.math.maxInt(usize); /// `polled` is the only flag that survives the port. On linux it adds /// IN_NONBLOCK, because a host that finds this descriptor ready in its own /// `poll(2)` must be able to stop draining it, while a -/// host that parks a thread in `wait` (tty.zig, gui.zig) wants the blocking +/// host that parks a thread in `wait` (tui.zig, gui.zig) wants the blocking /// read. On macos neither host needs either flag: a kqueue is not inherited /// across `fork(2)`, so there is no CLOEXEC to ask for, and whether a wait /// blocks is the timeout argument to `kevent(2)` rather than a property of the @@ -143,11 +143,11 @@ pub fn init(polled: bool) c_int { /// /// macos only, because it exists for the one thing a kqueue cannot do the way /// an inotify descriptor can — be read. The linux hosts keep reading theirs -/// (tty.zig through `std.Io.File`, so teardown's `cancel` interrupts it), and +/// (tui.zig through `std.Io.File`, so teardown's `cancel` interrupts it), and /// this is the shape that replaces that where there is nothing to read. /// /// Deliberately does NOT report WHAT changed, for the reason the watcher -/// threads in tty.zig and gui.zig already give: the loop re-reads every marked +/// threads in tui.zig and gui.zig already give: the loop re-reads every marked /// pane anyway. pub fn wait(fd: c_int) bool { if (comptime builtin.os.tag != .macos) return false; diff --git a/src/fonts.zig b/src/fonts.zig index 88cde63a..c4f96bad 100644 --- a/src/fonts.zig +++ b/src/fonts.zig @@ -7,7 +7,7 @@ //! //! It lives at src/ rather than under gui/ because two shells now draw their //! own text: builtins.zig imports it behind `platform == .gui or .macos`, so -//! the tty binary compiles not one line of this and never opens a font +//! the tui binary compiles not one line of this and never opens a font //! directory, and the browser (which has no font directories to open) is out //! for a better reason than taste. //! diff --git a/src/fs.zig b/src/fs.zig index 733418da..2c54f3df 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1098,7 +1098,7 @@ fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source { } pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { - .tty, .gui, .macos => true, + .tui, .gui, .macos => true, .web, .esp32p4 => false, }; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 50baf9ec..15347eb6 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2672,7 +2672,7 @@ const Client = struct { } /// Its own view drawn in the window, outside any step, as the tty's - /// client draws its terminal (tty.zig `Remote.draw`): what presenting + /// client draws its terminal (tui.zig `Remote.draw`): what presenting /// writes in the core (a frame skipped, one owed) is put back. fn draw(cl: *Client, s: *Shell) void { const r = cl.link.r; @@ -4205,10 +4205,10 @@ const Shell = struct { windowed: u8 = 1, /// This wait took only a replica's post (its input, its join): the pump /// after it reads no new time, so it moves nothing the replicas' - /// speculations stand on (tty.zig's `mail_only`). + /// speculations stand on (tui.zig's `mail_only`). mail_only: bool = false, waited: bool = false, - /// With replica clients, a wait takes one person's input (tty.zig + /// With replica clients, a wait takes one person's input (tui.zig /// `split`): the next is held for the next wait. took_input: bool = false, held: ?c.SDL_Event = null, @@ -4399,7 +4399,7 @@ const Shell = struct { } /// With replica clients, a wait takes one person's input and its pump - /// makes one unit of it (tty.zig `split`): whether `sev`, a second, is + /// makes one unit of it (tui.zig `split`): whether `sev`, a second, is /// held for the next wait. Any event but a wake is no replica's post. fn split(s: *Shell, sev: *const c.SDL_Event) bool { if (sev.type != c.SDL_EVENT_USER) s.mail_only = false; @@ -4574,7 +4574,7 @@ const Shell = struct { } /// One shell of a dead session (`pid` 0: the last of them was told): - /// a terminal pane made for it, as the Tty word makes one, whose spawn + /// a terminal pane made for it, as the Term word makes one, whose spawn /// takes this pty (spawnPane). fn adoptShell(s: *Shell, pid: libc.pid_t, fd: c_int) void { const core = s.core; diff --git a/src/host_io.zig b/src/host_io.zig index 3b91ea7e..5cdf6e0d 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1456,7 +1456,7 @@ pub const Shell = struct { return true; } - /// Why `bin` is no shell, for the words that name one (Tty, Shell); + /// Why `bin` is no shell, for the words that name one (Term, Shell); /// null when it is one. pub fn refusal(bin: []const u8, said: []u8) ?[]const u8 { var buf: [std.fs.max_path_bytes]u8 = undefined; @@ -2003,7 +2003,7 @@ pub fn forkShell( }; var master: c_int = -1; var path_buf: [std.fs.max_path_bytes]u8 = undefined; - // A terminal opened on a shell of its own (`Tty fish`) runs that one, + // A terminal opened on a shell of its own (`Term fish`) runs that one, // copied: looking it up gives the turn up, and the pane may go. var own_buf: [256]u8 = undefined; var own: ?[]const u8 = null; @@ -2225,7 +2225,7 @@ pub fn marksPrompts(pid: libc.pid_t) bool { } /// The program `pid` runs, where the system says (an adopted shell's, for -/// its pane's Tty word); null elsewhere. +/// its pane's Term word); null elsewhere. pub fn processExe(pid: libc.pid_t, buf: []u8) ?[]const u8 { if (comptime builtin.os.tag == .freebsd) { const n = kernProc(pid, 12, buf) orelse return null; // KERN_PROC_PATHNAME diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 5baf7129..cc92e00e 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -1546,7 +1546,7 @@ fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Re } if (pid == 0) { // Between fork and exec, in a process with threads: only async- - // signal-safe calls, no allocation, no locks. (Same rule as tty.zig's + // signal-safe calls, no allocation, no locks. (Same rule as tui.zig's // forkShell.) _ = libc.setsid(); // Ctrl-C in pardes's terminal is not the server's business @import("../host_io.zig").resetChildSignals(); diff --git a/src/main.zig b/src/main.zig index a07991f5..16675265 100644 --- a/src/main.zig +++ b/src/main.zig @@ -76,7 +76,8 @@ const help_text = \\terminal's PAGER), else a new editor's. \\ \\Options: - \\ --tty start as one shell pane already in tty mode + \\ --tui start as one shell pane already in tty mode + \\ (--tty, its old spelling, too) \\ -n initial shell panes: 1 (default) or 3 (classic). \\ A FILE argument boots just that file instead. \\ --tty-toggle use Ctrl- to toggle tty/editor mode @@ -395,7 +396,7 @@ fn webMain() !void { try @import("gui/gui.zig").run(.{}, .{}, false); } -// init.gpa, what the tty, gui and detached shells allocate from, is their +// init.gpa, what the tui, gui and detached shells allocate from, is their // own fixed arena (memory.host) in a release build, spilling to libc's // malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start // gives a safe build a SafeAllocator over the page allocator instead. @@ -420,7 +421,7 @@ fn nativeMain(std_init: std.process.Init) !void { // An upgraded session's new process (upgrade.zig): its record, then the // arguments it was started with, which configure it as before; its // file, stdin, directory and daemon come from the record instead. - const upgraded = comptime upgrade.supported and (pardes.platform == .tty or pardes.platform == .gui); + const upgraded = comptime upgrade.supported and (pardes.platform == .tui or pardes.platform == .gui); if (upgraded) if (args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.flag)) { upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{}); }; @@ -435,7 +436,7 @@ fn nativeMain(std_init: std.process.Init) !void { var i: usize = if (resuming) 2 else 1; while (i < args.len) : (i += 1) { const a = args[i]; - if (std.mem.eql(u8, a, "--tty")) { + if (std.mem.eql(u8, a, "--tui") or std.mem.eql(u8, a, "--tty")) { explicit_tty = true; } else if (std.mem.startsWith(u8, a, "--tty-toggle=")) { session_only = false; @@ -831,7 +832,7 @@ fn nativeMain(std_init: std.process.Init) !void { opts.rows = 50; } const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty; - var term: @import("tty/tty.zig").Term = if (detach != null) .none else .open; + var term: @import("tui/tui.zig").Term = if (detach != null) .none else .open; var headless = detach != null; upgrade.remember(args); if (upgrade.resumed) |*rec| { @@ -847,7 +848,7 @@ fn nativeMain(std_init: std.process.Init) !void { } else if (daemon.wanted()) { if (detach != null or pardes.platform == .gui) { _ = daemon.register(null, kind, opts.ninep_name, detach != null); - } else if (pardes.platform == .tty) fork: { + } else if (pardes.platform == .tui) fork: { // A terminal's session is forked off its stub, which stays the // job the shell waits on: Detach (or the terminal's end) ends // the job and leaves the session running (daemon.forkSession). @@ -877,7 +878,7 @@ fn nativeMain(std_init: std.process.Init) !void { defer daemon.quit(); errdefer daemon.tellStubExit(1); switch (pardes.platform) { - .tty => @import("tty/tty.zig").run(init, opts, term) catch |err| switch (err) { + .tui => @import("tui/tui.zig").run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not // an error trace. error.NoDevice => { @@ -992,23 +993,23 @@ fn commOf(pid: []const u8, buf: *[64]u8) []const u8 { return std.mem.trimEnd(u8, buf[0..@intCast(got)], "\n"); } -/// The replica client of this build's frontend: a terminal's (tty.zig) or a +/// The replica client of this build's frontend: a terminal's (tui.zig) or a /// window's (gui.zig). fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void { switch (pardes.platform) { - .tty => try @import("tty/tty.zig").remote(init, opts, path, name, far), + .tui => try @import("tui/tui.zig").remote(init, opts, path, name, far), .gui => try @import("gui/gui.zig").remote(init, opts, path, name, far), else => unreachable, } } /// `pardes --attach=:` (`pardes-gui` too): a replica client -/// (tty.zig and gui.zig `remote`), through the socket `where` names, or +/// (tui.zig and gui.zig `remote`), through the socket `where` names, or /// through `ssh -L` of host `where`'s replica socket to one of this /// process's. fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, name: []const u8) noreturn { const io = init.io; - if (comptime pardes.platform != .tty and pardes.platform != .gui) unreachable; + if (comptime pardes.platform != .tui and pardes.platform != .gui) unreachable; const Say = struct { fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { var buf: [700]u8 = undefined; @@ -1189,9 +1190,9 @@ test { _ = @import("file_watch.zig"); _ = @import("lsp/lsp_client.zig"); _ = @import("lsp/lsp.zig"); - if (comptime pardes.platform == .tty) { - _ = @import("tty/tty.zig"); - _ = @import("tty/panel_compositor.zig"); + if (comptime pardes.platform == .tui) { + _ = @import("tui/tui.zig"); + _ = @import("tui/panel_compositor.zig"); } if (comptime pardes.platform == .gui) _ = @import("gui/gui.zig"); if (comptime pardes.font_picker) _ = @import("fonts.zig"); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index 6f5bee23..0ee25345 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -150,7 +150,7 @@ pub fn released(p: *Pardes, serial: ?u32) void { } /// A column's ctl: the words that act on a column, as its tag's clicks do -- -/// Delcol, Joincol, New, Tty -- one a line, each run as from that tag. What +/// Delcol, Joincol, New, Term -- one a line, each run as from that tag. What /// they say is the session's in the log (`msg -`), not the focused pane's. pub fn writeCtl(p: *Pardes, req: Req, serial: u32) Reply { // What this write touched, alone, reads back (runBuiltin notes it). @@ -162,14 +162,14 @@ pub fn writeCtl(p: *Pardes, req: Req, serial: u32) Reply { const line = std.mem.trim(u8, raw, " \t\r"); if (line.len == 0 or pardes.exec.isComment(line)) continue; const word = line[0 .. std.mem.indexOfAny(u8, line, " \t") orelse line.len]; - const takes = for ([_][]const u8{ "Delcol", "Joincol", "New", "Tty" }) |w| { + const takes = for ([_][]const u8{ "Delcol", "Joincol", "New", "Term" }) |w| { if (std.mem.eql(u8, w, word)) break true; } else false; // Plan 9's words for it, so a mount's errno is EINVAL as the root's // and a pane's ctl give (9ns reads "control message"). - if (!takes) return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "unknown control message \"{s}\": a column's ctl takes Delcol, Joincol, New or Tty", .{pardes.ctlfs.ctl.firstWord(line)[0..@min(pardes.ctlfs.ctl.firstWord(line).len, 64)]}) catch "unknown control message"); - // Only Tty takes a word (its shell); `New extra` is no New. - if (!std.mem.eql(u8, word, "Tty") and word.len != line.len) + if (!takes) return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "unknown control message \"{s}\": a column's ctl takes Delcol, Joincol, New or Term", .{pardes.ctlfs.ctl.firstWord(line)[0..@min(pardes.ctlfs.ctl.firstWord(line).len, 64)]}) catch "unknown control message"); + // Only Term takes a word (its shell); `New extra` is no New. + if (!std.mem.eql(u8, word, "Term") and word.len != line.len) return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "wrong #args in control message \"{s}\"", .{pardes.ctlfs.ctl.firstWord(line)[0..@min(pardes.ctlfs.ctl.firstWord(line).len, 64)]}) catch "wrong #args in control message"); const col = layout.columnBySerial(p, serial) orelse return Reply.fail(req.tag, E.NOENT); p.exec_column = col; @@ -197,7 +197,7 @@ pub fn writeExec(p: *Pardes, req: Req, serial: ?u32) Reply { if (pardes.ctlfs.ctl.tooLong(req, line)) |refusal| return refusal; // A pane's word (Undo, Msg, Save) is no word of a tag no pane owns: // refused as the root's ctl refuses it, never done at whichever - // pane has the keyboard. The tag's own words (New, Tty, Find, Grep + // pane has the keyboard. The tag's own words (New, Term, Find, Grep // in a column's) are its to run. if (paneWord(line, if (serial == null) pardes.config.topbar_str else tagline.column_tag_default)) return pardes.ctlfs.ctl.refuseTo(p, req, "not a session control message", line, "pane//ctl"); @@ -380,7 +380,7 @@ fn paneWord(line: []const u8, own: []const u8) bool { const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), word) orelse return false; if (pardes.builtins.registry.scope(b) == .session) return false; // A new pane is every tag's to make, in the session's directory. - if (b == .New or b == .Tty) return false; + if (b == .New or b == .Term) return false; var words = std.mem.tokenizeScalar(u8, own, ' '); while (words.next()) |w| if (std.mem.eql(u8, w, word)) return false; return true; @@ -440,18 +440,18 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se } } -test "New and Tty run at /tagexec and a column's exec, with no pane at all too" { +test "New and Term run at /tagexec and a column's exec, with no pane at all too" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const tagexec = @backingInt(tree.TopFile.tagexec); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ tagexec, col_exec }) |node| for ([_][]const u8{ "New\n", "Tty\n" }) |line| { + for ([_]u64{ tagexec, col_exec }) |node| for ([_][]const u8{ "New\n", "Term\n" }) |line| { const before = p.next_serial; try testing.expectEqual(tree.Status.ok, th.wr(p, node, line).reply.status); try testing.expectEqual(before + 1, p.next_serial); }; // Every pane gone: the workspace tag makes one all the same. - for ([_][]const u8{ "New\n", "Tty\n" }) |line| { + for ([_][]const u8{ "New\n", "Term\n" }) |line| { while (p.ncol > 0) { const first = p.panes[p.col_panes[0][0]].?.serial; _ = th.wr(p, tree.Node.of(first, .ctl), "delete\n"); @@ -475,7 +475,7 @@ test "every pane word a tag no pane owns does not hold is refused there, Edit in var checked: usize = 0; for (std.enums.values(Builtin)) |b| { if (pardes.builtins.registry.scope(b) == .session) continue; - if (b == .New or b == .Tty) continue; // every tag's + if (b == .New or b == .Term) continue; // every tag's var owned = false; var words = std.mem.tokenizeScalar(u8, tag_file.own, ' '); while (words.next()) |w| owned = owned or std.mem.eql(u8, w, @tagName(b)); @@ -548,7 +548,7 @@ test "a column's tag and the workspace's read, replace and append as a pane tag try testing.expectEqual(E.NOENT, th.look_up(p, col_dir, "777").errno()); const tag = Node.ofCol(serial, .tag); try testing.expectEqual(tree.Status.ok, th.look_up(p, Node.ofCol(serial, .dir), "tag").reply.status); - try testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", th.rd(p, tag, 0, 4096).bytes); + try testing.expectEqualStrings("New Term Find Grep Joincol Delcol", th.rd(p, tag, 0, 4096).bytes); // `echo Make > tag`: cleared, then the newline ending the write dropped. _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); _ = th.wr(p, tag, "Make\n"); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 89549933..4749fc94 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -515,9 +515,15 @@ fn blanked(line: []const u8, buf: []u8) []const u8 { /// as on a tag; acme's lowercase verbs are the pane ctl's and alias none. fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ?Reply { var sp = std.mem.indexOfAny(u8, line, " \t"); - // `Word+arg` for a word that takes one so (`Tty+bash`), as exec does. - if (sp == null) if (std.mem.indexOfScalar(u8, line, '+')) |at| if (std.meta.stringToEnum(Builtin, line[0..at])) |head| { - if (builtins.registry.plusArg(head)) sp = at; + // `Word+arg` for a word that takes one so (`Term+bash`), as exec does; + // an old name's too (`Tty+bash`). + if (sp == null) if (std.mem.indexOfScalar(u8, line, '+')) |at| { + const head = for (pardes.exec.acme_words) |w| { + if (std.mem.eql(u8, line[0..at], w.acme)) break w.pardes orelse ""; + } else line[0..at]; + if (std.meta.stringToEnum(Builtin, head)) |b| if (builtins.registry.plusArg(b)) { + sp = at; + }; }; const typed = line[0 .. sp orelse line.len]; // acme's words: checked as the pardes word they run as, or refused. @@ -592,7 +598,7 @@ pub fn runBuiltin(p: *Pardes, req: Req, id: usize, line: []const u8) ?Reply { p.fs.failure_len = 0; defer p.fs.no_prompt = false; // What a ctl write touched reads back from /look and /exec as a click's - // does (`run`), so a script that made a pane with `Tty` finds it there. + // does (`run`), so a script that made a pane with `Term` finds it there. const context = if (p.panes[id]) |pane| pane.serial else 0; const before = Serials.snapshot(p); _ = exec_line.executeBuiltinLine(p, id, line); @@ -1768,7 +1774,7 @@ test "DumpConfig's whole report writes back to the root ctl, line by line, with } else return error.NoDumpConfigPane; defer testing.allocator.free(report); // What this shell cannot show is a comment, never a value it refuses. - if (pardes.platform == .tty) try testing.expect(std.mem.indexOf(u8, report, "# GripWidth unsupported\n") != null); + if (pardes.platform == .tui) try testing.expect(std.mem.indexOf(u8, report, "# GripWidth unsupported\n") != null); var lines = std.mem.splitScalar(u8, report, '\n'); while (lines.next()) |line| { if (line.len == 0) continue; @@ -1967,7 +1973,7 @@ test "Mount dials its peer and fails, mounting nothing, when none answers; a loo try testing.expect(th.logHas(p, "look: /n/gone/f.txt: dial failed: no answer")); } -test "Tty in a directory that is not there fails and makes no pane; a shell that never started answers a run" { +test "Term in a directory that is not there fails and makes no pane; a shell that never started answers a run" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); @@ -1981,15 +1987,15 @@ test "Tty in a directory that is not there fails and makes no pane; a shell that defer p.host = .{}; var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); - const refused = wr(p, Node.of(serial, .ctl), "Tty\n"); + const refused = wr(p, Node.of(serial, .ctl), "Term\n"); try testing.expectEqual(E.NOENT, refused.errno()); - try testing.expectStringStartsWith(refused.reply.ename, "Tty: /tmp/pardes-no-such-dir-zz: no such directory"); + try testing.expectStringStartsWith(refused.reply.ename, "Term: /tmp/pardes-no-such-dir-zz: no such directory"); var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); // A terminal whose shell the host could not start. _ = wr(p, Node.of(serial, .name), "/tmp/f.txt\n"); - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Tty\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Term\n").reply.status); const term = p.active; p.shellFailed(@intCast(term), error.FileNotFound); const run_node = Node.of(p.panes[term].?.serial, .pty_run); @@ -2066,7 +2072,7 @@ test "a terminal told the directory it already goes by logs no rename" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); _ = wr(p, Node.of(serialOf(p), .name), "/tmp/f.txt\n"); - try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .ctl), "Tty\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .ctl), "Term\n").reply.status); p.update(.tick); // announced const term = p.active; // The host says where its shell started: where it was already named. @@ -2161,7 +2167,7 @@ test "pty/ctl exec in a directory that is gone fails ENOENT; a shell that cannot try testing.expectEqualStrings("shell: permission denied", p.fs.late_failure[0..p.fs.late_failure_len]); } -test "a script whose interpreter is not there: Tty refuses it up front, only an err logged, and pty/ctl exec keeps the running shell" { +test "a script whose interpreter is not there: Term refuses it up front, only an err logged, and pty/ctl exec keeps the running shell" { const p = try th.withTerm(testing.allocator); defer p.deinit(); const Starting = struct { @@ -2178,14 +2184,14 @@ test "a script whose interpreter is not there: Tty refuses it up front, only an const serial = serialOf(p); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); - const refused = wr(p, Node.of(serial, .ctl), try std.fmt.bufPrint(&line, "Tty {s}/bad\n", .{dir})); + const refused = wr(p, Node.of(serial, .ctl), try std.fmt.bufPrint(&line, "Term {s}/bad\n", .{dir})); try testing.expectEqual(E.NOENT, refused.errno()); - try testing.expectEqualStrings("Tty: interpreter /no/such/interp not found", refused.reply.ename); + try testing.expectEqualStrings("Term: interpreter /no/such/interp not found", refused.reply.ename); var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); // The log gained the err and nothing else: no new, msg or del. - try testing.expect(th.logHas(p, "Tty: interpreter /no/such/interp not found\n")); + try testing.expect(th.logHas(p, "Term: interpreter /no/such/interp not found\n")); try testing.expect(!th.logHas(p, "\nmsg ")); try testing.expect(!th.logHas(p, "\ndel ")); // The shell to start again is that script: refused before the running @@ -2407,7 +2413,7 @@ test "a focus moved over 9P tells the programs that asked for focus reports, as const first = for (p.panes) |slot| { if (slot) |pane| if (pane.isTerminal()) break pane.serial; } else return error.NoShell; - try testing.expectEqual(Status.ok, wr(p, Node.of(first, .exec), "Tty\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(first, .exec), "Term\n").reply.status); var shells: [2]usize = undefined; var n: usize = 0; for (p.panes, 0..) |slot, id| if (slot) |pane| if (pane.isTerminal() and n < 2) { @@ -2536,11 +2542,11 @@ test "size is monotonic: growing is never refused, and a size once taken is take p.unattended = true; const root_ctl = @backingInt(tree.TopFile.ctl); const new = @backingInt(tree.TopFile.new); - // The dogfood's repro: Newcol, three pane/new, a Tty, then pane/new + // The dogfood's repro: Newcol, three pane/new, a Term, then pane/new // until a column has no room (ENOSPC). try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status); for (0..3) |_| try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status); - try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.active].?.serial, .ctl), "Tty\n").reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[p.active].?.serial, .ctl), "Term\n").reply.status); p.sync(); while (call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status == .ok) p.sync(); p.sync(); @@ -2875,12 +2881,15 @@ test "a body write to an image pane says its body takes none, not that terminals try testing.expectEqualStrings(pane_files.e_no_body, wr(p, Node.of(doc.serial, .body), "x").reply.ename); } -test "Tty+bash on a pane ctl is Tty with its argument, as exec and the tag take it" { +test "Term+bash on a pane ctl is Term with its argument, as exec and the tag take it" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = call(p, .{ .tag = 1, .op = .write, .node = Node.of(serialOf(p), .ctl), .data = "Tty+sh\n" }); - try testing.expectEqual(Status.ok, r.reply.status); - try testing.expect(r.spawned); + // Tty+sh too: Term's old name, as a saved tag holds it. + for ([_][]const u8{ "Term+sh\n", "Tty+sh\n" }) |data| { + const r = call(p, .{ .tag = 1, .op = .write, .node = Node.of(serialOf(p), .ctl), .data = data }); + try testing.expectEqual(Status.ok, r.reply.status); + try testing.expect(r.spawned); + } } test "a Rename that reaches other files previews them, says so, and is the pane a waiting write answers" { @@ -3003,7 +3012,7 @@ test "a command or a terminal refused for room is refused before anything is log defer p.deinit(); const exec = Node.of(serialOf(p), .exec); var buf: [32]u8 = undefined; - for ([_][]const u8{ "ls\n", "Tty\n" }) |line| { + for ([_][]const u8{ "ls\n", "Term\n" }) |line| { // Each a pane of its own until the column has no room for one more. var before = p.next_serial; var tries: usize = 0; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 28f1882d..d0b368ea 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -883,7 +883,7 @@ fn nameFault(name: []const u8) ?[]const u8 { fn unnamed(pane: *const Pane) []const u8 { return if (pane.isTerminal()) - "invalid rename: a terminal is named by its shell's directory; cd there, or Tty in another" + "invalid rename: a terminal is named by its shell's directory; cd there, or Term in another" else "invalid rename: an image or PDF is named by the file it shows"; } diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index ee8c618e..5c9a6289 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -76,7 +76,7 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { if (!apply and std.mem.eql(u8, line, "exec")) if (p.panes[id]) |pane| if (pane.command != null) return tree.failText(req.tag, E.INVAL, "invalid exec: a command pane does not restart"); // A shell restarted where the directory is gone would not start: - // refused before anything runs, as Tty there is. + // refused before anything runs, as Term there is. if (!apply and std.mem.eql(u8, line, "exec")) if (p.panes[id]) |pane| if (pardes.exec.missingDir(p, pane.cwdSlice())) { const dir = pane.cwdSlice(); return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}: no such directory", .{dir[0..@min(dir.len, 256)]}) catch "exec: no such directory"); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 6bf14243..bd53b6a9 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1843,7 +1843,7 @@ test "random placements, refused or not, leave no pane under its tag and two row 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }), 2 => _ = th.wr(p, Node.of(at, .exec), "Newcol\n"), 3 => _ = th.wr(p, Node.of(at, .exec), "Edit =\n"), - 4 => _ = th.wr(p, Node.of(at, .exec), "Tty\n"), + 4 => _ = th.wr(p, Node.of(at, .exec), "Term\n"), 5 => _ = th.wr(p, Node.of(at, .look), looked), 6 => _ = th.wr(p, Node.of(at, .exec), "Delcol\n"), else => _ = th.wr(p, Node.of(at, .ctl), "delete\n"), @@ -2005,7 +2005,7 @@ test "look and exec read back what their own open's write touched; a fresh open const first = p.panes[0].?.serial; const mine = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle; const theirs = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 2 }).reply.handle; - _ = call(p, .{ .tag = 3, .op = .write, .node = exec, .handle = mine, .data = "Tty\n" }); + _ = call(p, .{ .tag = 3, .op = .write, .node = exec, .handle = mine, .data = "Term\n" }); const made = p.panes[p.active].?.serial; try testing.expect(made != first); _ = call(p, .{ .tag = 4, .op = .write, .node = exec, .handle = theirs, .data = "Msg hi\n" }); diff --git a/src/panes.zig b/src/panes.zig index fd3cfab0..8a9b6aed 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -134,7 +134,7 @@ pub const Pane = struct { /// then /proc says this process's directory, not the shell's /// (Pardes.setCwd keeps the one it was started in). shell_spoke: bool = false, - /// A shell has run in it (Pardes.acknowledgeShell): a Tty whose first + /// A shell has run in it (Pardes.acknowledgeShell): a Term whose first /// shell fails to start closes, one started again keeps its pane. had_shell: bool = false, pending_command: terminal.PendingCommand = .{}, @@ -164,10 +164,10 @@ pub const Pane = struct { /// Its child pages as a terminal's does (`pardes -`, a +Pager), not /// through cat: Look's `git show` of a commit (look.lookCommit). command_pages: bool = false, - /// The shell a terminal runs when it is not the configured one (`Tty + /// The shell a terminal runs when it is not the configured one (`Term /// fish`), owned. shell: ?[]u8 = null, - /// An interactive terminal's tag text naming its shell, ` Tty+fish ...` + /// An interactive terminal's tag text naming its shell, ` Term+fish ...` /// (Pardes.acknowledgeShell); empty until the host says which it ran. shell_tail: [96]u8 = undefined, shell_tail_len: u8 = 0, diff --git a/src/pardes.zig b/src/pardes.zig index 4c1d0a10..89e99a9b 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -75,7 +75,7 @@ const host_io = @import("host_io.zig"); pub const Host = host_io.Host; pub const frameMark = tracy.frameMark; -pub const Platform = enum { tty, gui, web, macos, esp32p4 }; +pub const Platform = enum { tui, gui, web, macos, esp32p4 }; pub const platform: Platform = @field(Platform, @tagName(@import("pardes_config").platform)); pub const theme_animation = @import("pardes_config").theme_animation; @@ -87,7 +87,7 @@ pub const isolated = @import("pardes_isolation").isolated; pub const font_picker = platform == .gui or platform == .macos; -pub const hosted = platform == .tty or platform == .gui or platform == .macos; +pub const hosted = platform == .tui or platform == .gui or platform == .macos; /// Whose turn it is with the core. The core is single-threaded: the editor's /// thread has it, and lets go of it in two kinds of gap -- while it waits for @@ -174,7 +174,7 @@ pub const Turn = struct { pub fn yield(t: *Turn) void { // A replica makes no syscall: each is a site of the tape's. One that // is none stops a speculation and diverges a replay (it joins - // again), never the process (a window client's `Tty fish`, H17). + // again), never the process (a window client's `Term fish`, H17). if (tape.replaying()) tape.stray(); const io = t.io orelse return; yield_depth += 1; @@ -234,7 +234,7 @@ pub const Turn = struct { } }; -pub const can_attach = platform == .tty or platform == .gui; +pub const can_attach = platform == .tui or platform == .gui; pub const terminal_panes = platform != .esp32p4; @@ -253,7 +253,7 @@ pub const sdl_pdf_raster_policy: PdfRasterPolicy = .{ .match_viewport = true, }; pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) { - .tty => kitty_pdf_raster_policy, + .tui => kitty_pdf_raster_policy, // Both pixel shells rasterize for a real display and can afford it; the // wire-bandwidth argument that shapes the Kitty policy does not apply. .gui, .macos => sdl_pdf_raster_policy, @@ -638,21 +638,21 @@ test "topbar hover highlights exactly the executable word" { try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(TAG_TEXT_INSET + 1, 0).style.bg); } -test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { +test "pane-tag Exec prefers Term and argument builtins before shell fallback" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} // initial shell spawn/geometry p.acknowledgeShell(0, "/bin/sh", false); - // The Tty word names the shell the host ran, and opens another of it. + // The Term word names the shell the host ran, and opens another of it. const pane = p.panes[0].?; - try std.testing.expectEqualStrings(" Tty+sh" ++ tagline.terminal_pane_tail[" Tty".len..], tagline.curTail(pane)); + try std.testing.expectEqualStrings(" Term+sh" ++ tagline.terminal_pane_tail[" Term".len..], tagline.curTail(pane)); const tag_x = p.rects[0].x + TAG_TEXT_INSET; const tag_y = p.rects[0].y; const rendered = try tagline.tagText(p, p.scratch.allocator(), pane); - const new_x = tag_x + @as(u16, @intCast(std.mem.indexOf(u8, rendered, "Tty").?)) + 1; + const new_x = tag_x + @as(u16, @intCast(std.mem.indexOf(u8, rendered, "Term").?)) + 1; var panes_before: usize = 0; for (p.panes) |s| if (s != null) { panes_before += 1; @@ -914,14 +914,14 @@ test "compact tag commands stay beside their own prefix across layout changes" { try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); } -test "Tty spawns a raw shell in the caller's directory" { +test "Term spawns a raw shell in the caller's directory" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} p.setCwd(0, "/tmp/newtty-dir"); - try std.testing.expect(p.executeBuiltinLine(0, "Tty")); + try std.testing.expect(p.executeBuiltinLine(0, "Term")); const free = p.active; try std.testing.expect(free != 0); const nt = p.panes[free] orelse return error.NoNewPane; @@ -944,11 +944,11 @@ test "a terminal respawned into a closed pane's slot hangs the old shell up firs // end the new shell and leave the old one running. const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); - try std.testing.expect(p.executeBuiltinLine(0, "Tty")); + try std.testing.expect(p.executeBuiltinLine(0, "Term")); const slot = p.active; while (p.nextEffect()) |_| {} try p.removePane(slot, null); - try std.testing.expect(p.executeBuiltinLine(0, "Tty")); + try std.testing.expect(p.executeBuiltinLine(0, "Term")); try std.testing.expectEqual(slot, p.active); var closed = false; var spawned = false; @@ -965,7 +965,7 @@ test "a terminal respawned into a closed pane's slot hangs the old shell up firs try std.testing.expect(closed and spawned); } -test "first document fallback splits like Tty from the originating pane" { +test "first document fallback splits like Term from the originating pane" { for ([_]u16{ 100, 198 }) |width| for (0..3) |from| { for ([_]bool{ false, true }) |collapsed| { const p = try Pardes.init(std.testing.allocator, .{ .cols = width, .rows = 62, .shells = 3 }); @@ -1608,43 +1608,55 @@ test "a restored terminal's tag names neither the REPL it was nor the shell it h try std.testing.expect(pane.repl == null and pane.tag.own == null); const shown = try tagline.tagText(restored, restored.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, shown, "python-a") == null); - try std.testing.expect(std.mem.indexOf(u8, shown, "Tty+fish") == null); + try std.testing.expect(std.mem.indexOf(u8, shown, "Term+fish") == null); } -test "a Tty started by a shell's path keeps the path in its Tty+ word" { +test "a Term started by a shell's path keeps the path in its Term+ word" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} - try std.testing.expect(p.executeBuiltinLine(0, "Tty /bin/sh")); + try std.testing.expect(p.executeBuiltinLine(0, "Term /bin/sh")); try std.testing.expect(p.active != 0); p.acknowledgeShell(p.active, "/bin/sh", false); - try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.active].?), " Tty+/bin/sh ")); + try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.active].?), " Term+/bin/sh ")); } -test "Tty+fish, one word a tag can hold, opens a terminal on that shell" { +test "Tty, Term's old name in saved tags, runs as Term, bare and with its +shell" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} - // sh, the one shell every host has. try std.testing.expect(p.executeBuiltinLine(0, "Tty+sh")); + try std.testing.expectEqualStrings("sh", p.panes[p.active].?.shell.?); + const first = p.active; + p.active = 0; + try std.testing.expect(p.executeBuiltinLine(0, "Tty")); + try std.testing.expect(p.active != 0 and p.active != first); +} + +test "Term+fish, one word a tag can hold, opens a terminal on that shell" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + // sh, the one shell every host has. + try std.testing.expect(p.executeBuiltinLine(0, "Term+sh")); try std.testing.expect(p.active != 0); try std.testing.expectEqualStrings("sh", p.panes[p.active].?.shell.?); p.acknowledgeShell(p.active, "/bin/sh", false); - try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.active].?), " Tty+sh ")); + try std.testing.expect(std.mem.startsWith(u8, tagline.curTail(p.panes[p.active].?), " Term+sh ")); p.active = 0; // A shell that is not there is said, not quietly replaced, and the // pane that asked gets no shell of its own. const before = p.active; const caller = p.panes[0].?; - try std.testing.expect(p.executeBuiltinLine(0, "Tty /nonexistent")); + try std.testing.expect(p.executeBuiltinLine(0, "Term /nonexistent")); try std.testing.expect(p.active == before and caller.shell == null); try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "shell \"/nonexistent\" not found") != null); - try std.testing.expect(p.executeBuiltinLine(0, "Tty fsh-not-a-shell")); + try std.testing.expect(p.executeBuiltinLine(0, "Term fsh-not-a-shell")); try std.testing.expect(caller.shell == null); // A directory passes access(X_OK); it is no shell either. - try std.testing.expect(p.executeBuiltinLine(0, "Tty /etc")); + try std.testing.expect(p.executeBuiltinLine(0, "Term /etc")); try std.testing.expect(p.active == before); - try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "Tty: not a shell: /etc is a directory") != null); + try std.testing.expect(std.mem.indexOf(u8, caller.msg[0..caller.msg_len], "Term: not a shell: /etc is a directory") != null); // Only a word that says so splits at `+`: `Dump+x.zon` is no Dump. try std.testing.expect(!p.executeBuiltinLine(0, "Dump+x.zon")); try std.testing.expect(!p.executeBuiltinLine(0, "Msg+hello")); @@ -2417,13 +2429,13 @@ test "Save reaches every tagline with text behind it and no other" { // A scratch is an output buffer that wears the FILE tails. out.file.?.output = .{ .from = .{ .cmd = std.meta.stringToEnum(Builtin, "New").? } }; - try std.testing.expectEqualStrings(" Save Tty Collapse Del", tagline.curTail(out)); + try std.testing.expectEqualStrings(" Save Term Collapse Del", tagline.curTail(out)); // An image's bytes on disk already are what they are: nothing of the // pane's own is unwritten, so the word is absent and inert. const img_id = p.freeSlot().?; const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Collapse Del", tagline.curTail(img)); + try std.testing.expectEqualStrings(" Term Collapse Del", tagline.curTail(img)); try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); try std.testing.expect(img.prompt != .save); var buf: [256]u8 = undefined; @@ -3804,7 +3816,7 @@ pub const Options = struct { /// window's build replaying a terminal's session starts as it did. windowed: bool = platform == .gui, /// The layout to boot, when a host means one outright rather than leaving - /// it to be read off the options below. `--tty` names `.tty`; a core + /// it to be read off the options below. `--tui` names `.tty`; a core /// booted for a test names nothing and gets `.tty_shell`. boot: ?Boot = null, /// initial shell panes: 1 (default) or 3 for the classic two-column boot. @@ -5024,7 +5036,7 @@ pub const Pardes = struct { } /// A shell a dead session left, taken in (Adopt): a terminal pane made - /// for it as the Tty word makes one, its greeting off (the shell is up + /// for it as the Term word makes one, its greeting off (the shell is up /// already), whose spawn the host answers with that shell's pty. Its id, /// or null with no room. An input, as every host write into the core /// is: a replica of the session makes the same pane. @@ -5035,7 +5047,7 @@ pub const Pardes = struct { for (p.panes) |slot| if (slot) |pn| { newest = @max(newest, pn.serial); }; - _ = p.executeBuiltinLine(p.active, "Tty"); + _ = p.executeBuiltinLine(p.active, "Term"); for (p.panes, 0..) |slot, id| if (slot) |pn| if (pn.serial > newest and pn.isTerminal()) { pn.greet = false; return @intCast(id); @@ -5061,14 +5073,14 @@ pub const Pardes = struct { pane.shell_failed = false; pane.had_shell = true; pane.fs.unmarked = !prompt_marks; - // The tag's Tty word names the shell the host ran, and a click - // on it (`Tty+fish`) opens another of the same. + // The tag's Term word names the shell the host ran, and a click + // on it (`Term+fish`) opens another of the same. if (pane.command == null) { // A shell given as a path keeps it: its bare name would find // nothing, or another program, on the usual paths. const base = if (pane.shell) |given| (if (std.mem.indexOfScalar(u8, given, '/') != null) given else std.fs.path.basename(executable)) else std.fs.path.basename(executable); - const rest = tagline.terminal_pane_tail[" Tty".len..]; - if (std.fmt.bufPrint(&pane.shell_tail, " Tty+{s}{s}", .{ base, rest })) |tail| { + const rest = tagline.terminal_pane_tail[" Term".len..]; + if (std.fmt.bufPrint(&pane.shell_tail, " Term+{s}{s}", .{ base, rest })) |tail| { pane.shell_tail_len = @intCast(tail.len); } else |_| {} } @@ -5416,7 +5428,7 @@ pub const Pardes = struct { pane.command_pty = false; exec.commandDone(p, id, 127); } else if (pane.command == null and !pane.had_shell) { - // A Tty whose shell never ran: no dead pane left behind; the + // A Term whose shell never ran: no dead pane left behind; the // write that asked for it has failed with why. A terminal whose // shell was started again (pty/ctl exec) keeps its pane. p.unplaced.set(id); @@ -6244,7 +6256,7 @@ pub const Pardes = struct { // global window ops (any mode): Alt-n new terminal below, Alt-c move // the active terminal into a fresh column if (hit(key, config.new_shell_below)) { - const free = p.freeSlot() orelse return p.reportError(p.active, "Tty", error.NoPaneSlots); + const free = p.freeSlot() orelse return p.reportError(p.active, "Term", error.NoPaneSlots); const nt = p.newShell(free, "") catch return; nt.greet = true; // From a tag, as a 9P new is: acme's t->w == nil. diff --git a/src/replica.zig b/src/replica.zig index 8cacb075..a6014f5b 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -2109,7 +2109,7 @@ pub const Peers = struct { } /// Every client told `why` and let go, its view with it: an Upgrade's - /// exec is next (tty.zig `upgradeNow`). What each was sent goes first, + /// exec is next (tui.zig `upgradeNow`). What each was sent goes first, /// for up to 200 ms; a client then dials the session again. pub fn refuseAll(ps: *Peers, core: *Pardes, why: []const u8) void { if (ps.count() == 0) return; @@ -2757,7 +2757,7 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime rest.run(gpa, fd, ctx, Take.take); } -/// A replica client's link to its session, the terminal's (tty.zig +/// A replica client's link to its session, the terminal's (tui.zig /// `remote`) and the window's (gui.zig `remote`): its replica, its socket, /// what the session said, and what it checks. Drawing is the frontend's. pub const Link = struct { @@ -3666,7 +3666,7 @@ test "a host's Adopt and a terminal reader's failure are inputs: a replica makes defer a.core.gpa.free(bytes); const r = try Replica.initDump(gpa, 1, 0, bytes, .{ .cols = 80, .rows = 24 }); defer r.deinit(); - // What tty.zig's and gui.zig's adoptShell and a failed reader do between + // What tui.zig's and gui.zig's adoptShell and a failed reader do between // steps: they wrote the core straight, and every client joined again. const host = Stepping.begin(&a.t, null); const id = a.core.adoptShell().?; diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index 37cf22d0..207d45c2 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -168,7 +168,7 @@ pub const Outcome = union(enum) { ok: []u8, failed: Failure }; /// The in-flight set a host keeps while pipes run off its loop. /// -/// tty.zig and gui.zig each had this verbatim — same `finish` walk, same +/// tui.zig and gui.zig each had this verbatim — same `finish` walk, same /// `cancelAll`, same 16 — differing only in whether `add` asserted or returned /// a bool. It lives here beside the Job it tracks so a third host (the AppKit /// shell, which had no pipe support at all) does not have to grow a fourth. diff --git a/src/surface.zig b/src/surface.zig index aa0068e3..f5afdd98 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -477,7 +477,7 @@ pub const Chrome = struct { fx: u8 = 0, }; -/// The canonical interface: what a frame of pardes IS. The tty shell writes +/// The canonical interface: what a frame of pardes IS. The tui shell writes /// these cells to vaxis one-to-one; the SDL shells rasterize them. pub const Surface = struct { /// `box` is acme's boxcursor, shown while a pane or a column is carried diff --git a/src/tagline.zig b/src/tagline.zig index 7af9ba66..e7194981 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -47,7 +47,7 @@ pub fn dirty(pane: *const panes.Pane) bool { return panes.Output.fileTraits(f.output).saves and (f.revision != f.saved_revision or f.disk_gone); } /// What a column's tag says until someone edits it. -pub const column_tag_default = "New Tty Find Grep Joincol Delcol"; +pub const column_tag_default = "New Term Find Grep Joincol Delcol"; /// What a header says until someone edits it: for the workspace the /// fixed builtins, plus `Restore ` once a dump exists. @@ -135,7 +135,7 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.command_status) |n| return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit {d}{s}{s}", .{ (try shownDir(arena, pane)), shown, more, n, gap, id }); return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit ?{s}{s}", .{ (try shownDir(arena, pane)), shown, more, gap, id }); } - // A bound REPL says what it is bound as, beside its Tty word, while its + // A bound REPL says what it is bound as, beside its Term word, while its // program runs: a command REPL whose command exited says no id. if (pane.repl != null and !(pane.command != null and pane.command_done)) { var idbuf: [48]u8 = undefined; diff --git a/src/tape.zig b/src/tape.zig index c0f33f21..78b3c34b 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -1258,7 +1258,7 @@ pub fn startFromEnv() void { /// digest checked; 0 when none diverged. pub fn replayMain(io: std.Io, path: []const u8) u8 { const gpa = std.heap.c_allocator; - // What a shell starts before its core (tty.zig's localSession). + // What a shell starts before its core (tui.zig's localSession). pardes.image.start(io, gpa); if (comptime pardes.pdf_enabled) pardes.pdf.start(gpa); pardes.syntax.start(gpa); diff --git a/src/terminal.zig b/src/terminal.zig index 86eec32d..2bd41030 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -994,7 +994,7 @@ pub fn reviveShell(pane: *Pane) void { ingest(pane, "\x1b[?1l\x1b>\x1b[?25h\x1b[?7h\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[ {}, - .slide, .zoom => transform(out, source, track), - .dissolve => dissolve(out, source, track), - // Pardes core has already composed every character effect - // into source.cells — byte walks, glyph motion, and per-cell - // locks are semantic. TTY only owns cursor suppression here. - .ascii, .edges, .fall, .wave, .curtain, .scramble, .typewriter => {}, - .vertical => vertical(out, source, track), - } - } - } - return out; -} - -/// Content effects have no honest frame without the frozen old grid. In -/// production the core drops such tracks before publishing Surface; retain -/// this guard at the backend boundary so a partial/custom caller also snaps -/// to canonical content instead of manufacturing blanks. -fn drawable(source: *const pardes.Surface, track: Track) bool { - return track.active() and - (!track.effect.needsPreviousGrid() or source.hasPanelDiff()); -} - -fn transform(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { - const shown = track.presented(); - if (shown.w <= 0 or shown.h <= 0) return; - const dst = clipped(shown, out.cols, out.rows) orelse return; - var y = dst.y0; - while (y < dst.y1) : (y += 1) { - var x = dst.x0; - while (x < dst.x1) : (x += 1) { - // The core hit-tests cell CENTRES against this same half-open box. - // floor/ceil clipping includes boundary cells for iteration, but - // they are not visible unless their centre is actually inside. - // Test that containment before division: at large u16 grids f32 - // can round an inside right-edge ratio to exactly 1.0. - const cx = @as(f32, @floatFromInt(x)) + 0.5; - const cy = @as(f32, @floatFromInt(y)) + 0.5; - if (cx < shown.x or cx >= shown.x + shown.w or - cy < shown.y or cy >= shown.y + shown.h) continue; - const u = std.math.clamp((cx - shown.x) / shown.w, 0, 0.999_999); - const v = std.math.clamp((cy - shown.y) / shown.h, 0, 0.999_999); - const sx: i32 = @intFromFloat(@floor(track.to.x + u * track.to.w)); - const sy: i32 = @intFromFloat(@floor(track.to.y + v * track.to.h)); - if (sx < 0 or sy < 0 or sx >= source.cols or sy >= source.rows) continue; - out.at(x, y).* = source.cells[@as(usize, @intCast(sy)) * source.cols + @as(usize, @intCast(sx))]; - } - } -} - -fn dissolve(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { - const area = clipped(track.to, out.cols, out.rows) orelse return; - const amount = track.amount(); - var y = area.y0; - while (y < area.y1) : (y += 1) { - var x = area.x0; - while (x < area.x1) : (x += 1) { - if (!source.panelCellChanged(x, y)) continue; - if (animation.dissolveRevealed( - track.serial, - x - area.x0, - y - area.y0, - amount, - )) continue; - out.at(x, y).* = previousCell(source, x, y).*; - } - } -} - -fn previousCell(source: *const pardes.Surface, x: u16, y: u16) *const pardes.Cell { - std.debug.assert(source.hasPanelDiff()); - return &source.previous_cells[@as(usize, y) * source.cols + x]; -} - -fn restorePrevious(out: *pardes.Surface, source: *const pardes.Surface, box: Box) void { - const area = clipped(box, out.cols, out.rows) orelse return; - var y = area.y0; - while (y < area.y1) : (y += 1) { - var x = area.x0; - while (x < area.x1) : (x += 1) - out.at(x, y).* = previousCell(source, x, y).*; - } -} - -fn vertical(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { - const cells = if (track.phase == .closing) source.previous_cells else source.cells; - transformClipped(out, source.cols, source.rows, cells, track, track.contentBox()); -} - -/// Translate one old/new canonical panel through its fixed lifecycle clip. -/// Sampling is always relative to contentBox: an opener reads its new target, -/// while a closer reads the old box retained after that pane was destroyed. -fn transformClipped( - out: *pardes.Surface, - source_cols: u16, - source_rows: u16, - cells: []const pardes.Cell, - track: Track, - clip: Box, -) void { - const shown = track.presented(); - if (shown.w <= 0 or shown.h <= 0) return; - const dst = clipped(shown, out.cols, out.rows) orelse return; - const content = track.contentBox(); - var y = dst.y0; - while (y < dst.y1) : (y += 1) { - var x = dst.x0; - while (x < dst.x1) : (x += 1) { - const cx = @as(f32, @floatFromInt(x)) + 0.5; - const cy = @as(f32, @floatFromInt(y)) + 0.5; - if (cx < shown.x or cx >= shown.x + shown.w or - cy < shown.y or cy >= shown.y + shown.h or - cx < clip.x or cx >= clip.x + clip.w or - cy < clip.y or cy >= clip.y + clip.h) continue; - const u = std.math.clamp((cx - shown.x) / shown.w, 0, 0.999_999); - const v = std.math.clamp((cy - shown.y) / shown.h, 0, 0.999_999); - const sx: i32 = @intFromFloat(@floor(content.x + u * content.w)); - const sy: i32 = @intFromFloat(@floor(content.y + v * content.h)); - if (sx < 0 or sy < 0 or sx >= source_cols or sy >= source_rows) continue; - out.at(x, y).* = cells[@as(usize, @intCast(sy)) * source_cols + @as(usize, @intCast(sx))]; - } - } -} - -fn clearBox(surface: *pardes.Surface, box: Box, theme_bg: ?[3]u8) void { - const area = clipped(box, surface.cols, surface.rows) orelse return; - var blank: pardes.Cell = .{}; - if (theme_bg) |rgb| { - blank.default = false; - blank.style.bg = .{ .rgb = rgb }; - } - var y = area.y0; - while (y < area.y1) : (y += 1) { - var x = area.x0; - while (x < area.x1) : (x += 1) surface.at(x, y).* = blank; - } -} - -const GridBox = struct { x0: u16, y0: u16, x1: u16, y1: u16 }; - -fn clipped(box: Box, cols: u16, rows: u16) ?GridBox { - const x0: i32 = @intFromFloat(@floor(box.x)); - const y0: i32 = @intFromFloat(@floor(box.y)); - const x1: i32 = @intFromFloat(@ceil(box.x + box.w)); - const y1: i32 = @intFromFloat(@ceil(box.y + box.h)); - const area: GridBox = .{ - .x0 = @intCast(std.math.clamp(x0, 0, @as(i32, cols))), - .y0 = @intCast(std.math.clamp(y0, 0, @as(i32, rows))), - .x1 = @intCast(std.math.clamp(x1, 0, @as(i32, cols))), - .y1 = @intCast(std.math.clamp(y1, 0, @as(i32, rows))), - }; - return if (area.x0 < area.x1 and area.y0 < area.y1) area else null; -} - -test "TTY consumes core-composed ASCII cells without reinterpreting glyphs" { - var cells: [8]pardes.Cell = @splat(.{}); - var previous: [8]pardes.Cell = @splat(.{}); - const diffs: [8]pardes.PanelCellDiff = @splat(.visual); - for (&cells) |*cell| { - cell.text[0] = 'X'; - cell.len = 1; - cell.default = false; - } - for (&previous) |*cell| { - cell.text[0] = 'O'; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ - .cols = 4, - .rows = 2, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 9, - .effect = .ascii, - .frame = 0, - .from = .{ .w = 4, .h = 2 }, - .to = .{ .w = 4, .h = 2 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expect(animated != &surface); - try std.testing.expectEqualStrings("X", surface.at(0, 0).grapheme()); - for (animated.cells) |cell| try std.testing.expectEqualStrings("X", cell.grapheme()); -} - -test "dissolve changes only diff cells from old to new" { - var cells: [2]pardes.Cell = @splat(.{}); - var previous: [2]pardes.Cell = @splat(.{}); - for (&cells, "NU") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - for (&previous, "OU") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs = [_]pardes.PanelCellDiff{ .{ .ascii = .{ .from = 'O', .to = 'N' } }, .unchanged }; - var surface: pardes.Surface = .{ - .cols = 2, - .rows = 1, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - var track: Track = .{ - .serial = 1, - .effect = .dissolve, - .from = .{ .w = 2, .h = 1 }, - .to = .{ .w = 2, .h = 1 }, - }; - - const first = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("O", first.at(0, 0).grapheme()); - try std.testing.expectEqual(cells[1], first.at(1, 0).*); - - _ = arena.reset(.retain_capacity); - track.frame = track.effect.frames() - 1; - const final = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(cells[0], final.at(0, 0).*); - try std.testing.expectEqual(cells[1], final.at(1, 0).*); -} - -test "TTY content effects never touch cells outside the published diff" { - var cells: [4]pardes.Cell = @splat(.{}); - var previous: [4]pardes.Cell = @splat(.{}); - for (&cells, "NUQV") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - // Deliberately disagree even where the mask says unchanged. This makes - // the test prove that the compositor obeys the core cell diff rather than - // merely appearing correct because old and new happened to match there. - for (&previous, "OXRY") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs = [_]pardes.PanelCellDiff{ .visual, .unchanged, .visual, .unchanged }; - var surface: pardes.Surface = .{ - .cols = 4, - .rows = 1, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - - for ([_]animation.Transition{ .ascii, .dissolve }) |effect| { - const track: Track = .{ - .serial = 17, - .effect = effect, - .from = .{ .w = 4, .h = 1 }, - .to = .{ .w = 4, .h = 1 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(cells[1], animated.at(1, 0).*); - try std.testing.expectEqual(cells[3], animated.at(3, 0).*); - _ = arena.reset(.retain_capacity); - } -} - -test "content transition without a diff snaps to canonical surface" { - var cells = [_]pardes.Cell{.{}}; - cells[0].text[0] = 'N'; - cells[0].default = false; - var surface: pardes.Surface = .{ - .cols = 1, - .rows = 1, - .cells = &cells, - .cursor = .{ .x = 0, .y = 0 }, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - - for ([_]animation.Transition{ .dissolve, .ascii, .vertical }) |effect| { - const track: Track = .{ - .effect = effect, - .phase = .opening, - .from = .{ .y = 1, .w = 1, .h = 1 }, - .to = .{ .w = 1, .h = 1 }, - }; - try std.testing.expectEqual(&surface, try compose(arena.allocator(), &surface, &.{track}, null)); - } -} - -test "exact transition endpoint preserves the canonical cursor" { - var cells = [_]pardes.Cell{.{}}; - var previous = cells; - const diffs = [_]pardes.PanelCellDiff{.visual}; - var surface: pardes.Surface = .{ - .cols = 1, - .rows = 1, - .cells = &cells, - .cursor = .{ .x = 0, .y = 0 }, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - const track: Track = .{ - .effect = .ascii, - .frame = animation.Transition.ascii.frames() - 1, - .from = .{ .w = 1, .h = 1 }, - .to = .{ .w = 1, .h = 1 }, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - - const result = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(&surface, result); - try std.testing.expect(result.cursor != null); -} - -test "vertical opening rises through a fixed old-grid clip" { - var cells: [12]pardes.Cell = @splat(.{}); - var previous: [12]pardes.Cell = @splat(.{}); - for (&cells, "aaabbbcccddd") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - for (&previous, "000111222333") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs: [12]pardes.PanelCellDiff = @splat(.visual); - var surface: pardes.Surface = .{ - .cols = 3, - .rows = 4, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const target: Box = .{ .y = 1, .w = 3, .h = 2 }; - var track: Track = .{ - .serial = 5, - .phase = .opening, - .effect = .vertical, - .from = animation.openingBox(.vertical, target, 3), - .to = target, - }; - - const first = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("1", first.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("2", first.at(0, 2).grapheme()); - try std.testing.expectEqualStrings("a", first.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("d", first.at(0, 3).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = 2; - const entering = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("1", entering.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("b", entering.at(0, 2).grapheme()); - try std.testing.expectEqualStrings("a", entering.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("d", entering.at(0, 3).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = track.effect.frames() - 1; - const final = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("b", final.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("c", final.at(0, 2).grapheme()); -} - -test "vertical closing drops frozen content over canonical cells" { - var cells: [12]pardes.Cell = @splat(.{}); - var previous: [12]pardes.Cell = @splat(.{}); - for (&cells, "aaabbbcccddd") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - for (&previous, "000111222333") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - const diffs: [12]pardes.PanelCellDiff = @splat(.visual); - var surface: pardes.Surface = .{ - .cols = 3, - .rows = 4, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const old_box: Box = .{ .y = 1, .w = 3, .h = 2 }; - var track: Track = .{ - .serial = 5, - .phase = .closing, - .effect = .vertical, - .from = old_box, - .to = animation.closingBox(.vertical, old_box), - }; - - const first = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("1", first.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("2", first.at(0, 2).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = 8; - const leaving = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqualStrings("b", leaving.at(0, 1).grapheme()); - try std.testing.expectEqualStrings("1", leaving.at(0, 2).grapheme()); - try std.testing.expectEqualStrings("a", leaving.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("d", leaving.at(0, 3).grapheme()); - - _ = arena.reset(.retain_capacity); - track.frame = track.effect.frames() - 1; - const final = try compose(arena.allocator(), &surface, &.{track}, null); - try std.testing.expectEqual(cells[3], final.at(0, 1).*); - try std.testing.expectEqual(cells[6], final.at(0, 2).*); -} - -test "closing content paints after opening content regardless of track order" { - var cells = [_]pardes.Cell{.{}}; - var previous = [_]pardes.Cell{.{}}; - cells[0].text[0] = 'N'; - cells[0].default = false; - previous[0].text[0] = 'O'; - previous[0].default = false; - const diffs = [_]pardes.PanelCellDiff{.visual}; - var surface: pardes.Surface = .{ - .cols = 1, - .rows = 1, - .cells = &cells, - .previous_cells = &previous, - .cell_diffs = &diffs, - }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const box: Box = .{ .w = 1, .h = 1 }; - const closing: Track = .{ - .serial = 1, - .phase = .closing, - .effect = .vertical, - .from = box, - .to = animation.closingBox(.vertical, box), - }; - const opening: Track = .{ - .serial = 2, - .phase = .opening, - .effect = .ascii, - .frame = animation.Transition.ascii.frames() - 1, - .from = box, - .to = box, - }; - - const animated = try compose(arena.allocator(), &surface, &.{ closing, opening }, null); - try std.testing.expectEqualStrings("O", animated.at(0, 0).grapheme()); -} - -test "opening panel cannot erase an existing panel drawn underneath" { - var cells: [8]pardes.Cell = @splat(.{}); - for (&cells, 0..) |*cell, x| { - cell.text[0] = if (x < 4) 'A' else 'B'; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ .cols = 8, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const tracks = [_]Track{ - .{ - .serial = 1, - .phase = .moving, - .effect = .slide, - .from = .{ .w = 8, .h = 1 }, - .to = .{ .w = 4, .h = 1 }, - }, - .{ - .serial = 2, - .phase = .opening, - .effect = .slide, - .from = .{ .x = 8, .w = 4, .h = 1 }, - .to = .{ .x = 4, .w = 4, .h = 1 }, - }, - }; - const animated = try compose(arena.allocator(), &surface, &tracks, null); - try std.testing.expectEqualStrings("A", animated.at(7, 0).grapheme()); -} - -test "geometry gap is a blank painted in an explicit theme background" { - var cells: [4]pardes.Cell = @splat(.{}); - for (&cells, "ABCD") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - cell.style = .{ - .fg = .{ .rgb = .{ 220, 210, 200 } }, - .bg = .{ .rgb = .{ 30, 20, 10 } }, - .bold = true, - .font_role = .tagline, - }; - } - var surface: pardes.Surface = .{ .cols = 4, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 1, - .effect = .slide, - .from = .{ .x = 2, .w = 2, .h = 1 }, - .to = .{ .w = 4, .h = 1 }, - }; - const page_bg = [3]u8{ 248, 244, 232 }; - const animated = try compose(arena.allocator(), &surface, &.{track}, page_bg); - - const gap = animated.at(0, 0); - try std.testing.expect(!gap.default); - try std.testing.expectEqualStrings(" ", gap.grapheme()); - try std.testing.expectEqual(pardes.Color{ .rgb = page_bg }, gap.style.bg); - try std.testing.expectEqual(pardes.Color.default, gap.style.fg); - try std.testing.expect(!gap.style.bold); - try std.testing.expectEqual(pardes.FontRole.body, gap.style.font_role); - // The clear supplies only exposed geometry. Cells sampled from the moving - // panel retain all canonical content and style fields byte-for-byte. - try std.testing.expectEqual(cells[1], animated.at(2, 0).*); -} - -test "geometry gap stays terminal-default for a transparent theme" { - var cells: [2]pardes.Cell = @splat(.{}); - for (&cells, "AB") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ .cols = 2, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 1, - .effect = .slide, - .from = .{ .x = 1, .w = 1, .h = 1 }, - .to = .{ .w = 2, .h = 1 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - - const gap = animated.at(0, 0); - try std.testing.expect(gap.default); - try std.testing.expectEqualStrings(" ", gap.grapheme()); - try std.testing.expectEqual(pardes.Color.default, gap.style.bg); -} - -test "fractional geometry draws exactly the cell centres core can hit" { - var cells: [3]pardes.Cell = @splat(.{}); - for (&cells, "ABC") |*cell, glyph| { - cell.text[0] = glyph; - cell.len = 1; - cell.default = false; - } - var surface: pardes.Surface = .{ .cols = 3, .rows = 1, .cells = &cells }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const track: Track = .{ - .serial = 1, - .effect = .slide, - .from = .{ .x = 0.9, .w = 1, .h = 1 }, - .to = .{ .x = 0, .w = 1, .h = 1 }, - }; - const animated = try compose(arena.allocator(), &surface, &.{track}, null); - // Cell 0 lies in floor/ceil iteration bounds, but its centre (0.5) is - // outside [0.9, 1.9); cell 1 is the only presented/hit-testable cell. - try std.testing.expectEqualStrings(" ", animated.at(0, 0).grapheme()); - try std.testing.expectEqualStrings("A", animated.at(1, 0).grapheme()); -} - -test "large-grid right edge uses containment before rounded ratio" { - const cols = std.math.maxInt(u16); - const source_cells = try std.testing.allocator.alloc(pardes.Cell, cols); - defer std.testing.allocator.free(source_cells); - const output_cells = try std.testing.allocator.alloc(pardes.Cell, cols); - defer std.testing.allocator.free(output_cells); - @memset(source_cells, .{}); - @memset(output_cells, .{}); - for (source_cells) |*cell| { - cell.text[0] = 'X'; - cell.len = 1; - cell.default = false; - } - var source: pardes.Surface = .{ .cols = cols, .rows = 1, .cells = source_cells }; - var output: pardes.Surface = .{ .cols = cols, .rows = 1, .cells = output_cells }; - const track: Track = .{ - .serial = 1, - .effect = .zoom, - .frame = 8, - .from = .{ .x = 56_796, .w = 8_299, .h = 1 }, - .to = .{ .x = 556, .w = 63_483, .h = 1 }, - }; - const shown = track.presented(); - try std.testing.expect(@as(f32, 63_935.5) < shown.x + shown.w); - transform(&output, &source, track); - try std.testing.expectEqualStrings("X", output.at(63_935, 0).grapheme()); -} - -test "active panel transition hides only its own native attachment" { - const tracks = [_]Track{ - .{ .serial = 41, .effect = .slide, .frame = 0 }, - .{ .serial = 42, .effect = .ascii, .frame = 0 }, - .{ .serial = 43, .effect = .zoom, .frame = animation.Transition.zoom.frames() - 1 }, - .{ .serial = 44, .effect = .zoom, .frame = animation.Transition.zoom.frames() }, - .{ .serial = 45, .phase = .opening, .effect = .vertical, .frame = 0 }, - }; - - try std.testing.expect(hidesAttachment(&tracks, 41)); - try std.testing.expect(!hidesAttachment(&tracks, 42)); - try std.testing.expect(!hidesAttachment(&tracks, 43)); - try std.testing.expect(!hidesAttachment(&tracks, 44)); - try std.testing.expect(hidesAttachment(&tracks, 45)); - try std.testing.expect(!hidesAttachment(&tracks, 46)); -} diff --git a/src/tty/tty.zig b/src/tty/tty.zig deleted file mode 100644 index 4c054021..00000000 --- a/src/tty/tty.zig +++ /dev/null @@ -1,4017 +0,0 @@ -const filesystem = @import("../fs.zig"); -const std = @import("std"); -const builtin = @import("builtin"); -const posix = std.posix; -const libc = std.c; -const vaxis = @import("vaxis"); -const pardes = @import("../pardes.zig"); -const vaxis_input = @import("../vaxis_input.zig"); -const dump = @import("../dump.zig"); -const tracy = @import("../tracy.zig"); -const look = @import("../look.zig"); -const message = pardes.Messages.Message; -const file_watch = @import("../file_watch.zig"); -const selection_pipe = @import("../selection_pipe.zig"); -const ninep_io = @import("../9p_io.zig"); -const panel_compositor = @import("panel_compositor.zig"); -const daemon = @import("../daemon.zig"); -const host_io = @import("../host_io.zig"); -const upgrade = @import("../upgrade.zig"); -const replica = @import("../replica.zig"); -const wire = @import("../detached/wire.zig"); - -extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; - -const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); - -/// What a terminal's input reader keeps, one a terminal (views.zig): its -/// graphemes, the frame it waits on the answer to, the shm probe, and the -/// view its input is. -const Feed = struct { - view: u8 = 0, - cache: vaxis.GraphemeCache = .{}, - ack: FrameAck = .{}, - /// The terminal answered the shared-memory probe (`kittyShmProbe`): it - /// can read a raster from a POSIX shm object, so a page costs a name on - /// the wire instead of its whole base64 body. Set by the input reader, - /// which sees the reply before vaxis' parser swallows every graphics APC - /// alike. - shm: std.atomic.Value(bool) = .init(false), - /// Only a reply that arrives while the probe is out counts. The id is - /// one vaxis' own image numbering (1, 2, ...) never reaches, because a - /// terminal answers every transmission `i=;OK` and one of those must - /// not pass. - shm_probing: std.atomic.Value(bool) = .init(false), -}; - -/// A terminal's input onto the loop's queue, as its view's: a `from` goes -/// ahead of it whenever another terminal posted last. With one terminal -/// none ever does. -const Poster = struct { - loop: *Loop, - view: u8, - var lock: std.Io.Mutex = .init; - var last: u8 = 0; - - pub fn postEvent(p: Poster, ev: @TypeOf(Command.value)) !void { - lock.lockUncancelable(p.loop.io); - defer lock.unlock(p.loop.io); - if (last != p.view) { - try p.loop.postEvent(.{ .from = p.view }); - last = p.view; - } - try p.loop.postEvent(ev); - } -}; -const kitty_shm_probe_id = 0x7fff_fff1; -var kitty_shm_serial: u32 = 0; -/// Transmissions an unread shm segment outlives before it is removed. -const kitty_shm_window = 64; - -fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { - return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); -} - -/// A terminal unlinks what it reads; whatever it never read (the probe -/// unanswered, a transmission lost with the terminal) is ours to remove. -fn unlinkKittyShm() void { - var name_buf: [64]u8 = undefined; - var n: u32 = 0; - while (n <= kitty_shm_serial) : (n += 1) { - if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} - } -} - -/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading. -fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { - const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600)); - if (fd < 0) return false; - defer _ = libc.close(fd); - if (libc.ftruncate(fd, @intCast(bytes.len)) != 0) { - _ = libc.shm_unlink(name); - return false; - } - var off: usize = 0; - while (off < bytes.len) { - const n = libc.write(fd, bytes[off..].ptr, bytes.len - off); - if (n <= 0) { - _ = libc.shm_unlink(name); - return false; - } - off += @intCast(n); - } - return true; -} - -/// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A -/// remote terminal cannot see our shm and answers an error (or nothing). -fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { - var buf: [64]u8 = undefined; - const name = kittyShmName(&buf, 0) catch return; - if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; - var b64: [64]u8 = undefined; - const enc = std.base64.standard.Encoder.encode(&b64, name); - feed.shm_probing.store(true, .release); - w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; - w.flush() catch {}; -} - -pub const Command = struct { - pub var value: union(enum) { - nop, - /// The terminal's input ended: its end of file, a hangup. A session - /// a daemon keeps carries on detached; any other ends. - quit, - /// A terminal for this detached session, and its stub's pipe - /// (daemon.Note.attach). - attach: struct { tty: posix.fd_t, stub: posix.fd_t }, - /// A shell a dead session left, its pty's master (daemon.Note.adopted). - adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, - /// A timed wait ran out: the core's next wake has come. - wake, - /// The input after this is the terminal of this view's (Poster). - from: u8, - /// A SIGWINCH: a terminal changed size (Shell.winched). - winched, - /// A SIGHUP: the session's own terminal hung up. - hangup, - key_press: vaxis.Key, - pty_read: struct { id: usize, gen: u32, bytes: []u8 }, - pty_eof: struct { id: usize, gen: u32 }, - winsize: vaxis.Winsize, - mouse: vaxis.Mouse, - focus_in, - focus_out, - paste: []const u8, - paste_start, - paste_end, - lsp_done: struct { id: u32, rows: ?[]u8 }, - lsp_status: []u8, - pipe_done: selection_pipe.Response, - /// A streaming search's rows (pardes.Stream). - search_rows: pardes.Stream.Batch, - files_changed, - fs_ready, - /// A replica's connection, handed over by the daemon (Peers). - replica: daemon.Joining, - /// A replica's reader posted: the step boundary takes it in. - replica_mail, - /// A replica client's: what the session streamed (replica.Link). - said: replica.Said, - link_gone, - } = .nop; -}; -const Loop = vaxis.Loop(@TypeOf(Command.value)); - -fn startInput(loop: *Loop, sc: *Screen) !void { - if (comptime builtin.os.tag == .windows) return loop.start(); - if (sc.thread != null) return; - sc.thread = try loop.io.concurrent(inputThread, .{ loop, sc }); -} - -fn stopInput(io: std.Io, thread: *?std.Io.Future(void)) void { - if (thread.*) |*t| { - t.cancel(io); - thread.* = null; - } -} - -fn inputThread(loop: *Loop, sc: *Screen) void { - // vaxis's test terminal reads nothing off Linux: it has no read at all. - if (comptime !@hasDecl(vaxis.Tty, "read")) return; - inputReader(loop, &sc.tty, &sc.vx, &sc.feed); -} - -fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { - readInput(loop, tty, vx, feed) catch |err| { - if (err == error.Canceled) return; - std.log.err("terminal input: {s}", .{@errorName(err)}); - }; - (Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {}; -} - -fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { - const post: Poster = .{ .loop = loop, .view = feed.view }; - try post.postEvent(.{ .winsize = try tty.getWinsize() }); - var parser: vaxis.Parser = .{}; - var buf: [1024]u8 = undefined; - var carried: usize = 0; - while (true) { // stopInput cancels the task; the read then fails with Canceled - if (carried == buf.len) return error.InputSequenceTooLong; - const received = try tty.read(buf[carried..]); - if (received == 0) return; - // The terminal's answers to frames (FrameAck) come out first, - // wherever they sit: never events, and never glued to a key (an - // Escape pressed just before one would read as Alt on it). - const end = feed.ack.take(buf[0 .. carried + received], loop); - if (end == 0) { - carried = 0; - continue; - } - if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { - feed.shm_probing.store(false, .release); - feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); - // Answered either way: a terminal that could not read it left it. - var name_buf: [64]u8 = undefined; - if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} - }; - var parse_end = end; - var lead = end; - while (lead > 0 and buf[lead - 1] & 0xc0 == 0x80) lead -= 1; - if (lead > 0) { - const scalar_len = std.unicode.utf8ByteSequenceLength(buf[lead - 1]) catch 1; - if (scalar_len > end - (lead - 1)) parse_end = lead - 1; - } - var consumed: usize = 0; - // A read that is one ESC and nothing else is the Escape key: a - // terminal writes each key's sequence whole and ssh carries each of - // its writes whole, so no sequence arrives cut right after its ESC. - // Waiting on it cost every Escape press 50 ms on a legacy terminal - // (tmux, most ssh sessions), and 1 s before kitty's flags were on. - // (A terminal's answer to a frame is one write too: FrameAck.) - var waited = carried == 0 and end == 1; - while (consumed < parse_end) { - // A lone ESC that ends a longer read is the Escape key, or the - // first byte of a sequence whose rest the read boundary held - // back (an ssh packet, a busy link), which parsed now left the - // rest to be typed as text. Wait a moment for more. Under the - // kitty keyboard protocol Escape is `CSI 27 u`, so there the ESC - // can only start a sequence and the wait can be long. - const rest = buf[consumed..parse_end]; - // A frame's answer cut short by the read waits for its rest. - if (parse_end == end and rest.len > 1 and rest.len < FrameAck.answer.len and - std.mem.startsWith(u8, FrameAck.answer, rest)) break; - if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) { - waited = true; - if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break; - } - const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator); - if (result.n == 0) break; - consumed += result.n; - // A modifier pressed on its own, which the kitty keyboard - // protocol reports: pardes binds none, it would break a pending - // chord, and a shell pane was typed its private-use code. - if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue; - if (result.event) |event| - vaxis.loop.handleEventGeneric(post, vx, &feed.cache, @TypeOf(Command.value), event, vx.opts.system_clipboard_allocator) catch |err| { - if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); - return err; - }; - // The last answer to the startup queries is no event of its - // own: wake the loop so it takes the capabilities up (pollFrame) - // now. Left to the first key, that key paid for the full redraw - // they cost, and kitty's keys came in the legacy way till then. - if (result.event) |event| if (event == .cap_da1) { - _ = loop.tryPostEvent(.nop) catch {}; - }; - } - carried = end - consumed; - std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); - } -} - -/// One frame in flight at most. Each frame the tty draws ends with a device -/// status request (`CSI 5 n`), and no other frame is drawn until the -/// terminal's `CSI 0 n` comes back: over ssh the frames a burst of scrolling -/// or typing would queue behind each other (sshd's window holds megabytes) -/// are never drawn, and the burst ends one frame and one round trip after -/// its last input. On a local terminal the answer is back in well under a -/// millisecond. A terminal that never answers turns this off for good after -/// `timeout_ns`. -const FrameAck = struct { - const request = "\x1b[5n"; - const answer = "\x1b[0n"; - const timeout_ns: u64 = std.time.ns_per_s; - waiting: std.atomic.Value(bool) = .init(false), - off: std.atomic.Value(bool) = .init(false), - /// When the request went out (the loop's thread only). - sent_ns: u64 = 0, - - /// Take every answer out of `bytes`, closing up the rest; the new - /// length. The loop is woken for the frame that waited on one. - fn take(a: *FrameAck, bytes: []u8, loop: *Loop) usize { - var len = bytes.len; - var found = false; - while (std.mem.indexOf(u8, bytes[0..len], answer)) |at| { - std.mem.copyForwards(u8, bytes[at..], bytes[at + answer.len .. len]); - len -= answer.len; - found = true; - } - if (found and a.waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; - return len; - } - - /// Whether a new frame must wait (and the loop has a wake at the - /// timeout); past the timeout the terminal is taken to never answer. - fn holds(a: *FrameAck, now_ns: u64, io: std.Io) bool { - if (a.off.load(.acquire) or !a.waiting.load(.acquire)) return false; - const waited_ns = now_ns -| a.sent_ns; - if (waited_ns >= timeout_ns) { - a.off.store(true, .release); - a.waiting.store(false, .release); - return false; - } - requestWake(io, @intCast((timeout_ns - waited_ns + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); - return true; - } - - /// After a frame that wrote something: ask for the answer. - fn ask(a: *FrameAck, w: *std.Io.Writer, now_ns: u64) void { - if (a.off.load(.acquire)) return; - // Waiting before the request goes: a local terminal can answer - // before the write returns, and an answer nobody waited for is lost. - a.sent_ns = now_ns; - a.waiting.store(true, .release); - w.writeAll(request) catch return a.waiting.store(false, .release); - w.flush() catch return a.waiting.store(false, .release); - } -}; - -/// Whether more input is readable within `ms`, polled in short slices so -/// that a cancel of the input thread is still seen. A test reader answers -/// for itself. -fn inputFollows(tty: anytype, io: std.Io, ms: u32) !bool { - if (@hasDecl(@TypeOf(tty.*), "inputFollows")) return tty.inputFollows(ms); - const handle = if (@TypeOf(tty.fd) == std.Io.File) tty.fd.handle else tty.fd; - var fds = [_]posix.pollfd{.{ .fd = handle, .events = posix.POLL.IN, .revents = 0 }}; - var left = ms; - while (left > 0) : (left -|= 10) { - try io.checkCancel(); - if (try posix.poll(&fds, @intCast(@min(left, 10))) > 0) return true; - } - return false; -} - -test "terminal input preserves fragmented keys queries paste and text after EOF" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - vx.queries_done.store(false, .unordered); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - var reader: Reader = .{ .parts = &.{ - "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", - "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", - } }; - try readInput(&loop, &reader, &vx, &feed); - try std.testing.expect(vx.queries_done.load(.unordered)); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var resized = false; - var up = false; - var in_paste = false; - var pasted = false; - var clipboard = false; - var escape = false; - while (try loop.tryEvent()) |event| switch (event) { - .winsize => |size| { - try std.testing.expect(!resized); - resized = true; - try std.testing.expectEqual(@as(u16, 80), size.cols); - }, - .key_press => |key| { - try std.testing.expect(resized); - if (key.codepoint == vaxis.Key.up) { - up = true; - } else if (key.codepoint == vaxis.Key.escape) { - escape = true; - } else if (key.text) |bytes| { - if (in_paste) try std.testing.expect(up); - try text.appendSlice(gpa, bytes); - } else return error.UnexpectedInputKey; - }, - .paste_start => { - try std.testing.expect(up and !in_paste); - in_paste = true; - }, - .paste_end => { - try std.testing.expect(in_paste); - in_paste = false; - pasted = true; - }, - .paste => |bytes| { - defer gpa.free(@constCast(bytes)); - try std.testing.expect(pasted and !in_paste); - try std.testing.expectEqualStrings("clip", bytes); - clipboard = true; - }, - // The device attributes' wake (a capability answer). - .nop => try std.testing.expect(vx.queries_done.load(.unordered)), - else => return error.UnexpectedInputEvent, - }; - try std.testing.expectEqualStrings("plain café 界 😀tail", text.items); - try std.testing.expect(resized and up and pasted and clipboard and escape); -} - -test "terminal replies and malformed sequences never become typed text" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - vx.queries_done.store(false, .unordered); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - var reader: Reader = .{ - .parts = &.{ - // The startup width queries' answers where the terminal has no - // explicit width: both used to arrive as a bare F3, typed as text. - "a\x1b[1;1R\x1b[1;1R", - // A late report somewhere else on the screen, and DECXCPR. - "\x1b[12;40R\x1b[?3;7;1R", - // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`. - "b\x1b\x1b[A", - // A kitty graphics reply cut inside its ST sliced past its input. - "\x1b_Gi=1;OK\x1b", - "\\", - // An X10 mouse report cut after `CSI M` left three bytes as text. - "\x1b[M", - " !!", - // Malformed color and clipboard replies failed the parse, which - // ended input altogether; and a reply ended by BEL ran on to the - // next sequence's ESC, leaving what lay between as text. - "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07", - // Device reports whose fields end early. - "\x1b[?1;y\x1b[?997;n\x1b[c", - "\x1b[?62;c", - "c", - }, - }; - try readInput(&loop, &reader, &vx, &feed); - try std.testing.expect(vx.queries_done.load(.unordered)); - try std.testing.expect(vx.caps.kitty_graphics); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var alt_up = false; - var clicked = false; - while (try loop.tryEvent()) |event| switch (event) { - .winsize => {}, - .key_press => |key| { - if (key.codepoint == vaxis.Key.up and key.mods.alt) { - alt_up = true; - } else if (key.text) |bytes| { - try text.appendSlice(gpa, bytes); - } else return error.UnexpectedInputKey; - }, - .mouse => |mouse| { - try std.testing.expectEqual(@as(i16, 0), mouse.col); - clicked = true; - }, - .nop => {}, // the device attributes' wake - else => return error.UnexpectedInputEvent, - }; - try std.testing.expectEqualStrings("abc", text.items); - try std.testing.expect(alt_up and clicked); -} - -test "terminal input split at every byte with a gap reads as it does whole" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - // Two reads with `gap_ms` between them, as an ssh link delivers a - // sequence cut across two packets. - const Reader = struct { - parts: [2][]const u8, - gap_ms: u32, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), ms: u32) bool { - return self.next < self.parts.len and self.gap_ms <= ms; - } - fn read(self: *@This(), buf: []u8) !usize { - while (self.next < self.parts.len) { - const part = self.parts[self.next]; - self.next += 1; - if (part.len == 0) continue; - @memcpy(buf[0..part.len], part); - return part.len; - } - return 0; - } - /// What the loop was handed, one line per event. - fn events(l: *Loop, out: *std.ArrayList(u8)) !void { - out.clearRetainingCapacity(); - while (try l.tryEvent()) |event| switch (event) { - .winsize => {}, - .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }), - .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }), - .paste => |bytes| { - try out.print(std.testing.allocator, "paste {s}\n", .{bytes}); - std.testing.allocator.free(@constCast(bytes)); - }, - else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}), - }; - } - }; - const Case = struct { bytes: []const u8, kitty: bool = false }; - const cases = [_]Case{ - .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V - .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text - .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own - .{ .bytes = "\x1b[27u", .kitty = true }, // Escape - .{ .bytes = "\x1b[A" }, - .{ .bytes = "\x1bOA" }, - .{ .bytes = "\x1b[3;5~" }, - .{ .bytes = "\x1b\x1b[A" }, - // Four wheel notches: cut at a `;` with 60 ms between the halves, - // ssh's framing lost all four. - .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" }, - .{ .bytes = "\x1b[200~pasted\x1b[201~" }, - .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" }, - .{ .bytes = "\x1b_Gi=1;OK\x1b\\" }, - .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" }, - }; - var whole: std.ArrayList(u8) = .empty; - defer whole.deinit(gpa); - var split: std.ArrayList(u8) = .empty; - defer split.deinit(gpa); - for (cases) |case| { - vx.caps.kitty_keyboard = case.kitty; - const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); - defer gpa.free(all); - var one: Reader = .{ .parts = .{ all, "" }, .gap_ms = 0 }; - try readInput(&loop, &one, &vx, &feed); - try Reader.events(&loop, &whole); - for (1..all.len) |cut| { - // A cut just after an ESC is the one that has to wait, and a - // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut - // anywhere else is carried however long the gap. - const after_esc = all[cut - 1] == 0x1b; - var two: Reader = .{ .parts = .{ all[0..cut], all[cut..] }, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&loop, &two, &vx, &feed); - try Reader.events(&loop, &split); - std.testing.expectEqualStrings(whole.items, split.items) catch |err| { - std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); - return err; - }; - } - } - vx.caps.kitty_keyboard = false; -} - -test "an ESC read by itself is the Escape key at once" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - // More always follows at once: a reader that waited on the ESC would - // take `j` for the rest of its sequence (Alt-j). - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - asked: bool = false, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - self.asked = true; - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - for ([_]bool{ false, true }) |kitty| { - vx.caps.kitty_keyboard = kitty; - var reader: Reader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&loop, &reader, &vx, &feed); - try std.testing.expect(!reader.asked); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); - const escape = (try loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - const j = (try loop.tryEvent()).?.key_press; - try std.testing.expectEqual(@as(u21, 'j'), j.codepoint); - try std.testing.expect(!j.mods.alt); - try std.testing.expect(try loop.tryEvent() == null); - } - vx.caps.kitty_keyboard = false; -} - -test "a frame's answer is taken wherever the reads cut it, and never typed" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: [2][]const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - while (self.next < self.parts.len) { - const part = self.parts[self.next]; - self.next += 1; - if (part.len == 0) continue; - @memcpy(buf[0..part.len], part); - return part.len; - } - return 0; - } - }; - const all = "x" ++ FrameAck.answer ++ "y"; - defer feed.ack.waiting.store(false, .release); - for (0..all.len) |cut| { - feed.ack.waiting.store(true, .release); - var reader: Reader = .{ .parts = .{ all[0..cut], all[cut..] } }; - try readInput(&loop, &reader, &vx, &feed); - try std.testing.expect(!feed.ack.waiting.load(.acquire)); - var typed: std.ArrayList(u8) = .empty; - defer typed.deinit(gpa); - var woke = false; - while (try loop.tryEvent()) |event| switch (event) { - .winsize => {}, - .nop => woke = true, - .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey), - else => return error.UnexpectedInputEvent, - }; - std.testing.expectEqualStrings("xy", typed.items) catch |err| { - std.debug.print("cut at {d}\n", .{cut}); - return err; - }; - try std.testing.expect(woke); - } - // An Escape pressed just before an answer, in the same read, is the - // Escape key, not Alt on the answer. - feed.ack.waiting.store(true, .release); - var glued: Reader = .{ .parts = .{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&loop, &glued, &vx, &feed); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); - try std.testing.expectEqual(.nop, std.meta.activeTag((try loop.tryEvent()).?)); - const escape = (try loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - try std.testing.expectEqual(@as(u21, 'j'), (try loop.tryEvent()).?.key_press.codepoint); - try std.testing.expect(try loop.tryEvent() == null); -} - -test "a terminal that never answers a frame stops being asked after one timeout" { - const io = std.testing.io; - var ack: FrameAck = .{}; - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - const t0: u64 = 5 * std.time.ns_per_s; - ack.ask(&out.writer, t0); - try std.testing.expectEqualStrings(FrameAck.request, out.written()); - // Unanswered: the next frame waits, until the timeout. - try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); - try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); - try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); - // Then never again: no request, no wait. - out.clearRetainingCapacity(); - ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); - try std.testing.expectEqual(@as(usize, 0), out.written().len); - try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); -} - -test "terminal input cancellation joins blocked reads and queued EOF" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - const Reader = struct { - file: std.Io.File, - eof: bool, - entered: std.Io.Event = .unset, - release: std.Io.Event = .unset, - returned: std.Io.Event = .unset, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(_: *@This(), _: u32) bool { - return false; - } - fn read(self: *@This(), buf: []u8) !usize { - self.entered.set(std.testing.io); - if (self.eof) { - try self.release.wait(std.testing.io); - self.returned.set(std.testing.io); - return 0; - } - return self.file.readStreaming(std.testing.io, &.{buf}); - } - fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { - inputReader(loop, reader, vx_, feed); - } - }; - const Case = enum { blocked_read, cancel_eof, deliver_eof }; - for (std.enums.values(Case)) |case| { - const eof = case != .blocked_read; - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return error.PipeFailed; - defer _ = libc.close(fds[0]); - defer _ = libc.close(fds[1]); - var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &vx, &feed }); - defer stopInput(io, &thread); - try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); - try reader.entered.wait(io); - if (eof) { - for (0..512) |_| try loop.postEvent(.nop); - reader.release.set(io); - try reader.returned.wait(io); - } - if (case == .deliver_eof) { - try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); - thread.?.await(io); - } - stopInput(io, &thread); - try std.testing.expect(thread == null); - var count: usize = 0; - while (try loop.tryEvent()) |event| { - const expected: std.meta.Tag(@TypeOf(Command.value)) = if (case == .deliver_eof and count == 511) .quit else .nop; - try std.testing.expectEqual(expected, std.meta.activeTag(event)); - count += 1; - } - try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count); - } -} - -const PipeTasks = selection_pipe.Tasks; - -const Pty = struct { - file: std.Io.File, - pid: posix.pid_t, - reader: std.Io.Future(anyerror!void), - /// A command pane's child, watched to its exit (host_io.watchExit); - /// the pty stays open until both its end of file and its exit. - cmd: host_io.CommandWatch = .{}, -}; - -/// A watched child exited: wake the loop, which takes it (`takeExits`). -fn wakeForExit(ctx: ?*anyopaque) void { - const loop: *Loop = @ptrCast(@alignCast(ctx.?)); - _ = loop.tryPostEvent(.nop) catch {}; -} - -const KittyPlacement = struct { - cell_x: u16, - cell_y: u16, - cell_cols: u16, - cell_rows: u16, - options: vaxis.Image.DrawOptions, -}; - -fn terminalCellPixels(total_pixels: u16, cells: u16, fallback: u32) u32 { - if (total_pixels == 0 or cells == 0) return fallback; - return @max(1, @as(u32, total_pixels) / cells); -} - -fn updateCoreTerminalSize(core: *pardes.Pardes, cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) void { - core.update(.{ .resize = terminalSize(cols, rows, pixel_w, pixel_h) }); -} - -fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(pardes.Event, "resize") { - return .{ - .cols = cols, - .rows = rows, - .cell_pixels = .{ - .w = @intCast(terminalCellPixels(pixel_w, cols, 8)), - .h = @intCast(terminalCellPixels(pixel_h, rows, 16)), - }, - }; -} - -/// A terminal pane's image fragment (`native.exact`): its `src` into its -/// `dst`, inside one cell row. Kitty scales a source rectangle to whole -/// cells, so the source is trimmed to the cells' scale rather than the -/// picture stretched: a fragment loses under a cell at its right edge. -/// A full row is declared one row high; a part of one (an image's top or -/// bottom edge) only its columns, its height then following the source. -fn exactKittyPlacement( - place: pardes.ImagePlace, - screen_cols: u16, - screen_rows: u16, - screen_pixel_w: u16, - screen_pixel_h: u16, -) ?KittyPlacement { - if (comptime !pardes.pdf_enabled) return null; - const g = place.native.geometry orelse return null; - const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); - const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); - if (g.dst.w == 0 or g.dst.h == 0 or g.src.w == 0 or g.src.h == 0) return null; - const cell_x = g.dst.x / cell_w; - const pixel_x = g.dst.x % cell_w; - const pixel_y = @min(g.dst.y, cell_h - 1); - const cols: u32 = @max(1, (g.dst.w + cell_w / 2) / cell_w); - if (cell_x >= place.w) return null; - const declared_w = cols * cell_w; - // At the cells' scale, the source that fills `cols` cells. - var src_w = g.src.w; - if (declared_w < g.dst.w) src_w = @max(1, @as(u32, @intCast(@as(u64, g.src.w) * declared_w / g.dst.w))); - var src_h = g.src.h; - const full = g.dst.y == 0 and g.dst.h >= cell_h; - if (!full) { - // As tall as it is at that scale, and no taller than the row. - const room = cell_h - pixel_y; - const fits: u32 = @intCast(@as(u64, room) * src_w / declared_w); - if (fits == 0) return null; - src_h = @min(src_h, fits); - } - return .{ - .cell_x = std.math.cast(u16, cell_x) orelse return null, - .cell_y = 0, - .cell_cols = std.math.cast(u16, @min(@as(u32, place.w) - cell_x, (pixel_x + declared_w + cell_w - 1) / cell_w)) orelse return null, - .cell_rows = 1, - .options = .{ - .clip_region = .{ - .x = std.math.cast(u16, g.src.x) orelse return null, - .y = std.math.cast(u16, g.src.y) orelse return null, - .width = std.math.cast(u16, src_w) orelse return null, - .height = std.math.cast(u16, src_h) orelse return null, - }, - .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = @intCast(pixel_x), .y = @intCast(pixel_y) } else null, - // The outer terminal stacks them, under the text below 0. - .z_index = if (place.z != 0) place.z else null, - .size = if (full) - .{ .cols = std.math.cast(u16, cols) orelse return null, .rows = 1 } - else - .{ .cols = std.math.cast(u16, cols) orelse return null }, - }, - }; -} - -fn kittyPlacement( - place: pardes.ImagePlace, - screen_cols: u16, - screen_rows: u16, - screen_pixel_w: u16, - screen_pixel_h: u16, -) ?KittyPlacement { - if (comptime pardes.pdf_enabled) { - if (place.native.fit == .contain) return null; - const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); - const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); - const body_w = std.math.mul(u32, place.w, cell_w) catch return null; - const body_h = std.math.mul(u32, place.h, cell_h) catch return null; - const geometry = place.native.geometry orelse pardes.image.nativeGeometry( - place.iw, - place.ih, - body_w, - body_h, - place.native.fit, - place.native.pan_x, - place.native.pan_y, - ) orelse return null; - - const safe_rows_u32 = geometry.dst.h / cell_h; - if (safe_rows_u32 == 0) return null; - const safe_pixel_h = safe_rows_u32 * cell_h; - var safe_src_h: u32 = geometry.src.h; - var declared_cols: u32 = 0; - var declared_rows: u32 = 0; - switch (place.native.fit) { - .width => { - declared_cols = @intCast(@max( - @as(u64, 1), - (@as(u64, geometry.dst.w) + cell_w - 1) / cell_w, - )); - const declared_pixel_w = @as(u64, declared_cols) * cell_w; - const max_src_h: u32 = @intCast( - @as(u64, safe_pixel_h) * geometry.src.w / declared_pixel_w, - ); - if (max_src_h == 0) return null; - safe_src_h = @min(safe_src_h, max_src_h); - const aspect_pixel_h: u32 = @intCast( - (@as(u64, safe_src_h) * declared_pixel_w + geometry.src.w - 1) / - geometry.src.w, - ); - declared_rows = @intCast( - (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h, - ); - }, - .height => { - declared_rows = safe_rows_u32; - safe_src_h = @max(@as(u32, 1), @as(u32, @intCast( - @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h, - ))); - safe_src_h = @min(safe_src_h, geometry.src.h); - const aspect_pixel_w: u32 = @intCast( - (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) / - safe_src_h, - ); - declared_cols = @intCast( - (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w, - ); - }, - .contain => unreachable, - } - if (declared_rows == 0 or declared_rows > safe_rows_u32) return null; - - const src_x = std.math.cast(u16, geometry.src.x) orelse return null; - const src_y = std.math.cast(u16, geometry.src.y) orelse return null; - const src_w = std.math.cast(u16, geometry.src.w) orelse return null; - const src_h = std.math.cast(u16, safe_src_h) orelse return null; - const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null; - const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null; - if (cell_x >= place.w or cell_y >= place.h) return null; - const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null; - const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null; - const cell_cols = std.math.cast(u16, @min( - @as(u32, place.w - cell_x), - (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w, - )) orelse return null; - const cell_rows = std.math.cast(u16, @min( - @as(u32, place.h - cell_y), - (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h, - )) orelse return null; - if (cell_cols == 0 or cell_rows == 0) return null; - - return .{ - .cell_x = cell_x, - .cell_y = cell_y, - .cell_cols = cell_cols, - .cell_rows = cell_rows, - .options = .{ - .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h }, - .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null, - .size = switch (place.native.fit) { - .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, - .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, - .contain => unreachable, - }, - }, - }; - } else { - return null; - } -} - -test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { - if (comptime !pardes.pdf_enabled) return; - var place = pardes.ImagePlace{ - .pane = 0, - .serial = 3, - .native = .{ .page = 7, .exact = true, .geometry = .{ - .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, - .dst = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, - } }, - .x = 99, - .y = 4, - .w = 24, - .h = 1, - .rgba = &.{}, - .iw = 240, - .ih = 160, - }; - // 10x20 pixel cells: a whole row, one to one. - const full = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(u16, 0), full.cell_x); - try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows); - try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y); - try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width); - try std.testing.expect(full.options.pixel_offset == null); - - // The top of a letterboxed picture: 7 pixels down into the row, 13 - // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns - // only, its source no taller than the 13 pixels left in the row at - // that scale. - place.native.geometry = .{ - .src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }, - .dst = .{ .x = 35, .y = 7, .w = 205, .h = 13 }, - }; - const top = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(u16, 3), top.cell_x); - try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x); - try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y); - try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows); - const w = top.options.clip_region.?.width.?; - const h = top.options.clip_region.?.height.?; - try std.testing.expectEqual(@as(u16, 205), w); - try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13); - - // Narrower than its cells round to: the source is cut to their scale. - place.native.geometry = .{ - .src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }, - .dst = .{ .x = 0, .y = 0, .w = 204, .h = 20 }, - }; - const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?; - try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols); - try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width); -} - -test "Kitty PDF fragments never declare pixels beyond their clipped bottom" { - if (comptime !pardes.pdf_enabled) return; - - const base = pardes.ImagePlace{ - .pane = 0, - .serial = 1, - .native = .{ - .revision = 1, - .page = 0, - .fit = .width, - .geometry = .{ - .src = .{ .w = 96, .h = 10 }, - .dst = .{ .y = 195, .w = 304, .h = 29 }, - }, - }, - .x = 0, - .y = 0, - .w = 38, - .h = 14, - .rgba = &.{}, - .iw = 96, - .ih = 64, - }; - const width = kittyPlacement(base, 80, 16, 640, 256) orelse - return error.MissingSafeKittyWidthFragment; - const width_clip = width.options.clip_region.?; - const width_size = width.options.size.?; - try std.testing.expectEqual(@as(u16, 5), width_clip.height.?); - try std.testing.expectEqual(@as(u16, 38), width_size.cols.?); - try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y); - const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? + - width_clip.width.? - 1) / width_clip.width.?; - const inferred_rows = (aspect_pixels + 15) / 16; - try std.testing.expect(inferred_rows * 16 <= base.native.geometry.?.dst.h); - - var height = base; - height.native.fit = .height; - height.native.geometry.?.src.h = 9; - const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse - return error.MissingSafeKittyHeightFragment; - try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?); - try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <= - height.native.geometry.?.dst.h); - - height.native.geometry.?.dst.h = 13; - try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); -} - -test "host watch closes initial race and reloads rename-over PDF while idle" { - if (comptime !file_watch.supported or !pardes.pdf_enabled) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const original = try pardes.pdf.makeOutlineTestPdf(gpa); - defer gpa.free(original); - const replacement = try pardes.pdf.makeNoOutlineTestPdf(gpa); - defer gpa.free(replacement); - try tmp.dir.writeFile(io, .{ .sub_path = "live.pdf", .data = original }); - try tmp.dir.writeFile(io, .{ .sub_path = "initial.pdf", .data = replacement }); - try tmp.dir.writeFile(io, .{ .sub_path = "live-replacement.pdf", .data = original }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/live.pdf", .{tmp.sub_path}); - - const fd = file_watch.init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - var watches: file_watch.Table = @splat(null); - defer for (0..pardes.MAX_PANES) |id| file_watch.watchPane( - fd, - &watches, - @intCast(id), - null, - 0, - .{ .text = 0 }, - ); - - const core = try pardes.Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 }); - defer core.deinit(); - try std.testing.expectEqual(@as(usize, 3), core.panes[0].?.pdf.?.page_count); - - try tmp.dir.rename("initial.pdf", tmp.dir, "live.pdf", io); - var armed = false; - while (core.nextEffect()) |effect| switch (effect) { - .watch => |watch| if (watch.pane == 0 and watch.on) { - armed = true; - try std.testing.expect(!file_watch.applyEffect(core, io, fd, &watches, 0, true, watch.mode)); - }, - else => {}, - }; - try std.testing.expect(armed and watches[0] != null); - try std.testing.expectEqual(@as(usize, 1), core.panes[0].?.pdf.?.page_count); - - try tmp.dir.rename("live-replacement.pdf", tmp.dir, "live.pdf", io); - try std.testing.expect(file_watch.drain(fd)); - - try std.testing.expect(!file_watch.reloadChanged(core, io, gpa, &watches)); - const pane = core.panes[0].?; - try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count); - const disk_identity = try file_watch.identify(io, path); - switch (watches[0].?.generation) { - .pdf => |accepted| try std.testing.expect(accepted != null and accepted.?.eql(disk_identity)), - .text => return error.PdfWatchStoredTextGeneration, - } - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "reloaded") != null); - - core.native_images = true; - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const surface = try core.render(frame.allocator()); - try std.testing.expect(surface.nimages > 0); - try std.testing.expectEqual(@as(u32, 0), surface.images[0].?.native.page); -} - -fn kittyImageRepresentable(place: pardes.ImagePlace) bool { - return place.iw > 0 and place.ih > 0 and - place.iw <= std.math.maxInt(u16) and place.ih <= std.math.maxInt(u16); -} - -fn surfaceHasKittyKey(surface: *const pardes.Surface, key: pardes.ImageCacheKey) bool { - for (surface.images[0..surface.nimages]) |maybe| { - const place = maybe orelse continue; - if (comptime pardes.pdf_enabled) if (!kittyImageRepresentable(place)) continue; - if (place.cacheKey().eql(key)) return true; - } - return false; -} - -const PdfWheelTarget = struct { pane: usize, page: usize }; - -fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWheelTarget { - if (comptime !pardes.pdf_enabled) return null; - if (!core.native_images or mouse.type != .press or - (mouse.button != .wheel_up and mouse.button != .wheel_down) or - mouse.col < 0 or mouse.row < 0) return null; - const col: u16 = @intCast(mouse.col); - const row: u16 = @intCast(mouse.row); - for (core.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const rect = core.rects[id]; - if (col < rect.x or col >= rect.x + rect.w or - row < rect.y or row >= rect.y + rect.h) continue; - const page = pane.pdfPage() orelse return null; - return .{ .pane = id, .page = page }; - } - return null; -} - -/// Where a session's terminal comes from: /dev/tty, as a plain `pardes` -/// opens it; one open already (a session forked off its stub, -/// daemon.forkSession); or none, until one is attached (`--detach`). -/// The terminal a session starts on: /dev/tty, one its stub opened (an -/// upgraded session's is raw already, `termios` the cooked one), or none. -pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, none }; - -pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { - const io = init.io; - const gpa = init.gpa; - - var winch_set = posix.sigemptyset(); - posix.sigaddset(&winch_set, posix.SIG.WINCH); - // Kept by a daemon, a hangup is the terminal's end, not the session's: - // winchWatch takes it, and the session carries on detached. - if (daemon.link >= 0) posix.sigaddset(&winch_set, posix.SIG.HUP); - // FreeBSD drops a signal whose action is to be ignored (WINCH's - // default) as it is sent, sigwait or not: a handler keeps it. - if (comptime builtin.os.tag == .freebsd) - posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); - posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); - - var tty_buf: [0x10000]u8 = undefined; - var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; - defer screen.kitty.deinit(); - switch (term) { - .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), - .fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)), - .none => {}, - } - defer screen.leave(); - - var paste_buf: std.Io.Writer.Allocating = .init(gpa); - defer paste_buf.deinit(); - var loop: Loop = .init(io, &screen.tty, &screen.vx); - - try localSession(init, opts, &screen, &loop, &paste_buf); -} - -/// A replica client's link to its session (`remote`), drawn here. -const Remote = struct { - link: replica.Link, - - /// The client's own view drawn on its terminal, outside any step: the - /// replica's digest stays the session's (views.drawOne). What the host - /// writes in the core as it presents (a frame skipped, one owed) is put - /// back, as the frame statistics are this process's. - fn draw(c: *Remote, s: *Shell) void { - const r = c.link.r; - const core = r.core(); - const skipped = core.present_skipped; - const needs = core.needs_frame; - core.frames.mark_start = pardes.FrameStats.nowNs(); - core.frames.mark_update = core.frames.mark_start; - r.draw(.{ .ctx = s, .f = Shell.present }); - core.frames.mark_render = core.frames.mark_update; - const drew = core.frames.bytes > 0; - c.link.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), false, c.link.owed); - core.present_skipped = skipped; - core.needs_frame = needs; - c.link.drawn(drew); - } -}; - -/// The session's stream, onto the loop: its units, and its end. -fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void { - defer done.store(true, .release); - const Post = struct { - fn post(l: *Loop, said: replica.Said) bool { - l.postEvent(.{ .said = said }) catch return false; - return true; - } - }; - replica.readLink(gpa, fd, rest, loop, Post.post); - loop.postEvent(.link_gone) catch {}; -} - -/// `pardes --attach=:` (and `:`, through -/// ssh, main.zig): this terminal a replica client of a session elsewhere -/// (docs/next-daemon.md, "Phase 5 part B notes"). Its own core, loaded -/// from the session's dump, applies its keys at once (src/replica.zig); -/// the session's units are the truth it rolls back to. Its own view of the -/// session is drawn here, as the session draws its terminals'. -pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far_link: bool) !void { - const io = init.io; - const gpa = init.gpa; - const Said = struct { - fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { - var said: [800]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&said, "pardes: --attach: " ++ fmt ++ "\n", args) catch "pardes: --attach failed\n") catch {}; - std.process.exit(1); - } - }; - var why: [600]u8 = @splat(0); - // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash, - // those it holds kept from the link, and its stream in zstd. A client - // on this machine's own socket is sent the dump whole, as before: a - // hash and a compression there cost more than the bytes. - const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else far_link; - var have_store: replica.Have = if (far) .init(io) else .{ .io = io }; - defer have_store.deinit(); - const have: ?*replica.Have = if (far) &have_store else null; - var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - var joined = replica.dial(gpa, path, session, &why, have, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words}); - - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.image.start(io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.stop(); - } - var o = opts; - o.image_allocator = allocs.image; - o.pdf_allocator = allocs.pdf; - var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - // Its join's time, the dial and the load (PARDES_REPLICA_STATS). - var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); - - var winch_set = posix.sigemptyset(); - posix.sigaddset(&winch_set, posix.SIG.WINCH); - // A hangup ends it the normal way (`quit`), what it made kept on disk - // (`Have.keep`) and its ssh forward's socket unlinked (main.zig). - posix.sigaddset(&winch_set, posix.SIG.HUP); - hangup_quits = true; - if (comptime builtin.os.tag == .freebsd) - posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); - posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); - var tty_buf: [0x10000]u8 = undefined; - var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; - defer screen.kitty.deinit(); - try screen.enter(try vaxis.Tty.init(io, &tty_buf)); - defer screen.leave(); - defer screen.glide.deinit(gpa); - var paste_buf: std.Io.Writer.Allocating = .init(gpa); - defer paste_buf.deinit(); - var loop: Loop = .init(io, &screen.tty, &screen.vx); - var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); - defer frame_arena.deinit(); - var remote_link: Remote = .{ .link = .{ .r = r, .fd = joined.fd } }; - const link = &remote_link.link; - try link.fromEnv(gpa, init.environ_map); - defer link.deinit(gpa); - var sh: Shell = .{ - .io = io, - .gpa = gpa, - .lsp_gpa = allocs.lsp, - .core = r.core(), - .prompt_rcs = undefined, - .loop = &loop, - .frame = &frame_arena, - .paste_buf = &paste_buf, - .inotify_fd = -1, - .from = joined.view, - .remote = &remote_link, - }; - - try startInput(&loop, &screen); - defer stopInput(io, &screen.thread); - (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); - (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach(); - try screen.vx.queryTerminalSend(screen.tty.writer()); - // A join a pass: the first, and one after the replica diverged or the - // session let it go to upgrade. The terminal stays as it is. - while (true) { - r.gmtoff = joined.gmtoff; - sh.core = r.core(); - sh.from = joined.view; - sh.terms = @splat(null); - sh.terms[joined.view] = &screen; - screen.feed.view = joined.view; - link.reset(r, joined.fd); - link.joinedAs(&joined, dial_ms); - var reader_done: std.atomic.Value(bool) = .init(false); - const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); - // What it is, then its size, are its view's first inputs. - link.input(.{ .frontend = .{ .windowed = false } }); - screen.size = null; - sh.winched(); - screen.vx.queueRefresh(); - while (!link.quit) { - // Its predicted echo judged and caught up, once a frame. - if (r.echoFrame()) link.dirty = true; - if (link.dirty) remote_link.draw(&sh); - const first = (loop.tryEvent() catch null) orelse idle: { - // Idle, its frame drawn: the next key needs no copy taken. - r.ready(); - break :idle loop.nextEvent() catch break; - }; - var ev = first; - var batch: usize = 1; - while (true) { - _ = sh.apply(ev); - if (link.quit or (!sh.in_paste and batch >= 64)) break; - ev = (loop.tryEvent() catch null) orelse break; - batch += 1; - } - r.settle(); - if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { - screen.caps_pending = false; - screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; - screen.vx.queueRefresh(); - link.dirty = true; - } - if (link.owed or r.echo.changed) link.dirty = true; - // Predictions out: judged a frame at a time while they are. - if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms)); - if (link.quietCheck()) |ms| requestWake(io, ms); - if (r.diverged != null) link.quit = true; - } - if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(joined.fd, r.diverged != null); - // The link's reader ends with the link, posting as it goes: what it - // and the terminal posted is let go until it has. Its end is read - // before the drain, not after: its last post (`link_gone`) comes - // just before it, and left queued it ended the next link at once. - _ = libc.shutdown(joined.fd, 2); - while (true) { - const ended = reader_done.load(.acquire); - while (loop.tryEvent() catch null) |ev| switch (ev) { - .said => |said| switch (said) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), - .checked => {}, - }, - .paste => |b| gpa.free(@constCast(b)), - else => {}, - }; - if (ended) break; - std.Thread.yield() catch {}; - } - reader.join(); - _ = libc.close(joined.fd); - joined.rest.deinit(gpa); - // Why it joins again, in a line over its frame until a key. - if (!link.rejoins()) { - // What it made since it joined, kept for its next start. - if (have) |h| h.keep(r.core()); - r.deinit(); - if (link.gone) { - screen.leave(); - Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session}); - } - return; - } - // The session again, the core it leaves held meanwhile: its blobs - // are not sent again. - if (have) |h| h.leaving(r.core()); - dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - joined = replica.Link.redial(gpa, path, session, &why, have, r.diverged == null, joined.view) orelse { - screen.leave(); - Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)}); - }; - if (have) |h| h.left(); - r.deinit(); - r = replica.Link.load(gpa, &joined, o, &why, have) orelse { - screen.leave(); - Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - }; - dial_ms = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); - } -} - - -/// A terminal a session draws on, while it has one: entered (raw, the -/// alternate screen, mouse and paste reports) and left (all of it put back, -/// the terminal closed) at the session's start and end, and at a detach and -/// a reattach in between (daemon.zig). One a view (views.zig): the session's -/// own (`primary`, its stub `daemon.stub`), and one more for each terminal -/// `pardes --attach`ed while it is attached, which keeps its own. -const Screen = struct { - io: std.Io, - gpa: std.mem.Allocator, - env: *std.process.Environ.Map, - buf: []u8, - tty: vaxis.Tty = undefined, - vx: vaxis.Vaxis = undefined, - on: bool = false, - primary: bool = false, - /// The pipe to its stub, an attached one's (the primary's is daemon.stub). - stub: posix.fd_t = -1, - /// Its slot in Killed. - killed: ?usize = null, - feed: Feed = .{}, - thread: ?std.Io.Future(void) = null, - kitty: std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), - caps_pending: bool = true, - /// Its size as last taken (`Shell.resized`). - size: ?vaxis.Winsize = null, - tracks: []const pardes.animation.Track = &.{}, - /// T2: the cursor's jump trail (JumpTrail). - trail: JumpTrail = .{}, - /// The view's glide, the GUI's motion drawn at whole rows (anim 12). - glide: pardes.glide.Glide = .{}, - /// T7: when each pane's view last moved (ThumbFlash). - flash: ThumbFlash = .{}, - - /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a - /// forked session is no controlling terminal of its, which /dev/tty is. - /// An upgraded session's is raw already, `cooked` what it goes back to. - fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t, cooked: ?posix.termios) !vaxis.Tty { - if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty - const termios = cooked orelse try vaxis.Tty.makeRaw(fd); - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) }; - } - - fn enter(sc: *Screen, tty: vaxis.Tty) !void { - sc.tty = tty; - errdefer sc.tty.deinit(); - sc.vx = try vaxis.init(sc.io, sc.gpa, sc.env, .{ .system_clipboard_allocator = sc.gpa }); - errdefer sc.vx.deinit(sc.gpa, sc.tty.writer()); - try sc.vx.enterAltScreen(sc.tty.writer()); - try sc.vx.setMouseMode(sc.tty.writer(), true); - try sc.vx.setBracketedPaste(sc.tty.writer(), true); - if (comptime !builtin.is_test) { - sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios); - // What a panic puts back (vaxis.recover). - if (sc.primary) vaxis.tty.global_tty = sc.tty; - } - const view = sc.feed.view; - sc.feed = .{ .view = view }; - sc.caps_pending = true; - sc.size = null; - sc.on = true; - } - - fn leave(sc: *Screen) void { - if (!sc.on) return; - sc.on = false; - if (sc.killed) |slot| Killed.disarm(slot); - sc.killed = null; - clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); - sc.vx.exitAltScreen(sc.tty.writer()) catch {}; - sc.vx.deinit(sc.gpa, sc.tty.writer()); - if (comptime !builtin.is_test) if (sc.primary) { - vaxis.tty.global_tty = null; - }; - sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets - } - - /// Its stub told the terminal is detached (it ends, and its shell has - /// the terminal back). - fn sayDetached(sc: *Screen) void { - if (sc.primary) return daemon.tellStubDetached(); - daemon.tellDetached(sc.stub); - sc.stub = -1; - } - - /// Its terminal hung up, or the stub that waits on it is gone. - fn hungUp(sc: *const Screen) bool { - const stub = if (sc.primary) daemon.stub else sc.stub; - const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd; - var fds = [_]posix.pollfd{ - .{ .fd = handle, .events = 0, .revents = 0 }, - .{ .fd = stub, .events = 0, .revents = 0 }, - }; - _ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false; - const gone = posix.POLL.HUP | posix.POLL.ERR; - return fds[0].revents & gone != 0 or (stub >= 0 and fds[1].revents & gone != 0); - } - - fn setStub(sc: *Screen, fd: posix.fd_t) void { - if (sc.primary) daemon.stub = fd else sc.stub = fd; - } -}; - -/// SIGTERM or SIGHUP: each terminal put back as a clean exit leaves it -- -/// the main screen, no mouse, paste or keyboard modes, the cursor shown, -/// cooked termios -- and then the signal's own death. A nested editor -/// killed in a pane must not leave that pane's terminal wedged. -/// Async-signal-safe: write, tcsetattr, sigaction, raise. -const Killed = struct { - var fds: [pardes.views.max]posix.fd_t = @splat(-1); - var cooked: [pardes.views.max]posix.termios = undefined; - const reset = "\x1b[= 0) { - _ = std.c.write(fd, reset, reset.len); - _ = std.c.tcsetattr(fd, .FLUSH, termios); - }; - // The 9P socket and private prompt files go too: a killed editor - // leaves none behind. Its shells too, the daemon's dups let go. - ninep_io.unlinkOwnSocket(); - host_io.Shell.unlinkOwnedRcs(); - daemon.hangUp(); - // SA_RESETHAND put the default back: the same signal, now fatal. - _ = std.c.raise(sig); - } -}; - -fn localSession( - init: std.process.Init, - opts: pardes.Options, - screen: *Screen, - loop: *Loop, - paste_buf: *std.Io.Writer.Allocating, -) !void { - const io = init.io; - const gpa = init.gpa; - - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - var options = opts; - options.image_allocator = allocs.image; - options.pdf_allocator = allocs.pdf; - options.tree_sitter_allocator = allocs.tree_sitter; - options.frame_allocator = allocs.frame; - - pardes.image.start(io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - // Pages render on lanes off the loop (pdf_view.workers). - if (comptime pardes.pdf_enabled) pardes.panes.Pdf.workers = io; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.panes.Pdf.dropKept(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.stop(); - } - - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, options, rec) - else if (options.load_path) |lp| blk: { - const bytes = try filesystem.readFile(gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); - } else try pardes.Pardes.init(allocs.pardes, options); - defer core.deinit(); - - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); - - var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); - defer frame_arena.deinit(); - - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); - - var sh: Shell = .{ - .io = io, - .gpa = gpa, - .lsp_gpa = allocs.lsp, - .core = core, - .prompt_rcs = &prompt_rcs, - .loop = loop, - .frame = &frame_arena, - .paste_buf = paste_buf, - .inotify_fd = file_watch.init(false), - .fs = fs, - .test_clock = host_io.testClock(), - }; - sh.terms[0] = screen; - sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica }; - defer sh.peers.deinit(); - // Before the core goes: each client sees its link end. - defer sh.peers.dropAll(sh.core); - pardes.lsp.setStatusSink(&sh, lspStatusSink); - host_io.setExitWake(loop, wakeForExit); - defer screen.glide.deinit(gpa); - // The terminals of the other views end with the session: each put back, - // its stub told. - defer for (&sh.terms) |*slot| if (slot.*) |sc| if (!sc.primary) { - stopInput(io, &sc.thread); - sh.dropScreen(sc, .exit); - slot.* = null; - }; - defer { - host_io.setExitWake(null, null); - pardes.lsp.setStatusSink(null, null); - for (&sh.ptys) |*slot| if (slot.*) |*pt| { - pt.reader.cancel(io) catch {}; - _ = libc.close(pt.file.handle); - slot.* = null; - }; - for (sh.adoptions[0..sh.adoptions_len]) |a| _ = libc.close(a.fd); - if (sh.lsp_task) |*t| { - t.future.cancel(io); - sh.lsp_task = null; - } - sh.pipe_tasks.cancelAll(io); - // Its worker may be waiting on the loop's queue for room. - core.stream.cancelTask(); - file_watch.stop(sh.inotify_fd); - if (sh.watch_task) |*t| { - t.cancel(io) catch {}; - sh.watch_task = null; - } - if (sh.inotify_fd >= 0) { - _ = libc.close(sh.inotify_fd); - sh.inotify_fd = -1; - } - while (loop.tryEvent() catch null) |ev| switch (ev) { - .pty_read => |pr| { - tookRead(io, pr.id); - gpa.free(pr.bytes); - }, - .paste => |b| gpa.free(@constCast(b)), - .lsp_done => |d| if (d.rows) |rows| allocs.lsp.free(rows), - .lsp_status => |text| allocs.lsp.free(text), - .pipe_done => |response_value| { - var response = response_value; - response.deinit(gpa); - }, - .search_rows => |b| b.deinit(gpa), - .attach => |a| { - _ = libc.close(a.tty); - if (a.stub >= 0) _ = libc.close(a.stub); - }, - .adopted => |a| _ = libc.close(a.fd), - else => {}, - }; - } - const host = sh.host(); - - core.host = host; - // An upgraded session's terminals, its own again. - if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen); - // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). - sh.setAttended(sh.attached()); - while (core.nextEffect()) |effect| core.perform(effect); - // ...and its shells, once a fresh session's own has a directory to - // adopt them in. - if (upgrade.resumed) |*rec| { - sh.resumePtys(rec); - while (core.nextEffect()) |effect| core.perform(effect); - } - - if (screen.on) try startInput(loop, screen); - defer stopInput(io, &screen.thread); - (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); - (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); - if (fs) |f| try f.watch(loop, wakeFs); - if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); - // Detached from the start, nothing else may wake the first wait. - if (!screen.on) daemon.watch(loop, deliverNote); - // PARDES_TEST_VIEWS: the terminals at these paths are views of the - // session too, from its start, as `pardes --attach`ed ones are (the - // snapshot harness's `start ... views=N`). - if (upgrade.resumed == null) if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { - var it = std.mem.tokenizeScalar(u8, paths, ' '); - while (it.next()) |path| { - var path_buf: [256]u8 = undefined; - const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue; - const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0)); - if (fd >= 0) sh.attachTerminal(fd, -1, null); - } - }; - - sh.threads_ok = true; - for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try io.concurrent(readPty, .{ io, gpa, pt.file, id, sh.gens[id], loop }); - }; - if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; - - defer unlinkKittyShm(); - while (!core.quit) { - pardes.turn.bump(&pardes.turn.restores); - try core.pump(host); - // Its unit to each replica client, and theirs taken in. - sh.peers.boundary(core); - upgrade.locate(); - // Asked in the step (the word), done between steps: the session whole. - if (sh.upgrade_asked) |pane| sh.upgradeNow(pane); - // A terminal (`pardes --attach`) or an adopted shell, handed on by - // the daemon's thread to this loop; started after the first frame, - // off a startup's way. - daemon.watch(loop, deliverNote); - if (core.takeRestore()) |rp| blk: { - // ponytail: a Restore replaces the core its clients replicate; - // they are let go, and attach again. - sh.peers.dropAll(core); - const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { - core.reportError(core.active, "Restore", err); - break :blk; - }; - defer gpa.free(bytes); - const nc = dump.restore(core, bytes, rp) catch |err| { - core.reportError(core.active, "Restore", err); - break :blk; - }; - if (sh.lsp_task) |*task| { - task.future.cancel(io); - sh.lsp_task = null; - } - sh.pipe_tasks.cancelAll(io); - for (&sh.gens) |*generation| generation.* +%= 1; - for (&sh.ptys) |*slot| if (slot.*) |*pt| { - pt.reader.cancel(io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - slot.* = null; - }; - for (0..pardes.MAX_PANES) |wid| file_watch.watchPane( - sh.inotify_fd, - &sh.watches, - @intCast(wid), - null, - 0, - .{ .text = 0 }, - ); - _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); - // ponytail: a restored session is one view, the live one's - // terminal: the others are let go, as a detach of each. - const live = sh.term().?; - for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) { - stopInput(io, &sc.thread); - sh.dropScreen(sc, .detach); - slot.* = null; - }; - sh.terms = @splat(null); - sh.terms[0] = live; - stopInput(io, &live.thread); - live.feed.view = 0; - sh.from = 0; - if (live.on) startInput(loop, live) catch {}; - if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); - nc.native_images = live.on and live.vx.caps.kitty_graphics; - nc.unattended = !live.on; - sh.peers.alone_unattended = !live.on; - if (fs) |f| f.reset(nc); - core.deinit(); - core = nc; - sh.core = nc; - if (comptime pardes.pdf_enabled) if (live.on) { - updateCoreTerminalSize(core, live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix); - }; - } - } - if (fs) |f| { - f.deinit(gpa); - fs = null; - sh.fs = null; - } -} - -fn clearNativeImages( - kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), - vx: *vaxis.Vaxis, - tty: *vaxis.Tty, -) void { - var iterator = kitty_handles.valueIterator(); - while (iterator.next()) |handle| vx.freeImage(tty.writer(), handle.id); - kitty_handles.clearRetainingCapacity(); -} - -const Adoption = struct { pid: posix.pid_t, fd: posix.fd_t, pane: ?u8 }; - -/// The daemon's thread: what it says, onto the loop's queue. -fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const loop: *Loop = @ptrCast(@alignCast(ctx)); - switch (note) { - .attach => |a| if (a.tty < 0) { - if (a.stub >= 0) daemon.refuseStub(a.stub, "a terminal session takes a terminal"); - } else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch { - _ = libc.close(a.tty); - _ = libc.close(a.stub); - }, - .adopted => |a| { - for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch { - _ = libc.close(fd); - }; - loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {}; - }, - .replica => |j| loop.postEvent(.{ .replica = j }) catch { - _ = libc.close(j.fd); - }, - } -} - -/// A replica reader's post: the session's wait ends, and its step -/// boundary takes the post in. -fn wakeForReplica(ctx: ?*anyopaque) void { - const loop: *Loop = @ptrCast(@alignCast(ctx.?)); - // Never waits: a full queue wakes the loop anyway, and a reader the - // loop is joining (a client let go) must not wait on it. - _ = loop.tryPostEvent(.replica_mail) catch {}; -} - -const Shell = struct { - io: std.Io, - gpa: std.mem.Allocator, - lsp_gpa: std.mem.Allocator, - core: *pardes.Pardes, - prompt_rcs: *const host_io.Shell.PromptFiles, - loop: *Loop, - /// Each view's terminal, by view (views.zig): the session's own first; - /// none in tests. - terms: [pardes.views.max]?*Screen = @splat(null), - /// The view the input taken now is from (`Command.value.from`). - from: u8 = 0, - frame: *std.heap.ArenaAllocator, - paste_buf: *std.Io.Writer.Allocating, - inotify_fd: c_int, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: [pardes.MAX_PANES]Adoption = undefined, - adoptions_len: usize = 0, - adopted: usize = 0, - fs: ?*ninep_io.Listener = null, - ptys: [pardes.MAX_PANES]?Pty = @splat(null), - gens: [pardes.MAX_PANES]u32 = @splat(0), - watches: file_watch.Table = @splat(null), - watch_task: ?std.Io.Future(anyerror!void) = null, - lsp_task: ?host_io.Lsp.Task = null, - pipe_tasks: PipeTasks = .{}, - threads_ok: bool = false, - check_files: bool = false, - // ponytail: one bracketed paste at a time for every terminal: keys - // another terminal sends while one pastes join its paste. - in_paste: bool = false, - /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the - /// running-out wait moves it: the core's next wake. - test_clock: ?u64 = null, - /// The tick the last paced frame was due at (waitInput), and whether - /// this wait read an input (its frame is drawn at once). - pace_ns: u64 = 0, - input_seen: bool = false, - wake_to: u64 = 0, - /// waitInput's pacing of output: whether this wait read a pane's output, - /// and when the last frame was written, the last input was read and the - /// focused pane's output last was. - output_seen: bool = false, - drawn_ns: u64 = 0, - input_ns: u64 = 0, - focused_ns: u64 = 0, - /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). - upgrade_asked: ?u8 = null, - /// Its pty readers stopped for it: their end of file is not a shell's. - upgrading: bool = false, - /// The session's replica clients (src/replica.zig), on sockets. - peers: replica.Peers = .{}, - /// This wait took only a replica's post (its input, its join): the - /// pump after it reads no new time, so it moves nothing the replicas' - /// speculations stand on (a replica takes such a unit as is). - mail_only: bool = false, - waited: bool = false, - /// This wait's steps so far, and the input held for the next (`split`). - took_input: bool = false, - took_output: bool = false, - held: ?@TypeOf(Command.value) = null, - /// This process a replica client of a session elsewhere (`remote`): - /// its inputs go to the replica, never straight to the core. - remote: ?*Remote = null, - - const Leaving = enum { detach, exit }; - - /// A terminal's input, to the core, or to a replica client's engine - /// (applied at once there, and sent to the session). - fn feed(s: *Shell, ev: pardes.Event) void { - const c = s.remote orelse return s.core.update(ev); - c.link.input(ev); - } - - /// Whether a terminal of this process's shows the session, or - /// nothing (a test) can. - fn local(s: *const Shell) bool { - for (s.terms) |slot| if (slot != null) return true; - return false; - } - - /// Whether anyone looks at the session: a terminal here, or a replica - /// client (Peers keeps it attended while one is there). - fn setAttended(s: *Shell, on: bool) void { - s.peers.alone_unattended = !on; - s.core.unattended = !on and s.peers.count() == 0; - } - - fn of(ctx: ?*anyopaque) *Shell { - return @ptrCast(@alignCast(ctx.?)); - } - - fn host(s: *Shell) host_io.Host { - return .{ .ctx = s, .vtable = if (comptime pardes.isolated) &isolated_vtable else &vtable }; - } - - const isolated_vtable: host_io.Host.VTable = .{ - .wait_input = waitInput, - .now = clockNow, - .present = present, - .post_present = postPresent, - .poll_frame = stepGlide, - }; - - const vtable: host_io.Host.VTable = .{ - .wait_input = waitInput, - .now = clockNow, - .present = present, - .post_present = postPresent, - .poll_frame = pollFrame, - .watched = watched, - .detach = detach, - .adopt = adopt, - .upgrade = upgradeAsked, - .newer_build = newerBuild, - .spawn = spawn, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePty, - .tty_taken = ttyTaken, - .fg_name = fgName, - .kill_job = killJob, - .write_file = writeFile, - .write_dump = writeDump, - .watch_file = watchFile, - .watch_theme = watchTheme, - .dump_themes = dumpThemes, - .set_clipboard = setClipboard, - .read_clipboard = readClipboard, - .open_link = openLink, - .lsp = lsp, - .pipe = pipe, - .search = search, - }; - - fn clockNow(ctx: ?*anyopaque) u64 { - const s = of(ctx); - if (s.waited) { - s.waited = false; - if (s.mail_only and s.peers.count() > 0 and s.core.clock_started) return s.core.now_ns; - } - return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - } - - /// The live view's terminal (null in tests). - fn term(s: *const Shell) ?*Screen { - return s.terms[s.core.view]; - } - - fn attached(s: *const Shell) bool { - const screen = s.term() orelse return true; - return screen.on; - } - - /// Drawn only while a terminal shows it: a replica client's view live - /// (its input the last), whichever terminal here shows another. - fn watched(ctx: ?*anyopaque) bool { - const s = of(ctx); - if (s.term() == null and s.local()) { - for (s.terms) |slot| if (slot) |sc| if (sc.on) return true; - return false; - } - return s.attached(); - } - - /// Detach: the terminal put back and let go, the stub told (it ends, - /// and the shell has its terminal again), the session left running. - fn detach(ctx: ?*anyopaque) void { - const s = of(ctx); - // A replica client's: its link ends. - if (s.peers.detach(s.core.view)) return; - if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached"); - // One of several: its view goes, and the session stays on the rest. - if (pardes.views.count(s.core) > 1) return s.dropView(s.core.view, .detach); - if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session (it is its terminal's job)"); - s.leaveTerminal(); - } - - /// View `k`'s terminal let go (detached, or gone) while others stay: the - /// view goes with it. - fn dropView(s: *Shell, k: u8, how: Leaving) void { - const sc = s.terms[k] orelse return; - stopInput(s.io, &sc.thread); - s.terms[k] = null; - s.core.closeView(k); - s.dropScreen(sc, how); - } - - /// A terminal put back and its stub told; an attached one's Screen freed - /// (the session's own stays, a view of none). - fn dropScreen(s: *Shell, sc: *Screen, how: Leaving) void { - if (sc.primary) { - sc.leave(); - return sc.sayDetached(); - } - sc.leave(); - switch (how) { - .detach => sc.sayDetached(), - .exit => { - daemon.tellExit(sc.stub, 0); - sc.stub = -1; - }, - } - sc.glide.deinit(s.gpa); - sc.kitty.deinit(); - s.gpa.free(sc.buf); - s.gpa.destroy(sc); - } - - fn leaveTerminal(s: *Shell) void { - const screen = s.term() orelse return; - stopInput(s.io, &screen.thread); - screen.leave(); - s.core.native_images = false; - s.setAttended(false); - // The stub's stdin, stdout and stderr were its terminal too. - const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); - if (null_fd >= 0) { - for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); - if (null_fd > 2) _ = libc.close(null_fd); - } - screen.sayDetached(); - daemon.setState(true); - } - - /// `pardes --attach`'s terminal: for a detached session its own again, - /// entered as the first one was; for one attached already, a view of - /// its own (views.zig). Sized, asked what it can do, and drawn whole. - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - // A replica client's view live (its input the last) has no terminal - // here: the session's own is the one a terminal takes, or joins. - const live = s.term() orelse for (s.terms) |slot| { - if (slot) |sc| if (sc.primary) break sc; - } else { - _ = libc.close(fd); - return refuse(stub, "that session has no terminal of its own to attach to"); - }; - const screen = if (!live.on) live else extra: { - const sc = s.gpa.create(Screen) catch break :extra null; - const buf = s.gpa.alloc(u8, 0x10000) catch { - s.gpa.destroy(sc); - break :extra null; - }; - sc.* = .{ .io = s.io, .gpa = s.gpa, .env = live.env, .buf = buf, .kitty = .init(s.gpa) }; - break :extra sc; - } orelse { - _ = libc.close(fd); - return refuse(stub, "that session has no room for another terminal"); - }; - const extra = screen != live; - const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { - _ = libc.close(fd); - if (extra) s.freeScreen(screen) else daemon.setState(true); - return refuse(stub, "that terminal would not go raw"); - }; - screen.enter(tty) catch { - if (extra) s.freeScreen(screen) else daemon.setState(true); - return refuse(stub, "that terminal would not take the screen"); - }; - if (extra) { - const k = s.core.openView() orelse { - screen.leave(); - s.freeScreen(screen); - return refuse(stub, "that session has as many terminals as it takes"); - }; - screen.feed.view = k; - s.terms[k] = screen; - } - screen.setStub(stub); - s.setAttended(true); - startInput(s.loop, screen) catch {}; - screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; - s.core.needs_frame = true; - daemon.setState(false); - } - - fn freeScreen(s: *Shell, sc: *Screen) void { - sc.kitty.deinit(); - s.gpa.free(sc.buf); - s.gpa.destroy(sc); - } - - /// A terminal refused: its stub told why (a test's has none). - fn refuse(stub: posix.fd_t, why: []const u8) void { - if (stub >= 0) daemon.refuseStub(stub, why); - } - - /// Adopt: the daemon is asked for the shells of sessions that died - /// holding them; each comes back (`adopted`) as a terminal pane here. - fn adopt(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); - s.adopted = 0; - daemon.adopt(); - } - - /// 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).remote == null and upgrade.newer(); - } - - fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place"); - s.upgrade_asked = pane; - } - - /// Upgrade, between steps: this process exec'd as the pardes now at the - /// path it was started from, the session in its dump, and its ptys, - /// terminals, stubs and daemon link kept open across (upgrade.zig). - /// Returns only when it could not be, the session going on as it was. - fn upgradeNow(s: *Shell, pane: u8) void { - if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty - s.upgrade_asked = null; - const core = s.core; - var why: [800]u8 = undefined; - const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from"); - // 9P is served while the new binary is asked (its clients' clunks - // and reads after the word are answered), and not after. - pardes.turn.rest(); - const checked = upgrade.check(path, &why); - pardes.turn.wake(); - switch (checked) { - .no => |w| return core.reportFailure(pane, w), - .ok => {}, - } - // Nothing more read from a pty or a terminal, and what was read - // goes in; a reader's cancel posts an end of file, passed over. - s.upgrading = true; - defer s.upgrading = false; - for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; - for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread); - while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); - core.settle(); - // Its replica clients told, their views gone before the dump: each - // dials the session again once it is back. - s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); - var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); - for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{ - .view = @intCast(k), - .fd = sc.tty.fd.handle, - .stub = if (sc.primary) daemon.stub else sc.stub, - .primary = sc.primary, - .termios = sc.tty.termios, - }); - var popped = false; - var at_buf: [1024:0]u8 = undefined; - const failed: []const u8 = failed: { - const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is"; - const bytes = pardes.dump.dumpBytes(core) catch |err| { - var words: [128]u8 = undefined; - break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump"; - }; - defer s.gpa.free(bytes); - if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written"; - rec.dump = at; - rec.old = upgrade.openSelf(); - // What this process put in its terminals that the next puts in - // again: its images, and its keyboard mode, a stack. - for (s.terms) |slot| if (slot) |sc| if (sc.on) { - clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); - if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[= 0) _ = libc.close(rec.old); - break :failed std.fmt.bufPrint(&why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start"; - }; - // As it was: its ptys read on, its terminals' keys as they were. - for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; - }; - for (s.terms) |slot| if (slot) |sc| if (sc.on) { - if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; - startInput(s.loop, sc) catch {}; - }; - core.reportFailure(pane, failed); - } - - /// An upgraded session's shells, running on: each its pane's pty again, - /// or, when its dump would not load (`fresh`), adopted as new panes. - fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { - for (rec.ptys[0..rec.nptys]) |k| { - const pane = if (rec.fresh) null else s.core.panes[k.pane]; - if (pane == null or !pane.?.isTerminal()) { - s.adoptShell(k.pid, k.fd); - continue; - } - const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } }; - s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - - /// An upgraded session's terminals, each its view's again (`primary`, - /// run's, entered already); in a fresh session each but the primary a - /// view of its own, as `--attach` makes one. A view left with none - /// closes, but a replica client's, kept for its rejoin (views.away). - fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void { - if (comptime builtin.is_test) unreachable; - const core = s.core; - if (rec.fresh) { - for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios); - return; - } - s.terms = @splat(null); - if (rec.nttys == 0) { - // The live view alone (never one kept for a rejoin) is the - // session's own. - for (0..pardes.views.max) |k| if (k != core.view and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - s.terms[core.view] = primary; - primary.feed.view = core.view; - return; - } - for (rec.ttys[0..rec.nttys]) |t| { - if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) { - if (t.primary) continue; - _ = libc.close(t.fd); - if (t.stub >= 0) daemon.tellDetached(t.stub); - continue; - } - const sc = if (t.primary) primary else extra: { - const sc = s.gpa.create(Screen) catch break :extra null; - const buf = s.gpa.alloc(u8, 0x10000) catch { - s.gpa.destroy(sc); - break :extra null; - }; - sc.* = .{ .io = s.io, .gpa = s.gpa, .env = primary.env, .buf = buf, .kitty = .init(s.gpa) }; - const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch { - s.freeScreen(sc); - break :extra null; - }; - sc.enter(tty) catch { - s.freeScreen(sc); - break :extra null; - }; - sc.setStub(t.stub); - startInput(s.loop, sc) catch {}; - sc.vx.queryTerminalSend(sc.tty.writer()) catch {}; - break :extra sc; - } orelse { - _ = libc.close(t.fd); - if (t.stub >= 0) daemon.tellDetached(t.stub); - continue; - }; - sc.feed.view = t.view; - s.terms[t.view] = sc; - } - for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - if (s.terms[core.view] == null) s.terms[core.view] = primary; - } - - /// One shell of a dead session (`pid` 0: the last of them was told). - fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void { - const core = s.core; - if (pid == 0) { - var buf: [96]u8 = undefined; - return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in"); - } - if (s.adoptions_len < s.adoptions.len) { - // A terminal pane, as the Tty word makes one; its spawn takes - // this pty instead of forking a shell (`spawn`). - s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null }; - s.adoptions_len += 1; - if (core.adoptShell()) |id| { - s.adoptions[s.adoptions_len - 1].pane = id; - s.adopted += 1; - return; - } - s.adoptions_len -= 1; - } - // No room for it: its master goes, and the shell with this session. - _ = libc.close(fd); - var buf: [96]u8 = undefined; - core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell"); - } - - fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { - const s = of(ctx); - // The wait is the 9P connections' turn with the core. A timeout (the - // core's next wake) arrives through the same queue (`wakeWatch`). - // While anything moves, a frame a tick (animation.frame_ns) on a grid - // of them, as the GUI paces to its display: the loop ran as fast as - // the terminal answered, a frame every 2 ms, each a write. An input - // ends the wait at once and its frame is drawn then; the ticks after - // it run from it. - var wait = timeout_ms; - // Detached, nobody's key dismisses a message: they go on the clock - // (the pump's, after this wait), which wakes it. - if (!s.attached()) { - for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { - wait = if (wait == 0) 100 else @min(wait, 100); - break; - }; - } - const paced = s.test_clock == null and s.core.continuous(); - var tick: u64 = 0; - if (paced) { - const period = pardes.animation.frame_ns; - const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now; - if (tick < now) tick += (now - tick) / period * period; - s.pace_ns = tick; - wait = @intCast(@max(1, (tick -| now) / std.time.ns_per_ms)); - } - s.input_seen = false; - s.output_seen = false; - s.took_input = false; - s.took_output = false; - s.mail_only = true; - defer s.waited = true; - // Paced, what is not an input (a frame's ack, a pty's output) is - // taken in and the wait goes on to the tick: the acks alone ran the - // loop at the terminal's round trip. - while (true) { - s.waitOnce(wait); - if (!paced or s.input_seen or s.core.quit) break; - const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (now + std.time.ns_per_ms > tick) break; - wait = @intCast((tick - now) / std.time.ns_per_ms); - } - if (paced and s.input_seen) s.pace_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - // Output alone is drawn a frame a tick at most, what came in till - // then in one: a flood (`yes`, 4 KB a read) was drawn a read at a - // time, nearly all of its frames written over before they were - // seen. Never while what someone waits on is undrawn: an input - // (its frame held for the terminal's answer, FrameAck), or the - // focused pane's output soon after one, its echo (a remote shell's - // an RTT later). - while (!paced and s.output_seen and !s.input_seen and !s.core.quit and s.test_clock == null) { - if (s.input_ns > s.drawn_ns) break; - if (s.focused_ns > s.drawn_ns and s.focused_ns -| s.input_ns < std.time.ns_per_s) break; - const due = s.drawn_ns + pardes.animation.frame_ns; - const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (now + std.time.ns_per_ms > due) break; - s.waitOnce(@intCast((due - now) / std.time.ns_per_ms)); - } - } - - fn waitOnce(s: *Shell, wait: u32) void { - var batch: usize = 0; - const first = if (s.held) |held| held: { - s.held = null; - break :held held; - } else next: { - if (wait != 0) { - // A virtual clock moves a frame a wake while anything moves - // continuously (the glide), as the real one would. - s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0; - requestWake(s.io, wait); - } - pardes.turn.rest(); - const got = s.loop.nextEvent() catch { - pardes.turn.wake(); - s.core.quit = true; - return s.reloadWatched(); - }; - pardes.turn.wake(); - break :next got; - }; - batch = 1; - // A run of queued motions is one move to its last cell: each would - // otherwise redo hover and selection work the next one undoes. - var motion: ?@TypeOf(Command.value) = null; - var ev = first; - while (true) { - if (s.split(ev)) break; - if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) { - if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or - @as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods))) - { - _ = s.apply(m); - }; - motion = ev; - } else { - if (motion) |m| _ = s.apply(m); - motion = null; - if (s.apply(ev)) break; - } - if (!s.in_paste and batch >= 64) break; - ev = (s.loop.tryEvent() catch null) orelse break; - batch += 1; - } - if (motion) |m| _ = s.apply(m); - // An exit's wake (a .nop) or output an exit waited behind: told - // here, inside the step, so the frame after it shows it. - s.takeExits(); - s.reloadWatched(); - } - - /// With replica clients, a wait (one pump, one unit) takes one step of - /// a person's input, and none after a pty's output: a step reads the - /// terminals as the clients' deltas bring them, sent after each unit - /// (docs/next-daemon.md, part B terminal notes). One that must wait is - /// held for the next. Whether `ev` is. - fn split(s: *Shell, ev: @TypeOf(Command.value)) bool { - if (!s.peers.recording) return false; - switch (ev) { - .pty_read => { - s.took_output = true; - return false; - }, - .key_press => if (s.in_paste) return false, - .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {}, - else => return false, - } - if (s.took_output or s.took_input) { - s.held = ev; - s.input_seen = true; - return true; - } - s.took_input = true; - return false; - } - - fn apply(s: *Shell, event: @TypeOf(Command.value)) bool { - const core = s.core; - const tz_event = tracy.zone(@src(), "event"); - defer tz_event.end(); - // A key's or a click's time, for its latency to the frame that - // answers it (FrameStats): when the loop takes it in. - switch (event) { - .key_press => { - core.frames.input(pardes.FrameStats.nowNs()); - s.input_seen = true; - }, - .mouse => |m| if (m.type == .press) { - core.frames.input(pardes.FrameStats.nowNs()); - s.input_seen = true; - }, - .paste, .paste_start, .winsize => s.input_seen = true, - else => {}, - } - if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (event != .replica_mail) s.mail_only = false; - // A terminal's input goes into its view; a closed one's last is - // dropped. - switch (event) { - .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { - if (s.terms[s.from] == null and s.local()) { - if (event == .paste) s.gpa.free(@constCast(event.paste)); - return false; - } - if (s.local() and s.remote == null) core.toView(s.from); - }, - else => {}, - } - switch (event) { - .nop => {}, - .from => |k| s.from = k, - .winched => s.winched(), - // A terminal hung up (its stub passes the hangup on) or its stub - // died (a forked session's death signal): that one's input has - // ended. A HUP says not whose: each is asked. - .hangup => for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on and sc.hungUp()) { - s.from = @intCast(k); - if (s.apply(.quit)) return true; - }, - .wake => if (s.test_clock) |*virtual| { - virtual.* = @max(virtual.*, s.wake_to); - }, - .quit => { - if (s.remote) |c| { - c.link.quit = true; - return true; - } - // One of several: its view goes with it. - if (pardes.views.count(core) > 1) { - s.dropView(core.view, .detach); - return true; - } - // The terminal went: a session the daemon keeps carries on - // without it, to be attached again. Gone before the first - // frame, the reader that takes the daemon's `ok` (kept - // waits on it) is not started yet: started here. - daemon.watch(s.loop, deliverNote); - if (daemon.kept()) { - if (s.attached()) s.leaveTerminal(); - return true; - } - core.quit = true; - return true; - }, - .attach => |a| s.attachTerminal(a.tty, a.stub, null), - .adopted => |a| s.adoptShell(a.pid, a.fd), - .replica => |j| { - s.peers.handed(j.fd, j.view); - s.input_seen = true; - }, - .replica_mail => s.input_seen = true, - .said => |said| if (s.remote) |c| { - c.link.take(said); - if (said == .refused) return true; - } else switch (said) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), - .checked => {}, - }, - .link_gone => if (s.remote) |c| { - c.link.quit = true; - c.link.gone = true; - return true; - }, - .focus_in => s.feed(.{ .focus = true }), - .focus_out => { - s.feed(.pointer_leave); - s.feed(.{ .focus = false }); - }, - .winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws), - .pty_read => |pr| { - tookRead(s.io, pr.id); - s.output_seen = true; - if (pr.id == core.active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - if (s.gens[pr.id] == pr.gen) - core.update(.{ .output = .{ .pane = @intCast(pr.id), .bytes = pr.bytes } }); - s.gpa.free(pr.bytes); - // An exit waiting behind this output may be told now. - s.takeExits(); - return true; - }, - .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) { - if (s.ptys[e.id]) |*pt| { - pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks - // A command's pty stays open until its child has exited: - // closing it would hang up one that runs on without it. - // Its exit, if it came first, is told now its output is in. - if (pt.cmd.watched) { - host_io.commandEof(core, &s.ptys, e.id, s, closeWatched); - return true; - } - _ = libc.close(pt.file.handle); - // Unwatched, a command's exit is read here, as its end, - // and a shell's, for a run waiting on it and the log. - const command = if (core.panes[e.id]) |pn| pn.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status == null) host_io.retireShell(pt.pid); - s.ptys[e.id] = null; - if (command or status != null) core.update(.{ .exited = .{ .pane = @intCast(e.id), .status = status } }); - } - core.update(.{ .eof = .{ .pane = @intCast(e.id) } }); - }, - .key_press => |key| if (s.in_paste) { - const bytes = pasteBytes(key); - const room = max_paste_bytes -| s.paste_buf.written().len; - s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; - } else s.feed(vaxis_input.keyEvent(key)), - .mouse => |m| { - const pdf_before = nativePdfWheelTarget(core, m); - if (mouseEvent(m)) |ev| s.feed(ev); - if (pdf_before) |before| { - if (core.panes[before.pane]) |pane| { - if (pane.pdfPage()) |page| { - if (page != before.page) return true; - } - } - } - }, - .paste => |bytes| { - s.feed(.{ .paste = bytes }); - s.gpa.free(@constCast(bytes)); - }, - .paste_start => { - s.in_paste = true; - s.paste_buf.clearRetainingCapacity(); - }, - .paste_end => { - s.in_paste = false; - const pasted = s.paste_buf.written(); - if (pasted.len > 0) s.feed(.{ .paste = pasted }); - s.paste_buf.clearRetainingCapacity(); - }, - .files_changed => s.check_files = true, - .fs_ready => {}, - .lsp_done => |d| { - core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); - if (d.rows) |rows| s.lsp_gpa.free(rows); - if (s.lsp_task) |*t| if (t.id == d.id) { - t.future.await(s.io); - s.lsp_task = null; - }; - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - core.setStatus(core.active, message.stamp(&mbuf, "lsp", text)); - s.lsp_gpa.free(text); - }, - .pipe_done => |response_value| { - var response = response_value; - core.update(.{ .pipe_resp = .{ - .id = response.id, - .success = response.success, - .outputs = response.outputs, - .failure = response.failure, - } }); - response.deinit(s.gpa); - s.pipe_tasks.finish(s.io, response_value.id); - }, - .search_rows => |b| { - core.update(.{ .search = b }); - b.deinit(s.gpa); - }, - } - return false; - } - - /// Terminal `screen` (the live view's) is `ws` big. - fn resized(s: *Shell, screen: ?*Screen, ws: vaxis.Winsize) void { - if (screen) |sc| { - sc.size = ws; - sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {}; - } - s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } }); - } - - /// A SIGWINCH: each terminal whose size it changed is resized, in its - /// view (a terminal reporting in band says so as input). - fn winched(s: *Shell) void { - for (s.terms, 0..) |slot, k| { - const sc = slot orelse continue; - if (!sc.on or sc.vx.state.in_band_resize) continue; - const ws = sc.tty.getWinsize() catch continue; - if (sc.size) |was| if (std.meta.eql(was, ws)) continue; - if (s.remote == null) s.core.toView(@intCast(k)); - s.resized(sc, ws); - } - } - - fn reloadWatched(s: *Shell) void { - if (!s.check_files) return; - s.check_files = false; - if (file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) - s.loop.postEvent(.files_changed) catch {}; - } - - /// ponytail: a terminal's scrollback under the wheel lands here (the - /// wheel reaches the core as a mouse event, not counted as the GUI's - /// notches are); `wheeled` from the mouse event if it should glide. - fn stepGlide(ctx: ?*anyopaque) void { - const s = of(ctx); - if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null); - } - - fn pollFrame(ctx: ?*anyopaque) void { - const s = of(ctx); - stepGlide(ctx); - if (s.fs) |f| if (f.tick().pending) { - _ = s.loop.tryPostEvent(.fs_ready) catch {}; - }; - for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); - }; - - const sc = s.term() orelse return; - s.core.native_image_patches = sc.feed.shm.load(.acquire); - if (sc.caps_pending and sc.on and sc.vx.queries_done.load(.unordered)) { - sc.caps_pending = false; - sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; - s.core.native_images = sc.vx.caps.kitty_graphics; - if (sc.vx.caps.kitty_graphics) kittyShmProbe(sc.tty.writer(), &sc.feed); - sc.vx.queueRefresh(); - s.core.needs_frame = true; - } - } - - fn present(ctx: ?*anyopaque, canonical: *const pardes.Surface) void { - const s = of(ctx); - const sc = s.term() orelse return; - const vx = &sc.vx; - sc.tracks = canonical.panelTracks(); - // The last frame is not answered yet: this one stays owed, and the - // answer's wake draws the state as it is then. - if (sc.feed.ack.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { - s.core.present_skipped = true; - return; - } - _ = s.frame.reset(.retain_capacity); - const surface = panel_compositor.compose( - s.frame.allocator(), - @constCast(canonical), - sc.tracks, - s.core.theme().bg, - ) catch return; - const tz_cells = tracy.zone(@src(), "surface->vaxis"); - const win = vx.window(); - const truecolor = vx.caps.rgb or colortermTruecolor(); - // Each of the shell's own motions below asks for frames while it runs. - if (sc.glide.pending) sc.glide.measure(s.gpa, canonical); - if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion); - s.core.shell_continuous = sc.glide.moving(); - s.core.frames.scroll = @round(sc.glide.follow.offset); - const glided = pardes.glide.shifted(&sc.glide, s.frame.allocator(), surface) catch surface; - const shadowed = chipShadows(s.frame.allocator(), glided, s.core, truecolor) catch glided; - const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; - const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; - paintCells(win, trailed.cells, trailed.cols, trailed.rows); - if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), trailed.cols, trailed.rows); - tz_cells.end(); - for (surface.images[0..surface.nimages]) |maybe| { - const place = maybe orelse continue; - if (panel_compositor.hidesAttachment(surface.panelTracks(), place.serial)) continue; - if (comptime pardes.pdf_enabled) { - if (!kittyImageRepresentable(place)) continue; - } - const key = place.cacheKey(); - if (!sc.kitty.contains(key) and vx.caps.kitty_graphics and sc.feed.shm.load(.acquire)) shm: { - var buf: [64]u8 = undefined; - kitty_shm_serial +%= 1; - // Bounded: a segment this many transmissions old was never - // read (a terminal reads one as its command arrives), and a - // tmpfs holds it in memory until it goes. - if (kitty_shm_serial > kitty_shm_window) { - var old_buf: [64]u8 = undefined; - if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {} - } - const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; - if (!kittyShmWrite(name, place.rgba)) break :shm; - if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| - sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id) - else - _ = libc.shm_unlink(name); - } - if (!sc.kitty.contains(key) and vx.caps.kitty_graphics) { - const enc = std.base64.standard.Encoder; - if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { - defer s.gpa.free(b64); - _ = enc.encode(b64, place.rgba); - if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| - sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); - } else |_| {} - } - if (sc.kitty.get(key)) |cached| { - if (comptime !pardes.pdf_enabled) { - const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); - cached.draw(child, .{ .scale = .contain }) catch {}; - } else { - if (place.native.exact) { - if (exactKittyPlacement(place, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix)) |placement| { - // The cell keeps its own glyph and colours - // (Image.draw would reset them): a fragment - // short of the cell shows the pane under it. - const x = place.x + placement.cell_x; - if (win.readCell(x, place.y)) |under| { - var cell = under; - cell.image = .{ .img_id = cached.id, .options = placement.options }; - win.writeCell(x, place.y, cell); - } - } - } else if (place.native.fit == .contain) { - const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); - cached.draw(child, .{ .scale = .contain }) catch {}; - } else if (kittyPlacement( - place, - vx.screen.width, - vx.screen.height, - vx.screen.width_pix, - vx.screen.height_pix, - )) |placement| { - const child = win.child(.{ - .x_off = @as(i17, place.x) + placement.cell_x, - .y_off = @as(i17, place.y) + placement.cell_y, - .width = placement.cell_cols, - .height = placement.cell_rows, - }); - cached.draw(child, placement.options) catch {}; - } - } - } - } - while (true) { - var stale: [pardes.MAX_PANES]pardes.ImageCacheKey = undefined; - var stale_len: usize = 0; - var image_iterator = sc.kitty.iterator(); - while (image_iterator.next()) |entry| { - if (surfaceHasKittyKey(surface, entry.key_ptr.*)) continue; - stale[stale_len] = entry.key_ptr.*; - stale_len += 1; - if (stale_len == stale.len) break; - } - for (stale[0..stale_len]) |key| if (sc.kitty.fetchRemove(key)) |removed| - vx.freeImage(sc.tty.writer(), removed.value.id); - if (stale_len < stale.len) break; - } - if (glided.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar); - const tz_render = tracy.zone(@src(), "vx.render"); - const before = sc.tty.tty_writer.pos + sc.tty.writer().end; - vx.render(sc.tty.writer()) catch {}; - // The frame's cost to the terminal (FrameStats.Frame.bytes): what - // vaxis's diff of the cells wrote. - s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), sc.tty.tty_writer.pos + sc.tty.writer().end -| before)); - if (sc.tty.tty_writer.pos + sc.tty.writer().end != before) sc.feed.ack.ask(sc.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); - s.drawn_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - tz_render.end(); - } - - fn postPresent(ctx: ?*anyopaque) void { - const s = of(ctx); - if (s.term()) |sc| s.core.acknowledgePanelPresentation(sc.tracks); - tracy.frameMark(); - } - - fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { - const s = of(ctx); - for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) { - std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]); - s.adoptions_len -= 1; - return s.takeShell(pane, a); - }; - // The new shell starts before a running one goes: one that cannot - // start leaves the running one be (pty/ctl's exec). - const running = s.ptys[pane] != null; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.screen_h, s.core.screen_w, s.fs) catch |err| { - if (running) return s.core.restartFailed(pane, err); - return s.core.shellFailed(pane, err); - }; - closePty(ctx, pane); // a shell still in the slot goes, reaped - s.gens[pane] +%= 1; - const command = if (s.core.panes[pane]) |pn| pn.command != null else false; - s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - // Only a shell given no directory is asked where it is: one given a - // directory is named by it already (newShell), and asked now, before - // its chdir, it would answer this process's, a rename to undo. - if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - if (s.threads_ok) { - if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - } - } - } - - /// An adopted shell, running already, as pane `pane`'s: told the size - /// twice (a size it never had, then the pane's), which makes it redraw. - fn takeShell(s: *Shell, pane: u8, a: Adoption) void { - closePty(s, pane); - s.gens[pane] +%= 1; - const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; - s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; - var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; - _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); - if (s.threads_ok) if (s.ptys[pane]) |*pt| { - pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; - }; - } - - fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { - const s = of(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); - } - - fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { - const s = of(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); - } - } - - fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { - const s = of(ctx); - // A command whose exit is recorded is reaped: its group may be - // another's by now. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); - } - - /// The pane is gone: hang its pty up, which the kernel passes on to the - /// shell as SIGHUP, and retire the shell. Output still in flight - /// carries the old generation and is dropped. - fn closePty(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - var pt = s.ptys[pane] orelse return; - s.ptys[pane] = null; - s.gens[pane] +%= 1; - pt.reader.cancel(s.io) catch {}; - _ = libc.close(pt.file.handle); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - } - - fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.file.handle); - } - - fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { - const s = of(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.file.handle, buf); - } - - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *@This()) void { - host_io.takeExits(s.core, &s.ptys, s, closeWatched); - } - - fn closeWatched(s: *@This(), id: usize) void { - const pt = &(s.ptys[id] orelse return); - _ = libc.close(pt.file.handle); - s.ptys[id] = null; - } - - fn killJob(ctx: ?*anyopaque, pane: u8) bool { - const s = of(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.file.handle); - } - - fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { - const s = of(ctx); - host_io.writeFile(s.core, &s.watches, pane, path, bytes); - } - - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - host_io.writeDump(of(ctx).core, bytes); - } - - fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const s = of(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) - s.loop.postEvent(.files_changed) catch {}; - } - - fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = of(ctx); - if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on, s.threads_ok)) - s.loop.postEvent(.files_changed) catch {}; - } - - fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - host_io.dumpThemes(s.core, s.io, s.gpa, pane); - } - - fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { - const s = of(ctx); - // Detached, the session keeps it (a 9P read, a paste here). - const sc = s.term() orelse return s.core.fallback.setClipboard(text); - if (!sc.on) return s.core.fallback.setClipboard(text); - copyToClipboard(&sc.vx, &sc.tty, s.gpa, text); - } - - fn readClipboard(ctx: ?*anyopaque) void { - const s = of(ctx); - const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); - requestClipboard(&sc.vx, &sc.tty); - } - - fn openLink(_: ?*anyopaque, url: []const u8) void { - look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly - } - - fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { - const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); - } - host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); - } - - fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const s = of(ctx); - s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); - } - - fn pipe(ctx: ?*anyopaque, id: u32) void { - const s = of(ctx); - if (!s.threads_ok) { - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - return s.core.reportError(s.core.active, "pipe", error.WorkersUnavailable); - } - selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); - } - - 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); - } - - /// The loop's queue waits for room (a wait the worker's cancel ends). - fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { - const s = of(ctx); - s.loop.postEvent(.{ .search_rows = batch }) catch { - batch.deinit(s.gpa); - return false; - }; - return true; - } - - fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { - const s = of(ctx); - var owned = response; - s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); - } -}; - -test "TTY queued results reject old PTY generations and LSP request IDs" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer core.deinit(); - var shell: Shell = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_gpa = gpa, - .core = core, - .prompt_rcs = undefined, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .inotify_fd = -1, - }; - shell.gens[0] = 2; - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); - _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); - try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); - - core.lspRequest(0, .status, ""); - const old_id = core.lsp_wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_wait.?.id; - shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; - _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); - try std.testing.expect(shell.lsp_task != null); - try std.testing.expectEqual(current_id, shell.lsp_task.?.id); - try std.testing.expectEqual(current_id, core.lsp_wait.?.id); - _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expect(core.lsp_wait == null); -} - -test "TTY worker setup failures finish matching LSP and pipe requests" { - const gpa = std.testing.allocator; - var failing_vtable = std.testing.io.vtable.*; - failing_vtable.concurrent = std.Io.failingConcurrent; - const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; - for (0..2) |failure| { - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - var failing = std.testing.FailingAllocator.init(gpa, .{ - .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), - }); - var shell: Shell = .{ - .io = failing_io, - .gpa = failing.allocator(), - .lsp_gpa = failing.allocator(), - .core = core, - .prompt_rcs = undefined, - .loop = undefined, - .frame = undefined, - .paste_buf = undefined, - .inotify_fd = -1, - .threads_ok = true, - }; - core.lspRequest(core.active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_wait.?.id, - .kind = .status, - .pane = @intCast(core.active), - .offset = 0, - .arg = "", - }; - Shell.lsp(&shell, req); - try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - - pane.body.cur_col = 2; - pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - core.update(.{ .key = .{ .cp = '|' } }); - core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe.wait.?.id; - Shell.pipe(&shell, pipe_id); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(shell.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); - } -} - -fn copyToClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty, gpa: std.mem.Allocator, text: []const u8) void { - if (text.len == 0) return; - vx.copyToSystemClipboard(tty.writer(), text, gpa) catch {}; -} - -fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { - vx.requestSystemClipboard(tty.writer()) catch {}; -} - -fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { - const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); - const copy = s.lsp_gpa.dupe(u8, text) catch return; - const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; - if (!posted) s.lsp_gpa.free(copy); -} - -fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { - if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { - while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; - return; - } - const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [4096]u8 = undefined; - while (true) { - const n = file.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - loop.postEvent(.files_changed) catch break; - } -} - -fn keepSignal(_: posix.SIG) callconv(.c) void {} - -/// A replica client's (`remote`): a hangup is its end, whoever sent it. -var hangup_quits = false; - -fn winchWatch(loop: *Loop) void { - var set = posix.sigemptyset(); - posix.sigaddset(&set, posix.SIG.WINCH); - if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); - while (true) { - var sig: c_int = 0; - if (libc.sigwait(&set, &sig) != 0) continue; - // The terminals are the loop's: it asks each its size, and takes a - // hangup as the end of the one that hung up. - const ev: @TypeOf(Command.value) = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; - loop.postEvent(ev) catch {}; - } -} - -/// A wait with a timeout: post one `.wake` when it runs out. The wake joins -/// the input queue, so a key or a click that lands first is handled at once -/// instead of after a blind sleep; vaxis's queue has no timed wait. Each -/// request bumps `wake_gen`, which cuts short a sleep still timing an -/// earlier, longer request (an 800 ms linger interrupted by a key that -/// starts a 16 ms fall) and times the new one instead. -var wake_gen: std.atomic.Value(u32) = .init(0); -var wake_ms: std.atomic.Value(u32) = .init(0); - -fn requestWake(io: std.Io, ms: u32) void { - wake_ms.store(ms, .release); - _ = wake_gen.fetchAdd(1, .acq_rel); - io.futexWake(u32, &wake_gen.raw, 1); -} - -fn wakeWatch(io: std.Io, loop: *Loop) void { - var seen = wake_gen.load(.acquire); - while (true) { - // Asleep until a request. - while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen); - seen = wake_gen.load(.acquire); - if (timeWake(io, &seen)) loop.postEvent(.wake) catch {}; - } -} - -/// Sleep out the latest request; true when it ran its course, false when -/// none is pending. A newer request met on the way restarts the timing. -fn timeWake(io: std.Io, seen: *u32) bool { - while (true) { - const ms = wake_ms.load(.acquire); - const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms; - while (true) { - const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - if (now >= deadline) return true; - io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{ - .raw = .fromNanoseconds(@intCast(deadline - now)), - .clock = .awake, - } }) catch {}; - const gen = wake_gen.load(.acquire); - if (gen != seen.*) { - seen.* = gen; - break; - } - } - } -} - -test "a short wake request cuts short a long one still sleeping" { - const io = std.testing.io; - var seen = wake_gen.load(.acquire); - requestWake(io, 800); - seen = wake_gen.load(.acquire); - const Timer = struct { - fn run(timer_io: std.Io, start_seen: u32, done: *std.atomic.Value(u64)) void { - var local = start_seen; - _ = timeWake(timer_io, &local); - done.store(@intCast(std.Io.Clock.awake.now(timer_io).nanoseconds), .release); - } - }; - var done: std.atomic.Value(u64) = .init(0); - const start: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - const thread = try std.Thread.spawn(.{}, Timer.run, .{ io, seen, &done }); - try io.sleep(.fromMilliseconds(50), .awake); - requestWake(io, 16); - thread.join(); - // The 16 ms request lands about 66 ms in: well before the 800 ms one - // would have, however loaded the machine. - try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms); -} - -fn wakeFs(ctx: ?*anyopaque) void { - const loop: *Loop = @ptrCast(@alignCast(ctx.?)); - _ = loop.tryPostEvent(.fs_ready) catch {}; -} - -/// Each pane's reads posted and not yet taken in. Two at most: a flood the -/// loop cannot keep up with waits in its pty, not in the queue ahead of a -/// key and its echo (hundreds of 4 KB reads queued were half a second). -var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); - -/// A read of pane `id` taken in (or dropped): its reader may read on. Never -/// below zero, for an event no reader posted (a test's). -fn tookRead(io: std.Io, id: usize) void { - var queued = reads_queued[id].load(.acquire); - while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { - if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); - return; - }; -} - -fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { - // One buffer, read into directly: a Reader around it only added a second - // (and in a safe build, filled both as `undefined` on every start). - var buf: [0x10000]u8 = undefined; - read: while (true) { - while (true) { - const queued = reads_queued[id].load(.acquire); - if (queued < 2) break; - io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; - } - const n = pty.readStreaming(io, &.{&buf}) catch break; - if (n == 0) break; - const bytes = try gpa.dupe(u8, buf[0..n]); - _ = reads_queued[id].fetchAdd(1, .acq_rel); - loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { - tookRead(io, id); - gpa.free(bytes); - break; - }; - } - _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; -} - -const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; - -fn pasteBytes(key: vaxis.Key) []const u8 { - const text = key.text orelse ""; - if (text.len > 0) return text; - const cp = vaxis_input.mapKey(vaxis_input.effCp(key)); - if (cp == pardes.Key.tab) return "\t"; - if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n"; - return ""; -} - -test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { - if (comptime builtin.os.tag == .windows) return error.SkipZigTest; - const gpa = std.testing.allocator; - const io = std.testing.io; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(io, gpa, &env, .{}); - var output: std.Io.Writer.Allocating = .init(gpa); - defer output.deinit(); - defer vx.deinit(gpa, &output.writer); - vx.queries_done.store(false, .unordered); - var tty: vaxis.Tty = undefined; - var loop: Loop = .init(io, &tty, &vx); - var feed: Feed = .{}; - const Reader = struct { - parts: []const []const u8, - next: usize = 0, - fn getWinsize(_: *@This()) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - pub fn inputFollows(self: *@This(), _: u32) bool { - return self.next < self.parts.len; - } - fn read(self: *@This(), buf: []u8) !usize { - if (self.next == self.parts.len) return 0; - const part = self.parts[self.next]; - self.next += 1; - @memcpy(buf[0..part.len], part); - return part.len; - } - }; - var reader: Reader = .{ - .parts = &.{ - // The startup width queries' answers from a terminal without - // explicit width (foot, ghostty, tmux): two F3s, typed at the prompt. - "\x1b[1;1R\x1b[1;1R\x1b[?62;c", - // Kitty reports Ctrl and Shift pressed on their own: the Ctrl of a - // Ctrl-V typed `\x1b[57442;5u` into the shell. - "\x1b[57442;5u\x1b[57441;2u\x1b[57358u", - // F3, F5 and Insert the kitty way, F3 the legacy way and the - // keypad's Up: once typed as private-use junk, now what htop, - // mc and vim read them as. - "\x1b[13~\x1b[15~\x1b[2~\x1bOR\x1b[57419u", - "\x1b[104;;104u", - }, - }; - try readInput(&loop, &reader, &vx, &feed); - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - while (try loop.tryEvent()) |event| switch (event) { - .key_press => |key| core.update(vaxis_input.keyEvent(key)), - else => {}, - }; - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings("\x1bOR\x1b[15~\x1b[2~\x1bOR\x1b[Ah", written.written()); -} - -test "the terminal's keys reach a program as its cursor keys' mode and keyboard flags say" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - // What the outer terminal sends, what the program asked for, and what - // it should read. - const Case = struct { modes: []const u8, in: []const u8, sent: []const u8 }; - const cases = [_]Case{ - .{ .modes = "", .in = "\x1b[A\x1b[H\x1bOP\x1b[15~", .sent = "\x1b[A\x1b[H\x1bOP\x1b[15~" }, - .{ .modes = "\x1b[?1h", .in = "\x1b[A\x1b[F\x1b[1;5D", .sent = "\x1bOA\x1bOF\x1b[1;5D" }, - .{ .modes = "\x1b[?1l\x1b[>7u", .in = "\x1b[99;5u\x1b[97;3u\x1b[A", .sent = "\x1b[99;5u\x1b[97;3u\x1b[1;1:1A" }, - }; - for (cases) |case| { - core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); - while (core.nextEffect()) |_| {} - var parser: vaxis.Parser = .{}; - var bytes = case.in; - while (bytes.len > 0) { - const result = try parser.parse(bytes, gpa); - if (result.n == 0) break; - bytes = bytes[result.n..]; - if (result.event) |event| switch (event) { - .key_press => |key| core.update(vaxis_input.keyEvent(key)), - else => {}, - }; - } - written.clearRetainingCapacity(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings(case.sent, written.written()); - } -} - -test "keypad Enter matches Return for editor input terminal writes and paste" { - for ([_]u21{ vaxis.Key.enter, vaxis.Key.kp_enter }) |codepoint| { - const key: vaxis.Key = .{ .codepoint = codepoint }; - const event = vaxis_input.keyEvent(key); - try std.testing.expectEqual(pardes.Key.enter, event.key.cp); - try std.testing.expectEqualStrings("\n", pasteBytes(key)); - { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("ab"); - core.update(.{ .key = .{ .cp = 'i' } }); - core.update(event); - try std.testing.expectEqualStrings("\nab", pane.file.?.content); - } - { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - core.update(event); - var written: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer written.deinit(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings("\r", written.written()); - } - } -} - -fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { - const button: pardes.Mouse.Button = switch (m.button) { - .left => .left, - .middle => .middle, - .right => .right, - .wheel_up => .wheel_up, - .wheel_down => .wheel_down, - .wheel_left => .wheel_left, - .wheel_right => .wheel_right, - // A mouse's side buttons, as xterm reports them: Back and Forward. - .button_8 => .back, - .button_9 => .forward, - .none => .none, // button-less motion: hover tracking - else => return null, - }; - return .{ .mouse = .{ - .button = button, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, - }, - .col = cellOf(m.col), - .row = cellOf(m.row), - .ctrl = m.mods.ctrl, - .shift = m.mods.shift, - .alt = m.mods.alt, - } }; -} - -/// A report's cell, 0-based: one before the first (SGR's 0, a drag past -/// the window's top or left edge, in cells or in 1016's pixels) is the -/// first, never a panic; past the far edge the core clamps it. -pub fn cellOf(v: i16) u16 { - return @intCast(@max(0, v)); -} - -test "a mouse report at row or column 0, or before it, is the window's edge, never a panic" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - for ([_][]const u8{ "\x1b[<1;42;0M", "\x1b[<0;0;5M", "\x1b[<32;0;0M", "\x1b[<0;0;0m" }) |sequence| { - var parser: vaxis.Parser = .{}; - const result = try parser.parse(sequence, std.testing.allocator); - const m = result.event.?.mouse; - const event = mouseEvent(m) orelse continue; - try std.testing.expect(event.mouse.col <= 41 and event.mouse.row <= 4); - p.update(event); - } -} - -test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 and X2 are" { - for ([_]vaxis.Mouse.Button{ .button_8, .button_9 }, [_]pardes.Mouse.Button{ .back, .forward }) |from, to| { - const event = mouseEvent(.{ .col = 3, .row = 2, .button = from, .mods = .{}, .type = .press }).?; - try std.testing.expectEqual(to, event.mouse.button); - } -} - -/// A replica client's own line over its frame's last row (`Remote.notify`), -/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps -/// the slices). -fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { - if (rows == 0) return; - for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ - .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, - .style = .{ .reverse = true }, - }); -} - -/// A blank whose ink alone changed is not sent: vaxis's render skips it -/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows -/// nowhere. Deciding that here cost every cell of every frame a look at the -/// frame before; vaxis already makes that comparison. -fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void { - win.clear(); - var y: u16 = 0; - while (y < rows) : (y += 1) { - var x: u16 = 0; - while (x < cols) : (x += 1) { - const cell = &cells[@as(usize, y) * cols + x]; - if (cell.default) continue; - win.writeCell(x, y, .{ - .char = .{ .grapheme = cell.grapheme() }, - .style = vaxisStyle(cell.style), - }); - } - } -} - -test "a fade sends the text it dims, not the blanks beside it" { - const gpa = std.testing.allocator; - var env = try std.testing.environ.createMap(gpa); - defer env.deinit(); - var vx = try vaxis.init(std.testing.io, gpa, &env, .{}); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - defer vx.deinit(gpa, &out.writer); - try vx.resize(gpa, &out.writer, .{ .rows = 1, .cols = 32, .x_pixel = 0, .y_pixel = 0 }); - // `a`, a gap, `b`, a two-cell gap, `c`, a gap, an underlined blank - // (which shows its ink) and one more blank. - var cells: [32]pardes.Cell = @splat(.{ .default = false }); - cells[0].text[0] = 'a'; - cells[12].text[0] = 'b'; - cells[15].text[0] = 'c'; - cells[30].style.ul = .single; - var sent: [2][]u8 = .{ &.{}, &.{} }; - defer for (sent) |bytes| gpa.free(bytes); - for ([_][3]u8{ .{ 200, 200, 200 }, .{ 90, 90, 90 } }, 0..) |ink, frame| { - for (&cells) |*cell| cell.style.fg = .{ .rgb = ink }; - out.clearRetainingCapacity(); - paintCells(vx.window(), &cells, 32, 1); - try vx.render(&out.writer); - sent[frame] = try out.toOwnedSlice(); - } - // Against a cleared screen every cell goes. After the fade the letters - // go and the underlined blank; every plain blank is jumped. - try std.testing.expectEqual(@as(usize, 29), std.mem.count(u8, sent[0], " ")); - try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, sent[1], " ")); - try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'b') != null); - try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'c') != null); - try std.testing.expect(std.mem.indexOf(u8, sent[1], "90:90:90") != null); - try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'a') != null); -} - -/// T1 (§9.2): each notice chip casts a shadow one cell right and one down, -/// inside its own pane's body: its ground 35% toward black in OKLab on a -/// cell with text; on a blank one a half block (▌ on the right, ▀ below, -/// ▘ at the corner) in the darker colour, so the shadow is half a cell -/// thick and reads as one. Never the cursor's cell, a selection, a tag or -/// another chip. Truecolor terminals only. -fn chipShadows(arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { - if (!core.settings.chip_shadow or !truecolor) return surface; - const regions = surface.regionList(); - const any = for (regions) |region| { - if (region.kind == .notice) break true; - } else false; - if (!any) return surface; - const out = try arena.create(pardes.Surface); - out.* = surface.*; - out.cells = try arena.dupe(pardes.Cell, surface.cells); - const theme = core.theme(); - const page = theme.bg orelse pardes.colors.null_page; - for (regions) |chip| { - if (chip.kind != .notice or chip.rect.w == 0) continue; - const body = for (regions) |region| { - if (region.kind == .body and region.owner == chip.owner) break region.rect; - } else continue; - const right = chip.rect.x + chip.rect.w; - const below = chip.rect.y + chip.rect.h; - // The column right of it (from its second row), the row below (from - // its second column), and the corner. - var y = chip.rect.y; - while (y <= below) : (y += 1) { - var x = chip.rect.x; - while (x <= right) : (x += 1) { - const side = x == right and y > chip.rect.y and y < below; - const foot = y == below and x > chip.rect.x and x < right; - const corner = x == right and y == below; - if (!side and !foot and !corner) continue; - if (x < body.x or y < body.y or x >= body.x + body.w or y >= body.y + body.h or x >= out.cols or y >= out.rows) continue; - if (surface.cursor) |cu| if (cu.x == x and cu.y == y) continue; - const covered = for (regions) |region| { - if ((region.kind == .notice or region.kind == .tag or region.kind == .grip) and x >= region.rect.x and x < region.rect.x + region.rect.w and y >= region.rect.y and y < region.rect.y + region.rect.h) break true; - } else false; - if (covered) continue; - const cell = &out.cells[@as(usize, y) * out.cols + x]; - const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue; - const dark = pardes.colors.mixOklab(ground, .{ 0, 0, 0 }, 0.35); - const blank = cell.default or cell.len == 0 or (cell.len == 1 and cell.text[0] == ' '); - if (blank) { - const glyph: []const u8 = if (corner) "▘" else if (side) "▌" else "▀"; - cell.* = .{ .default = false, .style = .{ .fg = .{ .rgb = dark }, .bg = .{ .rgb = ground } } }; - @memcpy(cell.text[0..glyph.len], glyph); - cell.len = @intCast(glyph.len); - } else { - cell.default = false; - cell.style.bg = .{ .rgb = dark }; - } - } - } - } - return out; -} - -/// T7 (§9.2): a pane whose view moved (Region.line) has its scroll thumb -/// brighten, drawn most of the way to the text's colour, and fade back -/// over 250 ms with an ease-out: where you are in the file, as you move. -/// The rail is chrome, not a focus indicator. Truecolor terminals only. -const ThumbFlash = struct { - lines: [pardes.MAX_PANES]i32 = @splat(std.math.minInt(i32)), - since: [pardes.MAX_PANES]u64 = @splat(0), - - const life_ns: u64 = 250 * std.time.ns_per_ms; - - fn apply(flash: *ThumbFlash, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { - const on = core.settings.thumb_flash and truecolor and core.settings.motion != .off; - var out: ?*pardes.Surface = null; - const theme = core.theme(); - const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc }; - for (surface.regionList()) |body| { - if (body.kind != .body or body.owner >= flash.lines.len) continue; - const id = body.owner; - if (flash.lines[id] != std.math.minInt(i32) and flash.lines[id] != body.line) flash.since[id] = core.now_ns; - flash.lines[id] = body.line; - const age = core.now_ns -| flash.since[id]; - if (!on or flash.since[id] == 0 or age >= life_ns) continue; - const rail = for (surface.regionList()) |region| { - if (region.kind == .rail and region.owner == id) break region; - } else continue; - if (rail.thumb_h == 0) continue; - const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); - const strength = 0.6 * (1 - t) * (1 - t); - if (out == null) { - const copy = try arena.create(pardes.Surface); - copy.* = surface.*; - copy.cells = try arena.dupe(pardes.Cell, surface.cells); - out = copy; - } - const o = out.?; - var y = rail.rect.y + rail.thumb_y; - while (y < rail.rect.y + rail.thumb_y + rail.thumb_h and y < o.rows) : (y += 1) { - var x = rail.rect.x; - while (x < rail.rect.x + rail.rect.w and x < o.cols) : (x += 1) { - const cell = &o.cells[@as(usize, y) * o.cols + x]; - const ground: [3]u8 = switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => continue, - }; - if (!std.mem.eql(u8, &ground, &core.chromeTheme().scroll_thumb)) continue; - cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) }; - } - } - core.shell_continuous = true; - } - return out orelse surface; - } -}; - -/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does -/// not answer vaxis's query (§9.2: vaxis caps or COLORTERM). -fn colortermTruecolor() bool { - const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false); - return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit"); -} - -/// T2 (docs/render-pipeline.md §9.2): the cursor jumping three cells or -/// more leaves a trail of three to five cells along its path, just behind -/// it, their ground drawn toward the text's colour, most beside the -/// cursor, all fading out over 120 ms. Truecolor terminals only; a cell a -/// frame changes, a few bytes. Never the cursor's own cell, a selection or -/// anything outside the focused pane's body; off with Motion off. -const JumpTrail = struct { - last: ?[2]u16 = null, - from: [2]u16 = .{ 0, 0 }, - to: [2]u16 = .{ 0, 0 }, - start_ns: u64 = 0, - active: bool = false, - - const life_ns: u64 = 120 * std.time.ns_per_ms; - - fn apply(trail: *JumpTrail, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { - defer core.shell_continuous = trail.active or core.shell_continuous; - const on = core.settings.jump_trail and truecolor and core.settings.motion != .off; - const cursor = surface.cursor orelse { - trail.active = false; - return surface; - }; - const here: [2]u16 = .{ cursor.x, cursor.y }; - if (trail.last) |was| { - const dx = @as(i32, here[0]) - was[0]; - const dy = @as(i32, here[1]) - was[1]; - if (on and @max(@abs(dx), @abs(dy)) >= 3) { - trail.* = .{ .last = here, .from = was, .to = here, .start_ns = core.now_ns, .active = true }; - } - } - trail.last = here; - if (!on or !trail.active) { - trail.active = false; - return surface; - } - const age = core.now_ns -| trail.start_ns; - if (age >= life_ns or !std.meta.eql(trail.to, here)) { - trail.active = false; - return surface; - } - const out = try arena.create(pardes.Surface); - out.* = surface.*; - out.cells = try arena.dupe(pardes.Cell, surface.cells); - const theme = core.theme(); - const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc }; - const page = theme.bg orelse pardes.colors.null_page; - const body = for (surface.regionList()) |region| { - if (region.kind == .body and region.owner == core.active) break region.rect; - } else return out; - const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); - const fade = (1 - t) * (1 - t); - const dx = @as(f32, @floatFromInt(@as(i32, trail.from[0]) - trail.to[0])); - const dy = @as(f32, @floatFromInt(@as(i32, trail.from[1]) - trail.to[1])); - const span = @max(@abs(dx), @abs(dy)); - const n: usize = @intFromFloat(std.math.clamp(@round(span / 4), 3, 5)); - var k: usize = 1; - var last_cell: ?[2]i32 = null; - var step: f32 = 1; - while (k <= n and step <= span) : (step += 1) { - const x: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[0])) + dx * step / span)); - const y: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[1])) + dy * step / span)); - if (last_cell) |seen| if (seen[0] == x and seen[1] == y) continue; - last_cell = .{ x, y }; - defer k += 1; - if (x < body.x or y < body.y or x >= @as(i32, body.x) + body.w or y >= @as(i32, body.y) + body.h) continue; - const cell = &out.cells[@as(usize, @intCast(y)) * out.cols + @as(usize, @intCast(x))]; - const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue; - const strength = 0.55 * fade * (1 - @as(f32, @floatFromInt(k - 1)) / @as(f32, @floatFromInt(n))); - if (strength < 0.02) continue; - const was_default = cell.default; - cell.default = false; - if (was_default) cell.style = .{}; - cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) }; - } - return out; - } -}; - -fn paintCursor(win: vaxis.Window, x: u16, y: u16, bar: bool) void { - win.showCursor(x, y); - win.setCursorShape(if (bar) .beam else .default); -} - -fn vaxisStyle(s: pardes.CellStyle) vaxis.Style { - return .{ - .fg = vaxisColor(s.fg), - .bg = vaxisColor(s.bg), - .bold = s.bold, - .dim = s.dim, - .italic = s.italic, - .blink = s.blink, - .reverse = s.reverse, - .invisible = s.invisible, - .strikethrough = s.strikethrough, - .ul_style = switch (s.ul) { - .off => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; -} - -fn vaxisColor(c: pardes.Color) vaxis.Color { - return switch (c) { - .default => .default, - .index => |i| .{ .index = i }, - .rgb => |rgb| .{ .rgb = rgb }, - }; -} - -test "a jump leaves a trail of a few cells behind the cursor that fades in 120 ms" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); - try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); - core.settings.jump_trail = true; - for (0..40) |_| core.update(.tick); - core.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const s = try core.render(arena.allocator()); - const body = for (s.regionList()) |region| { - if (region.kind == .body) break region.rect; - } else return error.NoBody; - var trail: JumpTrail = .{}; - core.now_ns = std.time.ns_per_s; - s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; - _ = try trail.apply(arena.allocator(), s, core, true); - // Ten cells right: a trail back toward where it was. - s.cursor = .{ .x = body.x + 12, .y = body.y + 1 }; - core.now_ns += 16 * std.time.ns_per_ms; - const lit = try trail.apply(arena.allocator(), s, core, true); - try std.testing.expect(trail.active and core.shell_continuous); - var changed: usize = 0; - for (lit.cells, s.cells, 0..) |a, b, i| { - if (std.meta.eql(a.style.bg, b.style.bg)) continue; - changed += 1; - // On the cursor's row, behind it, never its own cell. - try std.testing.expectEqual(@as(usize, body.y + 1), i / s.cols); - try std.testing.expect(i % s.cols < body.x + 12 and i % s.cols > body.x + 2); - } - try std.testing.expect(changed >= 3 and changed <= 5); - // Gone by 120 ms; a step of a cell leaves none; nor a terminal without - // truecolor. - core.now_ns += 130 * std.time.ns_per_ms; - core.shell_continuous = false; - const faded = try trail.apply(arena.allocator(), s, core, true); - try std.testing.expect(faded == s and !trail.active and !core.shell_continuous); - s.cursor = .{ .x = body.x + 13, .y = body.y + 1 }; - try std.testing.expect(try trail.apply(arena.allocator(), s, core, true) == s); - s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; - try std.testing.expect(try trail.apply(arena.allocator(), s, core, false) == s); -} - -test "a notice chip casts a cell's shadow right and down, inside its body, off the cursor" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); - try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); - core.settings.chip_shadow = true; - try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice")); - for (0..60) |_| core.update(.tick); - core.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const s = try core.render(arena.allocator()); - const chip = for (s.regionList()) |region| { - if (region.kind == .notice) break region.rect; - } else return error.NoNotice; - s.cursor = null; - const out = try chipShadows(arena.allocator(), s, core, true); - try std.testing.expect(out != s); - var changed: usize = 0; - for (out.cells, s.cells, 0..) |a, b, i| { - if (std.meta.eql(a, b)) continue; - changed += 1; - const x = i % s.cols; - const y = i / s.cols; - // Right of the chip or below it, never inside it. - try std.testing.expect(x == chip.x + chip.w or y == chip.y + chip.h); - try std.testing.expect(!(x >= chip.x and x < chip.x + chip.w and y >= chip.y and y < chip.y + chip.h)); - } - try std.testing.expect(changed >= chip.w - 1); - // Off, or without truecolor: the frame as it was. - try std.testing.expect(try chipShadows(arena.allocator(), s, core, false) == s); - core.settings.chip_shadow = false; - try std.testing.expect(try chipShadows(arena.allocator(), s, core, true) == s); -} - -test "a scrolled pane's thumb brightens and fades back in 250 ms" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([200][20]u8, @splat("some text on a line\n".*)))); - try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); - core.settings.thumb_flash = true; - for (0..40) |_| core.update(.tick); - core.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var flash: ThumbFlash = .{}; - core.now_ns = std.time.ns_per_s; - const first = try core.render(arena.allocator()); - try std.testing.expect(try flash.apply(arena.allocator(), first, core, true) == first); - pane.scrollBy(20); - core.now_ns += 16 * std.time.ns_per_ms; - const moved = try core.render(arena.allocator()); - const lit = try flash.apply(arena.allocator(), moved, core, true); - try std.testing.expect(lit != moved and core.shell_continuous); - var brighter: usize = 0; - for (lit.cells, moved.cells) |a, b| { - if (!std.meta.eql(a.style.bg, b.style.bg)) brighter += 1; - } - try std.testing.expect(brighter >= 1); - core.now_ns += 300 * std.time.ns_per_ms; - core.shell_continuous = false; - const later = try core.render(arena.allocator()); - try std.testing.expect(try flash.apply(arena.allocator(), later, core, true) == later); - try std.testing.expect(!core.shell_continuous); -} diff --git a/src/tui/panel_compositor.zig b/src/tui/panel_compositor.zig new file mode 100644 index 00000000..67d3a6e6 --- /dev/null +++ b/src/tui/panel_compositor.zig @@ -0,0 +1,706 @@ +//! TTY implementation of panel transitions. +//! +//! The core publishes presentation cells plus POD tracks. It has already +//! composed PanelAscii because byte stepping is semantic, while this backend +//! copies the grid for geometry and dissolve operations. No terminal escape +//! trick or pixel assumption leaks into the core. + +const std = @import("std"); +const pardes = @import("../pardes.zig"); +const layout = @import("../layout.zig"); +const animation = @import("../animation.zig"); + +const Box = animation.Box; +const Track = animation.Track; + +/// Kitty placements cannot be resampled through the character-grid transform. +/// Keep their transmitted pixels cached, but omit the placement while its pane +/// geometry moves. Data effects animate changed grid cells in place and have +/// no honest old Kitty bitmap, so leaving an unchanged attachment canonical is +/// better than making it disappear for the whole reveal and pop back. +pub fn hidesAttachment(tracks: []const Track, serial: u32) bool { + for (tracks) |track| { + if (track.serial != serial or !track.active()) continue; + if (track.effect != .slide and track.effect != .zoom and track.effect != .vertical) continue; + // The last active sample is already the exact canonical frame. Place + // the image there too, rather than making it pop in one tick later. + if (track.frame + 1 < track.frames()) return true; + } + return false; +} + +/// Return `source` unchanged when idle, otherwise an arena-owned Surface whose +/// cells contain this frame's TTY presentation. Geometry exposed by a moving +/// panel uses the theme's page background when it has one; null deliberately +/// leaves the host terminal's default background showing. +pub fn compose( + arena: std.mem.Allocator, + source: *pardes.Surface, + tracks: []const Track, + theme_bg: ?[3]u8, +) !*pardes.Surface { + var active = false; + var noncanonical = false; + for (tracks) |track| { + if (!drawable(source, track)) continue; + active = true; + noncanonical = noncanonical or track.amount() < 1.0; + } + if (!active) return source; + // Every effect's last active sample is its exact canonical endpoint. Keep + // the real cursor and attachments in that sample instead of suppressing + // them for one extra frame that is otherwise pixel-identical. + if (!noncanonical) return source; + + const out = try arena.create(pardes.Surface); + out.* = source.*; + out.cells = try arena.dupe(pardes.Cell, source.cells); + // A cursor has no pane/phase record of its own. All native backends hide + // it for the short transition rather than disagreeing about whether it + // should move, stay static, or cover an overlapping opening pane. + out.cursor = null; + + // Clear every final geometry before drawing any presented geometry. If + // clear and draw are interleaved, a new panel can erase the old full-width + // panel that was deliberately drawn underneath it at frame zero. + for (tracks) |track| + if (drawable(source, track) and (track.effect == .slide or track.effect == .zoom)) + clearBox(out, track.to, theme_bg); + + // A vertical opener starts over the exact old pixels in its fixed target + // clip. Its new content then rises into that clip from below. Restore all + // bases before painting anything so an opener cannot erase an earlier + // moving panel merely because its pane slot sorts later. + for (tracks) |track| + if (drawable(source, track) and track.effect == .vertical and track.phase == .opening) + restorePrevious(out, source, track.contentBox()); + + // Stable layout motion first, newly opening panels above it, and closing + // tombstones last. A closing pane no longer owns input or canonical cells, + // but its frozen old content remains the top visual until it slides out. + for ([_]animation.Phase{ .moving, .opening, .closing }) |phase| { + for (tracks) |track| { + if (!drawable(source, track) or track.phase != phase) continue; + switch (track.effect) { + .off => {}, + .slide, .zoom => transform(out, source, track), + .dissolve => dissolve(out, source, track), + // Pardes core has already composed every character effect + // into source.cells — byte walks, glyph motion, and per-cell + // locks are semantic. TTY only owns cursor suppression here. + .ascii, .edges, .fall, .wave, .curtain, .scramble, .typewriter => {}, + .vertical => vertical(out, source, track), + } + } + } + return out; +} + +/// Content effects have no honest frame without the frozen old grid. In +/// production the core drops such tracks before publishing Surface; retain +/// this guard at the backend boundary so a partial/custom caller also snaps +/// to canonical content instead of manufacturing blanks. +fn drawable(source: *const pardes.Surface, track: Track) bool { + return track.active() and + (!track.effect.needsPreviousGrid() or source.hasPanelDiff()); +} + +fn transform(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { + const shown = track.presented(); + if (shown.w <= 0 or shown.h <= 0) return; + const dst = clipped(shown, out.cols, out.rows) orelse return; + var y = dst.y0; + while (y < dst.y1) : (y += 1) { + var x = dst.x0; + while (x < dst.x1) : (x += 1) { + // The core hit-tests cell CENTRES against this same half-open box. + // floor/ceil clipping includes boundary cells for iteration, but + // they are not visible unless their centre is actually inside. + // Test that containment before division: at large u16 grids f32 + // can round an inside right-edge ratio to exactly 1.0. + const cx = @as(f32, @floatFromInt(x)) + 0.5; + const cy = @as(f32, @floatFromInt(y)) + 0.5; + if (cx < shown.x or cx >= shown.x + shown.w or + cy < shown.y or cy >= shown.y + shown.h) continue; + const u = std.math.clamp((cx - shown.x) / shown.w, 0, 0.999_999); + const v = std.math.clamp((cy - shown.y) / shown.h, 0, 0.999_999); + const sx: i32 = @intFromFloat(@floor(track.to.x + u * track.to.w)); + const sy: i32 = @intFromFloat(@floor(track.to.y + v * track.to.h)); + if (sx < 0 or sy < 0 or sx >= source.cols or sy >= source.rows) continue; + out.at(x, y).* = source.cells[@as(usize, @intCast(sy)) * source.cols + @as(usize, @intCast(sx))]; + } + } +} + +fn dissolve(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { + const area = clipped(track.to, out.cols, out.rows) orelse return; + const amount = track.amount(); + var y = area.y0; + while (y < area.y1) : (y += 1) { + var x = area.x0; + while (x < area.x1) : (x += 1) { + if (!source.panelCellChanged(x, y)) continue; + if (animation.dissolveRevealed( + track.serial, + x - area.x0, + y - area.y0, + amount, + )) continue; + out.at(x, y).* = previousCell(source, x, y).*; + } + } +} + +fn previousCell(source: *const pardes.Surface, x: u16, y: u16) *const pardes.Cell { + std.debug.assert(source.hasPanelDiff()); + return &source.previous_cells[@as(usize, y) * source.cols + x]; +} + +fn restorePrevious(out: *pardes.Surface, source: *const pardes.Surface, box: Box) void { + const area = clipped(box, out.cols, out.rows) orelse return; + var y = area.y0; + while (y < area.y1) : (y += 1) { + var x = area.x0; + while (x < area.x1) : (x += 1) + out.at(x, y).* = previousCell(source, x, y).*; + } +} + +fn vertical(out: *pardes.Surface, source: *const pardes.Surface, track: Track) void { + const cells = if (track.phase == .closing) source.previous_cells else source.cells; + transformClipped(out, source.cols, source.rows, cells, track, track.contentBox()); +} + +/// Translate one old/new canonical panel through its fixed lifecycle clip. +/// Sampling is always relative to contentBox: an opener reads its new target, +/// while a closer reads the old box retained after that pane was destroyed. +fn transformClipped( + out: *pardes.Surface, + source_cols: u16, + source_rows: u16, + cells: []const pardes.Cell, + track: Track, + clip: Box, +) void { + const shown = track.presented(); + if (shown.w <= 0 or shown.h <= 0) return; + const dst = clipped(shown, out.cols, out.rows) orelse return; + const content = track.contentBox(); + var y = dst.y0; + while (y < dst.y1) : (y += 1) { + var x = dst.x0; + while (x < dst.x1) : (x += 1) { + const cx = @as(f32, @floatFromInt(x)) + 0.5; + const cy = @as(f32, @floatFromInt(y)) + 0.5; + if (cx < shown.x or cx >= shown.x + shown.w or + cy < shown.y or cy >= shown.y + shown.h or + cx < clip.x or cx >= clip.x + clip.w or + cy < clip.y or cy >= clip.y + clip.h) continue; + const u = std.math.clamp((cx - shown.x) / shown.w, 0, 0.999_999); + const v = std.math.clamp((cy - shown.y) / shown.h, 0, 0.999_999); + const sx: i32 = @intFromFloat(@floor(content.x + u * content.w)); + const sy: i32 = @intFromFloat(@floor(content.y + v * content.h)); + if (sx < 0 or sy < 0 or sx >= source_cols or sy >= source_rows) continue; + out.at(x, y).* = cells[@as(usize, @intCast(sy)) * source_cols + @as(usize, @intCast(sx))]; + } + } +} + +fn clearBox(surface: *pardes.Surface, box: Box, theme_bg: ?[3]u8) void { + const area = clipped(box, surface.cols, surface.rows) orelse return; + var blank: pardes.Cell = .{}; + if (theme_bg) |rgb| { + blank.default = false; + blank.style.bg = .{ .rgb = rgb }; + } + var y = area.y0; + while (y < area.y1) : (y += 1) { + var x = area.x0; + while (x < area.x1) : (x += 1) surface.at(x, y).* = blank; + } +} + +const GridBox = struct { x0: u16, y0: u16, x1: u16, y1: u16 }; + +fn clipped(box: Box, cols: u16, rows: u16) ?GridBox { + const x0: i32 = @intFromFloat(@floor(box.x)); + const y0: i32 = @intFromFloat(@floor(box.y)); + const x1: i32 = @intFromFloat(@ceil(box.x + box.w)); + const y1: i32 = @intFromFloat(@ceil(box.y + box.h)); + const area: GridBox = .{ + .x0 = @intCast(std.math.clamp(x0, 0, @as(i32, cols))), + .y0 = @intCast(std.math.clamp(y0, 0, @as(i32, rows))), + .x1 = @intCast(std.math.clamp(x1, 0, @as(i32, cols))), + .y1 = @intCast(std.math.clamp(y1, 0, @as(i32, rows))), + }; + return if (area.x0 < area.x1 and area.y0 < area.y1) area else null; +} + +test "TTY consumes core-composed ASCII cells without reinterpreting glyphs" { + var cells: [8]pardes.Cell = @splat(.{}); + var previous: [8]pardes.Cell = @splat(.{}); + const diffs: [8]pardes.PanelCellDiff = @splat(.visual); + for (&cells) |*cell| { + cell.text[0] = 'X'; + cell.len = 1; + cell.default = false; + } + for (&previous) |*cell| { + cell.text[0] = 'O'; + cell.len = 1; + cell.default = false; + } + var surface: pardes.Surface = .{ + .cols = 4, + .rows = 2, + .cells = &cells, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const track: Track = .{ + .serial = 9, + .effect = .ascii, + .frame = 0, + .from = .{ .w = 4, .h = 2 }, + .to = .{ .w = 4, .h = 2 }, + }; + const animated = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expect(animated != &surface); + try std.testing.expectEqualStrings("X", surface.at(0, 0).grapheme()); + for (animated.cells) |cell| try std.testing.expectEqualStrings("X", cell.grapheme()); +} + +test "dissolve changes only diff cells from old to new" { + var cells: [2]pardes.Cell = @splat(.{}); + var previous: [2]pardes.Cell = @splat(.{}); + for (&cells, "NU") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + for (&previous, "OU") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + const diffs = [_]pardes.PanelCellDiff{ .{ .ascii = .{ .from = 'O', .to = 'N' } }, .unchanged }; + var surface: pardes.Surface = .{ + .cols = 2, + .rows = 1, + .cells = &cells, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var track: Track = .{ + .serial = 1, + .effect = .dissolve, + .from = .{ .w = 2, .h = 1 }, + .to = .{ .w = 2, .h = 1 }, + }; + + const first = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqualStrings("O", first.at(0, 0).grapheme()); + try std.testing.expectEqual(cells[1], first.at(1, 0).*); + + _ = arena.reset(.retain_capacity); + track.frame = track.effect.frames() - 1; + const final = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqual(cells[0], final.at(0, 0).*); + try std.testing.expectEqual(cells[1], final.at(1, 0).*); +} + +test "TTY content effects never touch cells outside the published diff" { + var cells: [4]pardes.Cell = @splat(.{}); + var previous: [4]pardes.Cell = @splat(.{}); + for (&cells, "NUQV") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + // Deliberately disagree even where the mask says unchanged. This makes + // the test prove that the compositor obeys the core cell diff rather than + // merely appearing correct because old and new happened to match there. + for (&previous, "OXRY") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + const diffs = [_]pardes.PanelCellDiff{ .visual, .unchanged, .visual, .unchanged }; + var surface: pardes.Surface = .{ + .cols = 4, + .rows = 1, + .cells = &cells, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + + for ([_]animation.Transition{ .ascii, .dissolve }) |effect| { + const track: Track = .{ + .serial = 17, + .effect = effect, + .from = .{ .w = 4, .h = 1 }, + .to = .{ .w = 4, .h = 1 }, + }; + const animated = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqual(cells[1], animated.at(1, 0).*); + try std.testing.expectEqual(cells[3], animated.at(3, 0).*); + _ = arena.reset(.retain_capacity); + } +} + +test "content transition without a diff snaps to canonical surface" { + var cells = [_]pardes.Cell{.{}}; + cells[0].text[0] = 'N'; + cells[0].default = false; + var surface: pardes.Surface = .{ + .cols = 1, + .rows = 1, + .cells = &cells, + .cursor = .{ .x = 0, .y = 0 }, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + + for ([_]animation.Transition{ .dissolve, .ascii, .vertical }) |effect| { + const track: Track = .{ + .effect = effect, + .phase = .opening, + .from = .{ .y = 1, .w = 1, .h = 1 }, + .to = .{ .w = 1, .h = 1 }, + }; + try std.testing.expectEqual(&surface, try compose(arena.allocator(), &surface, &.{track}, null)); + } +} + +test "exact transition endpoint preserves the canonical cursor" { + var cells = [_]pardes.Cell{.{}}; + var previous = cells; + const diffs = [_]pardes.PanelCellDiff{.visual}; + var surface: pardes.Surface = .{ + .cols = 1, + .rows = 1, + .cells = &cells, + .cursor = .{ .x = 0, .y = 0 }, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + const track: Track = .{ + .effect = .ascii, + .frame = animation.Transition.ascii.frames() - 1, + .from = .{ .w = 1, .h = 1 }, + .to = .{ .w = 1, .h = 1 }, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + + const result = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqual(&surface, result); + try std.testing.expect(result.cursor != null); +} + +test "vertical opening rises through a fixed old-grid clip" { + var cells: [12]pardes.Cell = @splat(.{}); + var previous: [12]pardes.Cell = @splat(.{}); + for (&cells, "aaabbbcccddd") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + for (&previous, "000111222333") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + const diffs: [12]pardes.PanelCellDiff = @splat(.visual); + var surface: pardes.Surface = .{ + .cols = 3, + .rows = 4, + .cells = &cells, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const target: Box = .{ .y = 1, .w = 3, .h = 2 }; + var track: Track = .{ + .serial = 5, + .phase = .opening, + .effect = .vertical, + .from = animation.openingBox(.vertical, target, 3), + .to = target, + }; + + const first = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqualStrings("1", first.at(0, 1).grapheme()); + try std.testing.expectEqualStrings("2", first.at(0, 2).grapheme()); + try std.testing.expectEqualStrings("a", first.at(0, 0).grapheme()); + try std.testing.expectEqualStrings("d", first.at(0, 3).grapheme()); + + _ = arena.reset(.retain_capacity); + track.frame = 2; + const entering = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqualStrings("1", entering.at(0, 1).grapheme()); + try std.testing.expectEqualStrings("b", entering.at(0, 2).grapheme()); + try std.testing.expectEqualStrings("a", entering.at(0, 0).grapheme()); + try std.testing.expectEqualStrings("d", entering.at(0, 3).grapheme()); + + _ = arena.reset(.retain_capacity); + track.frame = track.effect.frames() - 1; + const final = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqualStrings("b", final.at(0, 1).grapheme()); + try std.testing.expectEqualStrings("c", final.at(0, 2).grapheme()); +} + +test "vertical closing drops frozen content over canonical cells" { + var cells: [12]pardes.Cell = @splat(.{}); + var previous: [12]pardes.Cell = @splat(.{}); + for (&cells, "aaabbbcccddd") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + for (&previous, "000111222333") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + const diffs: [12]pardes.PanelCellDiff = @splat(.visual); + var surface: pardes.Surface = .{ + .cols = 3, + .rows = 4, + .cells = &cells, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const old_box: Box = .{ .y = 1, .w = 3, .h = 2 }; + var track: Track = .{ + .serial = 5, + .phase = .closing, + .effect = .vertical, + .from = old_box, + .to = animation.closingBox(.vertical, old_box), + }; + + const first = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqualStrings("1", first.at(0, 1).grapheme()); + try std.testing.expectEqualStrings("2", first.at(0, 2).grapheme()); + + _ = arena.reset(.retain_capacity); + track.frame = 8; + const leaving = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqualStrings("b", leaving.at(0, 1).grapheme()); + try std.testing.expectEqualStrings("1", leaving.at(0, 2).grapheme()); + try std.testing.expectEqualStrings("a", leaving.at(0, 0).grapheme()); + try std.testing.expectEqualStrings("d", leaving.at(0, 3).grapheme()); + + _ = arena.reset(.retain_capacity); + track.frame = track.effect.frames() - 1; + const final = try compose(arena.allocator(), &surface, &.{track}, null); + try std.testing.expectEqual(cells[3], final.at(0, 1).*); + try std.testing.expectEqual(cells[6], final.at(0, 2).*); +} + +test "closing content paints after opening content regardless of track order" { + var cells = [_]pardes.Cell{.{}}; + var previous = [_]pardes.Cell{.{}}; + cells[0].text[0] = 'N'; + cells[0].default = false; + previous[0].text[0] = 'O'; + previous[0].default = false; + const diffs = [_]pardes.PanelCellDiff{.visual}; + var surface: pardes.Surface = .{ + .cols = 1, + .rows = 1, + .cells = &cells, + .previous_cells = &previous, + .cell_diffs = &diffs, + }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const box: Box = .{ .w = 1, .h = 1 }; + const closing: Track = .{ + .serial = 1, + .phase = .closing, + .effect = .vertical, + .from = box, + .to = animation.closingBox(.vertical, box), + }; + const opening: Track = .{ + .serial = 2, + .phase = .opening, + .effect = .ascii, + .frame = animation.Transition.ascii.frames() - 1, + .from = box, + .to = box, + }; + + const animated = try compose(arena.allocator(), &surface, &.{ closing, opening }, null); + try std.testing.expectEqualStrings("O", animated.at(0, 0).grapheme()); +} + +test "opening panel cannot erase an existing panel drawn underneath" { + var cells: [8]pardes.Cell = @splat(.{}); + for (&cells, 0..) |*cell, x| { + cell.text[0] = if (x < 4) 'A' else 'B'; + cell.len = 1; + cell.default = false; + } + var surface: pardes.Surface = .{ .cols = 8, .rows = 1, .cells = &cells }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const tracks = [_]Track{ + .{ + .serial = 1, + .phase = .moving, + .effect = .slide, + .from = .{ .w = 8, .h = 1 }, + .to = .{ .w = 4, .h = 1 }, + }, + .{ + .serial = 2, + .phase = .opening, + .effect = .slide, + .from = .{ .x = 8, .w = 4, .h = 1 }, + .to = .{ .x = 4, .w = 4, .h = 1 }, + }, + }; + const animated = try compose(arena.allocator(), &surface, &tracks, null); + try std.testing.expectEqualStrings("A", animated.at(7, 0).grapheme()); +} + +test "geometry gap is a blank painted in an explicit theme background" { + var cells: [4]pardes.Cell = @splat(.{}); + for (&cells, "ABCD") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + cell.style = .{ + .fg = .{ .rgb = .{ 220, 210, 200 } }, + .bg = .{ .rgb = .{ 30, 20, 10 } }, + .bold = true, + .font_role = .tagline, + }; + } + var surface: pardes.Surface = .{ .cols = 4, .rows = 1, .cells = &cells }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const track: Track = .{ + .serial = 1, + .effect = .slide, + .from = .{ .x = 2, .w = 2, .h = 1 }, + .to = .{ .w = 4, .h = 1 }, + }; + const page_bg = [3]u8{ 248, 244, 232 }; + const animated = try compose(arena.allocator(), &surface, &.{track}, page_bg); + + const gap = animated.at(0, 0); + try std.testing.expect(!gap.default); + try std.testing.expectEqualStrings(" ", gap.grapheme()); + try std.testing.expectEqual(pardes.Color{ .rgb = page_bg }, gap.style.bg); + try std.testing.expectEqual(pardes.Color.default, gap.style.fg); + try std.testing.expect(!gap.style.bold); + try std.testing.expectEqual(pardes.FontRole.body, gap.style.font_role); + // The clear supplies only exposed geometry. Cells sampled from the moving + // panel retain all canonical content and style fields byte-for-byte. + try std.testing.expectEqual(cells[1], animated.at(2, 0).*); +} + +test "geometry gap stays terminal-default for a transparent theme" { + var cells: [2]pardes.Cell = @splat(.{}); + for (&cells, "AB") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + var surface: pardes.Surface = .{ .cols = 2, .rows = 1, .cells = &cells }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const track: Track = .{ + .serial = 1, + .effect = .slide, + .from = .{ .x = 1, .w = 1, .h = 1 }, + .to = .{ .w = 2, .h = 1 }, + }; + const animated = try compose(arena.allocator(), &surface, &.{track}, null); + + const gap = animated.at(0, 0); + try std.testing.expect(gap.default); + try std.testing.expectEqualStrings(" ", gap.grapheme()); + try std.testing.expectEqual(pardes.Color.default, gap.style.bg); +} + +test "fractional geometry draws exactly the cell centres core can hit" { + var cells: [3]pardes.Cell = @splat(.{}); + for (&cells, "ABC") |*cell, glyph| { + cell.text[0] = glyph; + cell.len = 1; + cell.default = false; + } + var surface: pardes.Surface = .{ .cols = 3, .rows = 1, .cells = &cells }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const track: Track = .{ + .serial = 1, + .effect = .slide, + .from = .{ .x = 0.9, .w = 1, .h = 1 }, + .to = .{ .x = 0, .w = 1, .h = 1 }, + }; + const animated = try compose(arena.allocator(), &surface, &.{track}, null); + // Cell 0 lies in floor/ceil iteration bounds, but its centre (0.5) is + // outside [0.9, 1.9); cell 1 is the only presented/hit-testable cell. + try std.testing.expectEqualStrings(" ", animated.at(0, 0).grapheme()); + try std.testing.expectEqualStrings("A", animated.at(1, 0).grapheme()); +} + +test "large-grid right edge uses containment before rounded ratio" { + const cols = std.math.maxInt(u16); + const source_cells = try std.testing.allocator.alloc(pardes.Cell, cols); + defer std.testing.allocator.free(source_cells); + const output_cells = try std.testing.allocator.alloc(pardes.Cell, cols); + defer std.testing.allocator.free(output_cells); + @memset(source_cells, .{}); + @memset(output_cells, .{}); + for (source_cells) |*cell| { + cell.text[0] = 'X'; + cell.len = 1; + cell.default = false; + } + var source: pardes.Surface = .{ .cols = cols, .rows = 1, .cells = source_cells }; + var output: pardes.Surface = .{ .cols = cols, .rows = 1, .cells = output_cells }; + const track: Track = .{ + .serial = 1, + .effect = .zoom, + .frame = 8, + .from = .{ .x = 56_796, .w = 8_299, .h = 1 }, + .to = .{ .x = 556, .w = 63_483, .h = 1 }, + }; + const shown = track.presented(); + try std.testing.expect(@as(f32, 63_935.5) < shown.x + shown.w); + transform(&output, &source, track); + try std.testing.expectEqualStrings("X", output.at(63_935, 0).grapheme()); +} + +test "active panel transition hides only its own native attachment" { + const tracks = [_]Track{ + .{ .serial = 41, .effect = .slide, .frame = 0 }, + .{ .serial = 42, .effect = .ascii, .frame = 0 }, + .{ .serial = 43, .effect = .zoom, .frame = animation.Transition.zoom.frames() - 1 }, + .{ .serial = 44, .effect = .zoom, .frame = animation.Transition.zoom.frames() }, + .{ .serial = 45, .phase = .opening, .effect = .vertical, .frame = 0 }, + }; + + try std.testing.expect(hidesAttachment(&tracks, 41)); + try std.testing.expect(!hidesAttachment(&tracks, 42)); + try std.testing.expect(!hidesAttachment(&tracks, 43)); + try std.testing.expect(!hidesAttachment(&tracks, 44)); + try std.testing.expect(hidesAttachment(&tracks, 45)); + try std.testing.expect(!hidesAttachment(&tracks, 46)); +} diff --git a/src/tui/tui.zig b/src/tui/tui.zig new file mode 100644 index 00000000..e7fde434 --- /dev/null +++ b/src/tui/tui.zig @@ -0,0 +1,4017 @@ +const filesystem = @import("../fs.zig"); +const std = @import("std"); +const builtin = @import("builtin"); +const posix = std.posix; +const libc = std.c; +const vaxis = @import("vaxis"); +const pardes = @import("../pardes.zig"); +const vaxis_input = @import("../vaxis_input.zig"); +const dump = @import("../dump.zig"); +const tracy = @import("../tracy.zig"); +const look = @import("../look.zig"); +const message = pardes.Messages.Message; +const file_watch = @import("../file_watch.zig"); +const selection_pipe = @import("../selection_pipe.zig"); +const ninep_io = @import("../9p_io.zig"); +const panel_compositor = @import("panel_compositor.zig"); +const daemon = @import("../daemon.zig"); +const host_io = @import("../host_io.zig"); +const upgrade = @import("../upgrade.zig"); +const replica = @import("../replica.zig"); +const wire = @import("../detached/wire.zig"); + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + +const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); + +/// What a terminal's input reader keeps, one a terminal (views.zig): its +/// graphemes, the frame it waits on the answer to, the shm probe, and the +/// view its input is. +const Feed = struct { + view: u8 = 0, + cache: vaxis.GraphemeCache = .{}, + ack: FrameAck = .{}, + /// The terminal answered the shared-memory probe (`kittyShmProbe`): it + /// can read a raster from a POSIX shm object, so a page costs a name on + /// the wire instead of its whole base64 body. Set by the input reader, + /// which sees the reply before vaxis' parser swallows every graphics APC + /// alike. + shm: std.atomic.Value(bool) = .init(false), + /// Only a reply that arrives while the probe is out counts. The id is + /// one vaxis' own image numbering (1, 2, ...) never reaches, because a + /// terminal answers every transmission `i=;OK` and one of those must + /// not pass. + shm_probing: std.atomic.Value(bool) = .init(false), +}; + +/// A terminal's input onto the loop's queue, as its view's: a `from` goes +/// ahead of it whenever another terminal posted last. With one terminal +/// none ever does. +const Poster = struct { + loop: *Loop, + view: u8, + var lock: std.Io.Mutex = .init; + var last: u8 = 0; + + pub fn postEvent(p: Poster, ev: @TypeOf(Command.value)) !void { + lock.lockUncancelable(p.loop.io); + defer lock.unlock(p.loop.io); + if (last != p.view) { + try p.loop.postEvent(.{ .from = p.view }); + last = p.view; + } + try p.loop.postEvent(ev); + } +}; +const kitty_shm_probe_id = 0x7fff_fff1; +var kitty_shm_serial: u32 = 0; +/// Transmissions an unread shm segment outlives before it is removed. +const kitty_shm_window = 64; + +fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); +} + +/// A terminal unlinks what it reads; whatever it never read (the probe +/// unanswered, a transmission lost with the terminal) is ours to remove. +fn unlinkKittyShm() void { + var name_buf: [64]u8 = undefined; + var n: u32 = 0; + while (n <= kitty_shm_serial) : (n += 1) { + if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} + } +} + +/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading. +fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { + const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600)); + if (fd < 0) return false; + defer _ = libc.close(fd); + if (libc.ftruncate(fd, @intCast(bytes.len)) != 0) { + _ = libc.shm_unlink(name); + return false; + } + var off: usize = 0; + while (off < bytes.len) { + const n = libc.write(fd, bytes[off..].ptr, bytes.len - off); + if (n <= 0) { + _ = libc.shm_unlink(name); + return false; + } + off += @intCast(n); + } + return true; +} + +/// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A +/// remote terminal cannot see our shm and answers an error (or nothing). +fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { + var buf: [64]u8 = undefined; + const name = kittyShmName(&buf, 0) catch return; + if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; + var b64: [64]u8 = undefined; + const enc = std.base64.standard.Encoder.encode(&b64, name); + feed.shm_probing.store(true, .release); + w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; + w.flush() catch {}; +} + +pub const Command = struct { + pub var value: union(enum) { + nop, + /// The terminal's input ended: its end of file, a hangup. A session + /// a daemon keeps carries on detached; any other ends. + quit, + /// A terminal for this detached session, and its stub's pipe + /// (daemon.Note.attach). + attach: struct { tty: posix.fd_t, stub: posix.fd_t }, + /// A shell a dead session left, its pty's master (daemon.Note.adopted). + adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, + /// A timed wait ran out: the core's next wake has come. + wake, + /// The input after this is the terminal of this view's (Poster). + from: u8, + /// A SIGWINCH: a terminal changed size (Shell.winched). + winched, + /// A SIGHUP: the session's own terminal hung up. + hangup, + key_press: vaxis.Key, + pty_read: struct { id: usize, gen: u32, bytes: []u8 }, + pty_eof: struct { id: usize, gen: u32 }, + winsize: vaxis.Winsize, + mouse: vaxis.Mouse, + focus_in, + focus_out, + paste: []const u8, + paste_start, + paste_end, + lsp_done: struct { id: u32, rows: ?[]u8 }, + lsp_status: []u8, + pipe_done: selection_pipe.Response, + /// A streaming search's rows (pardes.Stream). + search_rows: pardes.Stream.Batch, + files_changed, + fs_ready, + /// A replica's connection, handed over by the daemon (Peers). + replica: daemon.Joining, + /// A replica's reader posted: the step boundary takes it in. + replica_mail, + /// A replica client's: what the session streamed (replica.Link). + said: replica.Said, + link_gone, + } = .nop; +}; +const Loop = vaxis.Loop(@TypeOf(Command.value)); + +fn startInput(loop: *Loop, sc: *Screen) !void { + if (comptime builtin.os.tag == .windows) return loop.start(); + if (sc.thread != null) return; + sc.thread = try loop.io.concurrent(inputThread, .{ loop, sc }); +} + +fn stopInput(io: std.Io, thread: *?std.Io.Future(void)) void { + if (thread.*) |*t| { + t.cancel(io); + thread.* = null; + } +} + +fn inputThread(loop: *Loop, sc: *Screen) void { + // vaxis's test terminal reads nothing off Linux: it has no read at all. + if (comptime !@hasDecl(vaxis.Tty, "read")) return; + inputReader(loop, &sc.tty, &sc.vx, &sc.feed); +} + +fn inputReader(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) void { + readInput(loop, tty, vx, feed) catch |err| { + if (err == error.Canceled) return; + std.log.err("terminal input: {s}", .{@errorName(err)}); + }; + (Poster{ .loop = loop, .view = feed.view }).postEvent(.quit) catch {}; +} + +fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { + const post: Poster = .{ .loop = loop, .view = feed.view }; + try post.postEvent(.{ .winsize = try tty.getWinsize() }); + var parser: vaxis.Parser = .{}; + var buf: [1024]u8 = undefined; + var carried: usize = 0; + while (true) { // stopInput cancels the task; the read then fails with Canceled + if (carried == buf.len) return error.InputSequenceTooLong; + const received = try tty.read(buf[carried..]); + if (received == 0) return; + // The terminal's answers to frames (FrameAck) come out first, + // wherever they sit: never events, and never glued to a key (an + // Escape pressed just before one would read as Alt on it). + const end = feed.ack.take(buf[0 .. carried + received], loop); + if (end == 0) { + carried = 0; + continue; + } + if (feed.shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { + feed.shm_probing.store(false, .release); + feed.shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); + // Answered either way: a terminal that could not read it left it. + var name_buf: [64]u8 = undefined; + if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} + }; + var parse_end = end; + var lead = end; + while (lead > 0 and buf[lead - 1] & 0xc0 == 0x80) lead -= 1; + if (lead > 0) { + const scalar_len = std.unicode.utf8ByteSequenceLength(buf[lead - 1]) catch 1; + if (scalar_len > end - (lead - 1)) parse_end = lead - 1; + } + var consumed: usize = 0; + // A read that is one ESC and nothing else is the Escape key: a + // terminal writes each key's sequence whole and ssh carries each of + // its writes whole, so no sequence arrives cut right after its ESC. + // Waiting on it cost every Escape press 50 ms on a legacy terminal + // (tmux, most ssh sessions), and 1 s before kitty's flags were on. + // (A terminal's answer to a frame is one write too: FrameAck.) + var waited = carried == 0 and end == 1; + while (consumed < parse_end) { + // A lone ESC that ends a longer read is the Escape key, or the + // first byte of a sequence whose rest the read boundary held + // back (an ssh packet, a busy link), which parsed now left the + // rest to be typed as text. Wait a moment for more. Under the + // kitty keyboard protocol Escape is `CSI 27 u`, so there the ESC + // can only start a sequence and the wait can be long. + const rest = buf[consumed..parse_end]; + // A frame's answer cut short by the read waits for its rest. + if (parse_end == end and rest.len > 1 and rest.len < FrameAck.answer.len and + std.mem.startsWith(u8, FrameAck.answer, rest)) break; + if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) { + waited = true; + if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break; + } + const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator); + if (result.n == 0) break; + consumed += result.n; + // A modifier pressed on its own, which the kitty keyboard + // protocol reports: pardes binds none, it would break a pending + // chord, and a shell pane was typed its private-use code. + if (result.event) |event| if (event == .key_press and event.key_press.isModifier()) continue; + if (result.event) |event| + vaxis.loop.handleEventGeneric(post, vx, &feed.cache, @TypeOf(Command.value), event, vx.opts.system_clipboard_allocator) catch |err| { + if (event == .paste) if (vx.opts.system_clipboard_allocator) |gpa| gpa.free(@constCast(event.paste)); + return err; + }; + // The last answer to the startup queries is no event of its + // own: wake the loop so it takes the capabilities up (pollFrame) + // now. Left to the first key, that key paid for the full redraw + // they cost, and kitty's keys came in the legacy way till then. + if (result.event) |event| if (event == .cap_da1) { + _ = loop.tryPostEvent(.nop) catch {}; + }; + } + carried = end - consumed; + std.mem.copyForwards(u8, buf[0..carried], buf[consumed..end]); + } +} + +/// One frame in flight at most. Each frame the tty draws ends with a device +/// status request (`CSI 5 n`), and no other frame is drawn until the +/// terminal's `CSI 0 n` comes back: over ssh the frames a burst of scrolling +/// or typing would queue behind each other (sshd's window holds megabytes) +/// are never drawn, and the burst ends one frame and one round trip after +/// its last input. On a local terminal the answer is back in well under a +/// millisecond. A terminal that never answers turns this off for good after +/// `timeout_ns`. +const FrameAck = struct { + const request = "\x1b[5n"; + const answer = "\x1b[0n"; + const timeout_ns: u64 = std.time.ns_per_s; + waiting: std.atomic.Value(bool) = .init(false), + off: std.atomic.Value(bool) = .init(false), + /// When the request went out (the loop's thread only). + sent_ns: u64 = 0, + + /// Take every answer out of `bytes`, closing up the rest; the new + /// length. The loop is woken for the frame that waited on one. + fn take(a: *FrameAck, bytes: []u8, loop: *Loop) usize { + var len = bytes.len; + var found = false; + while (std.mem.indexOf(u8, bytes[0..len], answer)) |at| { + std.mem.copyForwards(u8, bytes[at..], bytes[at + answer.len .. len]); + len -= answer.len; + found = true; + } + if (found and a.waiting.swap(false, .acq_rel)) loop.postEvent(.nop) catch {}; + return len; + } + + /// Whether a new frame must wait (and the loop has a wake at the + /// timeout); past the timeout the terminal is taken to never answer. + fn holds(a: *FrameAck, now_ns: u64, io: std.Io) bool { + if (a.off.load(.acquire) or !a.waiting.load(.acquire)) return false; + const waited_ns = now_ns -| a.sent_ns; + if (waited_ns >= timeout_ns) { + a.off.store(true, .release); + a.waiting.store(false, .release); + return false; + } + requestWake(io, @intCast((timeout_ns - waited_ns + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); + return true; + } + + /// After a frame that wrote something: ask for the answer. + fn ask(a: *FrameAck, w: *std.Io.Writer, now_ns: u64) void { + if (a.off.load(.acquire)) return; + // Waiting before the request goes: a local terminal can answer + // before the write returns, and an answer nobody waited for is lost. + a.sent_ns = now_ns; + a.waiting.store(true, .release); + w.writeAll(request) catch return a.waiting.store(false, .release); + w.flush() catch return a.waiting.store(false, .release); + } +}; + +/// Whether more input is readable within `ms`, polled in short slices so +/// that a cancel of the input thread is still seen. A test reader answers +/// for itself. +fn inputFollows(tty: anytype, io: std.Io, ms: u32) !bool { + if (@hasDecl(@TypeOf(tty.*), "inputFollows")) return tty.inputFollows(ms); + const handle = if (@TypeOf(tty.fd) == std.Io.File) tty.fd.handle else tty.fd; + var fds = [_]posix.pollfd{.{ .fd = handle, .events = posix.POLL.IN, .revents = 0 }}; + var left = ms; + while (left > 0) : (left -|= 10) { + try io.checkCancel(); + if (try posix.poll(&fds, @intCast(@min(left, 10))) > 0) return true; + } + return false; +} + +test "terminal input preserves fragmented keys queries paste and text after EOF" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + vx.queries_done.store(false, .unordered); + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + const Reader = struct { + parts: []const []const u8, + next: usize = 0, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(self: *@This(), _: u32) bool { + return self.next < self.parts.len; + } + fn read(self: *@This(), buf: []u8) !usize { + if (self.next == self.parts.len) return 0; + const part = self.parts[self.next]; + self.next += 1; + @memcpy(buf[0..part.len], part); + return part.len; + } + }; + var reader: Reader = .{ .parts = &.{ + "plain \x1b[?62;", "4c\x1b[", "A\x1b[200", "~caf\xc3", "\xa9 \xe7", "\x95", + "\x8c \xf0\x9f", "\x98\x80", "\x1b[201", "~\x1b]52;c;Y2", "xpcA==\x07tail", "\x1b", + } }; + try readInput(&loop, &reader, &vx, &feed); + try std.testing.expect(vx.queries_done.load(.unordered)); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var resized = false; + var up = false; + var in_paste = false; + var pasted = false; + var clipboard = false; + var escape = false; + while (try loop.tryEvent()) |event| switch (event) { + .winsize => |size| { + try std.testing.expect(!resized); + resized = true; + try std.testing.expectEqual(@as(u16, 80), size.cols); + }, + .key_press => |key| { + try std.testing.expect(resized); + if (key.codepoint == vaxis.Key.up) { + up = true; + } else if (key.codepoint == vaxis.Key.escape) { + escape = true; + } else if (key.text) |bytes| { + if (in_paste) try std.testing.expect(up); + try text.appendSlice(gpa, bytes); + } else return error.UnexpectedInputKey; + }, + .paste_start => { + try std.testing.expect(up and !in_paste); + in_paste = true; + }, + .paste_end => { + try std.testing.expect(in_paste); + in_paste = false; + pasted = true; + }, + .paste => |bytes| { + defer gpa.free(@constCast(bytes)); + try std.testing.expect(pasted and !in_paste); + try std.testing.expectEqualStrings("clip", bytes); + clipboard = true; + }, + // The device attributes' wake (a capability answer). + .nop => try std.testing.expect(vx.queries_done.load(.unordered)), + else => return error.UnexpectedInputEvent, + }; + try std.testing.expectEqualStrings("plain café 界 😀tail", text.items); + try std.testing.expect(resized and up and pasted and clipboard and escape); +} + +test "terminal replies and malformed sequences never become typed text" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + vx.queries_done.store(false, .unordered); + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + const Reader = struct { + parts: []const []const u8, + next: usize = 0, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(self: *@This(), _: u32) bool { + return self.next < self.parts.len; + } + fn read(self: *@This(), buf: []u8) !usize { + if (self.next == self.parts.len) return 0; + const part = self.parts[self.next]; + self.next += 1; + @memcpy(buf[0..part.len], part); + return part.len; + } + }; + var reader: Reader = .{ + .parts = &.{ + // The startup width queries' answers where the terminal has no + // explicit width: both used to arrive as a bare F3, typed as text. + "a\x1b[1;1R\x1b[1;1R", + // A late report somewhere else on the screen, and DECXCPR. + "\x1b[12;40R\x1b[?3;7;1R", + // rxvt's Alt+Up: ESC before the sequence, not Alt+Esc then `[A`. + "b\x1b\x1b[A", + // A kitty graphics reply cut inside its ST sliced past its input. + "\x1b_Gi=1;OK\x1b", + "\\", + // An X10 mouse report cut after `CSI M` left three bytes as text. + "\x1b[M", + " !!", + // Malformed color and clipboard replies failed the parse, which + // ended input altogether; and a reply ended by BEL ran on to the + // next sequence's ESC, leaving what lay between as text. + "\x1b]11;rgb:zz/zz/zz\x1b\\\x1b]52;c;!!!!\x07\x1b]52\x07", + // Device reports whose fields end early. + "\x1b[?1;y\x1b[?997;n\x1b[c", + "\x1b[?62;c", + "c", + }, + }; + try readInput(&loop, &reader, &vx, &feed); + try std.testing.expect(vx.queries_done.load(.unordered)); + try std.testing.expect(vx.caps.kitty_graphics); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var alt_up = false; + var clicked = false; + while (try loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |key| { + if (key.codepoint == vaxis.Key.up and key.mods.alt) { + alt_up = true; + } else if (key.text) |bytes| { + try text.appendSlice(gpa, bytes); + } else return error.UnexpectedInputKey; + }, + .mouse => |mouse| { + try std.testing.expectEqual(@as(i16, 0), mouse.col); + clicked = true; + }, + .nop => {}, // the device attributes' wake + else => return error.UnexpectedInputEvent, + }; + try std.testing.expectEqualStrings("abc", text.items); + try std.testing.expect(alt_up and clicked); +} + +test "terminal input split at every byte with a gap reads as it does whole" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{ .system_clipboard_allocator = gpa }); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + // Two reads with `gap_ms` between them, as an ssh link delivers a + // sequence cut across two packets. + const Reader = struct { + parts: [2][]const u8, + gap_ms: u32, + next: usize = 0, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(self: *@This(), ms: u32) bool { + return self.next < self.parts.len and self.gap_ms <= ms; + } + fn read(self: *@This(), buf: []u8) !usize { + while (self.next < self.parts.len) { + const part = self.parts[self.next]; + self.next += 1; + if (part.len == 0) continue; + @memcpy(buf[0..part.len], part); + return part.len; + } + return 0; + } + /// What the loop was handed, one line per event. + fn events(l: *Loop, out: *std.ArrayList(u8)) !void { + out.clearRetainingCapacity(); + while (try l.tryEvent()) |event| switch (event) { + .winsize => {}, + .key_press => |k| try out.print(std.testing.allocator, "key {d} {d} {?s}\n", .{ k.codepoint, @as(u8, @bitCast(k.mods)), k.text }), + .mouse => |m| try out.print(std.testing.allocator, "mouse {d} {d} {t} {t}\n", .{ m.col, m.row, m.button, m.type }), + .paste => |bytes| { + try out.print(std.testing.allocator, "paste {s}\n", .{bytes}); + std.testing.allocator.free(@constCast(bytes)); + }, + else => |other| try out.print(std.testing.allocator, "{t}\n", .{other}), + }; + } + }; + const Case = struct { bytes: []const u8, kitty: bool = false }; + const cases = [_]Case{ + .{ .bytes = "\x1b[118;5u", .kitty = true }, // Ctrl-V + .{ .bytes = "\x1b[97;;97u", .kitty = true }, // a, with its text + .{ .bytes = "\x1b[57442;5u", .kitty = true }, // Ctrl on its own + .{ .bytes = "\x1b[27u", .kitty = true }, // Escape + .{ .bytes = "\x1b[A" }, + .{ .bytes = "\x1bOA" }, + .{ .bytes = "\x1b[3;5~" }, + .{ .bytes = "\x1b\x1b[A" }, + // Four wheel notches: cut at a `;` with 60 ms between the halves, + // ssh's framing lost all four. + .{ .bytes = "\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M\x1b[<65;10;5M" }, + .{ .bytes = "\x1b[200~pasted\x1b[201~" }, + .{ .bytes = "\x1b]52;c;Y2xpcA==\x1b\\" }, + .{ .bytes = "\x1b_Gi=1;OK\x1b\\" }, + .{ .bytes = "\x1bP>|kitty(0.40)\x1b\\" }, + }; + var whole: std.ArrayList(u8) = .empty; + defer whole.deinit(gpa); + var split: std.ArrayList(u8) = .empty; + defer split.deinit(gpa); + for (cases) |case| { + vx.caps.kitty_keyboard = case.kitty; + const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); + defer gpa.free(all); + var one: Reader = .{ .parts = .{ all, "" }, .gap_ms = 0 }; + try readInput(&loop, &one, &vx, &feed); + try Reader.events(&loop, &whole); + for (1..all.len) |cut| { + // A cut just after an ESC is the one that has to wait, and a + // legacy terminal's Escape waits only 50 ms: 40 ms there. A cut + // anywhere else is carried however long the gap. + const after_esc = all[cut - 1] == 0x1b; + var two: Reader = .{ .parts = .{ all[0..cut], all[cut..] }, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; + try readInput(&loop, &two, &vx, &feed); + try Reader.events(&loop, &split); + std.testing.expectEqualStrings(whole.items, split.items) catch |err| { + std.debug.print("case {f} cut at {d}\n", .{ std.ascii.hexEscape(case.bytes, .lower), cut }); + return err; + }; + } + } + vx.caps.kitty_keyboard = false; +} + +test "an ESC read by itself is the Escape key at once" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{}); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + // More always follows at once: a reader that waited on the ESC would + // take `j` for the rest of its sequence (Alt-j). + const Reader = struct { + parts: []const []const u8, + next: usize = 0, + asked: bool = false, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(self: *@This(), _: u32) bool { + self.asked = true; + return self.next < self.parts.len; + } + fn read(self: *@This(), buf: []u8) !usize { + if (self.next == self.parts.len) return 0; + const part = self.parts[self.next]; + self.next += 1; + @memcpy(buf[0..part.len], part); + return part.len; + } + }; + for ([_]bool{ false, true }) |kitty| { + vx.caps.kitty_keyboard = kitty; + var reader: Reader = .{ .parts = &.{ "\x1b", "j" } }; + try readInput(&loop, &reader, &vx, &feed); + try std.testing.expect(!reader.asked); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); + const escape = (try loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + const j = (try loop.tryEvent()).?.key_press; + try std.testing.expectEqual(@as(u21, 'j'), j.codepoint); + try std.testing.expect(!j.mods.alt); + try std.testing.expect(try loop.tryEvent() == null); + } + vx.caps.kitty_keyboard = false; +} + +test "a frame's answer is taken wherever the reads cut it, and never typed" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{}); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + const Reader = struct { + parts: [2][]const u8, + next: usize = 0, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(self: *@This(), _: u32) bool { + return self.next < self.parts.len; + } + fn read(self: *@This(), buf: []u8) !usize { + while (self.next < self.parts.len) { + const part = self.parts[self.next]; + self.next += 1; + if (part.len == 0) continue; + @memcpy(buf[0..part.len], part); + return part.len; + } + return 0; + } + }; + const all = "x" ++ FrameAck.answer ++ "y"; + defer feed.ack.waiting.store(false, .release); + for (0..all.len) |cut| { + feed.ack.waiting.store(true, .release); + var reader: Reader = .{ .parts = .{ all[0..cut], all[cut..] } }; + try readInput(&loop, &reader, &vx, &feed); + try std.testing.expect(!feed.ack.waiting.load(.acquire)); + var typed: std.ArrayList(u8) = .empty; + defer typed.deinit(gpa); + var woke = false; + while (try loop.tryEvent()) |event| switch (event) { + .winsize => {}, + .nop => woke = true, + .key_press => |key| try typed.appendSlice(gpa, key.text orelse return error.UnexpectedInputKey), + else => return error.UnexpectedInputEvent, + }; + std.testing.expectEqualStrings("xy", typed.items) catch |err| { + std.debug.print("cut at {d}\n", .{cut}); + return err; + }; + try std.testing.expect(woke); + } + // An Escape pressed just before an answer, in the same read, is the + // Escape key, not Alt on the answer. + feed.ack.waiting.store(true, .release); + var glued: Reader = .{ .parts = .{ "\x1b" ++ FrameAck.answer, "j" } }; + try readInput(&loop, &glued, &vx, &feed); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try loop.tryEvent()).?)); + try std.testing.expectEqual(.nop, std.meta.activeTag((try loop.tryEvent()).?)); + const escape = (try loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + try std.testing.expectEqual(@as(u21, 'j'), (try loop.tryEvent()).?.key_press.codepoint); + try std.testing.expect(try loop.tryEvent() == null); +} + +test "a terminal that never answers a frame stops being asked after one timeout" { + const io = std.testing.io; + var ack: FrameAck = .{}; + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + const t0: u64 = 5 * std.time.ns_per_s; + ack.ask(&out.writer, t0); + try std.testing.expectEqualStrings(FrameAck.request, out.written()); + // Unanswered: the next frame waits, until the timeout. + try std.testing.expect(ack.holds(t0 + 10 * std.time.ns_per_ms, io)); + try std.testing.expect(ack.holds(t0 + 999 * std.time.ns_per_ms, io)); + try std.testing.expect(!ack.holds(t0 + FrameAck.timeout_ns, io)); + // Then never again: no request, no wait. + out.clearRetainingCapacity(); + ack.ask(&out.writer, t0 + 2 * std.time.ns_per_s); + try std.testing.expectEqual(@as(usize, 0), out.written().len); + try std.testing.expect(!ack.holds(t0 + 2 * std.time.ns_per_s, io)); +} + +test "terminal input cancellation joins blocked reads and queued EOF" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{}); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + const Reader = struct { + file: std.Io.File, + eof: bool, + entered: std.Io.Event = .unset, + release: std.Io.Event = .unset, + returned: std.Io.Event = .unset, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(_: *@This(), _: u32) bool { + return false; + } + fn read(self: *@This(), buf: []u8) !usize { + self.entered.set(std.testing.io); + if (self.eof) { + try self.release.wait(std.testing.io); + self.returned.set(std.testing.io); + return 0; + } + return self.file.readStreaming(std.testing.io, &.{buf}); + } + fn run(loop: *Loop, reader: *@This(), vx_: *vaxis.Vaxis, feed: *Feed) void { + inputReader(loop, reader, vx_, feed); + } + }; + const Case = enum { blocked_read, cancel_eof, deliver_eof }; + for (std.enums.values(Case)) |case| { + const eof = case != .blocked_read; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + defer _ = libc.close(fds[0]); + defer _ = libc.close(fds[1]); + var reader: Reader = .{ .file = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .eof = eof }; + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &vx, &feed }); + defer stopInput(io, &thread); + try std.testing.expectEqual(.winsize, std.meta.activeTag(try loop.nextEvent())); + try reader.entered.wait(io); + if (eof) { + for (0..512) |_| try loop.postEvent(.nop); + reader.release.set(io); + try reader.returned.wait(io); + } + if (case == .deliver_eof) { + try std.testing.expectEqual(.nop, std.meta.activeTag(try loop.nextEvent())); + thread.?.await(io); + } + stopInput(io, &thread); + try std.testing.expect(thread == null); + var count: usize = 0; + while (try loop.tryEvent()) |event| { + const expected: std.meta.Tag(@TypeOf(Command.value)) = if (case == .deliver_eof and count == 511) .quit else .nop; + try std.testing.expectEqual(expected, std.meta.activeTag(event)); + count += 1; + } + try std.testing.expectEqual(@as(usize, if (eof) 512 else 0), count); + } +} + +const PipeTasks = selection_pipe.Tasks; + +const Pty = struct { + file: std.Io.File, + pid: posix.pid_t, + reader: std.Io.Future(anyerror!void), + /// A command pane's child, watched to its exit (host_io.watchExit); + /// the pty stays open until both its end of file and its exit. + cmd: host_io.CommandWatch = .{}, +}; + +/// A watched child exited: wake the loop, which takes it (`takeExits`). +fn wakeForExit(ctx: ?*anyopaque) void { + const loop: *Loop = @ptrCast(@alignCast(ctx.?)); + _ = loop.tryPostEvent(.nop) catch {}; +} + +const KittyPlacement = struct { + cell_x: u16, + cell_y: u16, + cell_cols: u16, + cell_rows: u16, + options: vaxis.Image.DrawOptions, +}; + +fn terminalCellPixels(total_pixels: u16, cells: u16, fallback: u32) u32 { + if (total_pixels == 0 or cells == 0) return fallback; + return @max(1, @as(u32, total_pixels) / cells); +} + +fn updateCoreTerminalSize(core: *pardes.Pardes, cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) void { + core.update(.{ .resize = terminalSize(cols, rows, pixel_w, pixel_h) }); +} + +fn terminalSize(cols: u16, rows: u16, pixel_w: u16, pixel_h: u16) @FieldType(pardes.Event, "resize") { + return .{ + .cols = cols, + .rows = rows, + .cell_pixels = .{ + .w = @intCast(terminalCellPixels(pixel_w, cols, 8)), + .h = @intCast(terminalCellPixels(pixel_h, rows, 16)), + }, + }; +} + +/// A terminal pane's image fragment (`native.exact`): its `src` into its +/// `dst`, inside one cell row. Kitty scales a source rectangle to whole +/// cells, so the source is trimmed to the cells' scale rather than the +/// picture stretched: a fragment loses under a cell at its right edge. +/// A full row is declared one row high; a part of one (an image's top or +/// bottom edge) only its columns, its height then following the source. +fn exactKittyPlacement( + place: pardes.ImagePlace, + screen_cols: u16, + screen_rows: u16, + screen_pixel_w: u16, + screen_pixel_h: u16, +) ?KittyPlacement { + if (comptime !pardes.pdf_enabled) return null; + const g = place.native.geometry orelse return null; + const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); + const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); + if (g.dst.w == 0 or g.dst.h == 0 or g.src.w == 0 or g.src.h == 0) return null; + const cell_x = g.dst.x / cell_w; + const pixel_x = g.dst.x % cell_w; + const pixel_y = @min(g.dst.y, cell_h - 1); + const cols: u32 = @max(1, (g.dst.w + cell_w / 2) / cell_w); + if (cell_x >= place.w) return null; + const declared_w = cols * cell_w; + // At the cells' scale, the source that fills `cols` cells. + var src_w = g.src.w; + if (declared_w < g.dst.w) src_w = @max(1, @as(u32, @intCast(@as(u64, g.src.w) * declared_w / g.dst.w))); + var src_h = g.src.h; + const full = g.dst.y == 0 and g.dst.h >= cell_h; + if (!full) { + // As tall as it is at that scale, and no taller than the row. + const room = cell_h - pixel_y; + const fits: u32 = @intCast(@as(u64, room) * src_w / declared_w); + if (fits == 0) return null; + src_h = @min(src_h, fits); + } + return .{ + .cell_x = std.math.cast(u16, cell_x) orelse return null, + .cell_y = 0, + .cell_cols = std.math.cast(u16, @min(@as(u32, place.w) - cell_x, (pixel_x + declared_w + cell_w - 1) / cell_w)) orelse return null, + .cell_rows = 1, + .options = .{ + .clip_region = .{ + .x = std.math.cast(u16, g.src.x) orelse return null, + .y = std.math.cast(u16, g.src.y) orelse return null, + .width = std.math.cast(u16, src_w) orelse return null, + .height = std.math.cast(u16, src_h) orelse return null, + }, + .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = @intCast(pixel_x), .y = @intCast(pixel_y) } else null, + // The outer terminal stacks them, under the text below 0. + .z_index = if (place.z != 0) place.z else null, + .size = if (full) + .{ .cols = std.math.cast(u16, cols) orelse return null, .rows = 1 } + else + .{ .cols = std.math.cast(u16, cols) orelse return null }, + }, + }; +} + +fn kittyPlacement( + place: pardes.ImagePlace, + screen_cols: u16, + screen_rows: u16, + screen_pixel_w: u16, + screen_pixel_h: u16, +) ?KittyPlacement { + if (comptime pardes.pdf_enabled) { + if (place.native.fit == .contain) return null; + const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); + const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); + const body_w = std.math.mul(u32, place.w, cell_w) catch return null; + const body_h = std.math.mul(u32, place.h, cell_h) catch return null; + const geometry = place.native.geometry orelse pardes.image.nativeGeometry( + place.iw, + place.ih, + body_w, + body_h, + place.native.fit, + place.native.pan_x, + place.native.pan_y, + ) orelse return null; + + const safe_rows_u32 = geometry.dst.h / cell_h; + if (safe_rows_u32 == 0) return null; + const safe_pixel_h = safe_rows_u32 * cell_h; + var safe_src_h: u32 = geometry.src.h; + var declared_cols: u32 = 0; + var declared_rows: u32 = 0; + switch (place.native.fit) { + .width => { + declared_cols = @intCast(@max( + @as(u64, 1), + (@as(u64, geometry.dst.w) + cell_w - 1) / cell_w, + )); + const declared_pixel_w = @as(u64, declared_cols) * cell_w; + const max_src_h: u32 = @intCast( + @as(u64, safe_pixel_h) * geometry.src.w / declared_pixel_w, + ); + if (max_src_h == 0) return null; + safe_src_h = @min(safe_src_h, max_src_h); + const aspect_pixel_h: u32 = @intCast( + (@as(u64, safe_src_h) * declared_pixel_w + geometry.src.w - 1) / + geometry.src.w, + ); + declared_rows = @intCast( + (@as(u64, aspect_pixel_h) + cell_h - 1) / cell_h, + ); + }, + .height => { + declared_rows = safe_rows_u32; + safe_src_h = @max(@as(u32, 1), @as(u32, @intCast( + @as(u64, safe_pixel_h) * geometry.src.h / geometry.dst.h, + ))); + safe_src_h = @min(safe_src_h, geometry.src.h); + const aspect_pixel_w: u32 = @intCast( + (@as(u64, geometry.src.w) * safe_pixel_h + safe_src_h - 1) / + safe_src_h, + ); + declared_cols = @intCast( + (@as(u64, aspect_pixel_w) + cell_w - 1) / cell_w, + ); + }, + .contain => unreachable, + } + if (declared_rows == 0 or declared_rows > safe_rows_u32) return null; + + const src_x = std.math.cast(u16, geometry.src.x) orelse return null; + const src_y = std.math.cast(u16, geometry.src.y) orelse return null; + const src_w = std.math.cast(u16, geometry.src.w) orelse return null; + const src_h = std.math.cast(u16, safe_src_h) orelse return null; + const cell_x = std.math.cast(u16, geometry.dst.x / cell_w) orelse return null; + const cell_y = std.math.cast(u16, geometry.dst.y / cell_h) orelse return null; + if (cell_x >= place.w or cell_y >= place.h) return null; + const pixel_x = std.math.cast(u16, geometry.dst.x % cell_w) orelse return null; + const pixel_y = std.math.cast(u16, geometry.dst.y % cell_h) orelse return null; + const cell_cols = std.math.cast(u16, @min( + @as(u32, place.w - cell_x), + (@as(u64, pixel_x) + @as(u64, declared_cols) * cell_w + cell_w - 1) / cell_w, + )) orelse return null; + const cell_rows = std.math.cast(u16, @min( + @as(u32, place.h - cell_y), + (@as(u64, pixel_y) + declared_rows * cell_h + cell_h - 1) / cell_h, + )) orelse return null; + if (cell_cols == 0 or cell_rows == 0) return null; + + return .{ + .cell_x = cell_x, + .cell_y = cell_y, + .cell_cols = cell_cols, + .cell_rows = cell_rows, + .options = .{ + .clip_region = .{ .x = src_x, .y = src_y, .width = src_w, .height = src_h }, + .pixel_offset = if (pixel_x != 0 or pixel_y != 0) .{ .x = pixel_x, .y = pixel_y } else null, + .size = switch (place.native.fit) { + .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, + .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, + .contain => unreachable, + }, + }, + }; + } else { + return null; + } +} + +test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { + if (comptime !pardes.pdf_enabled) return; + var place = pardes.ImagePlace{ + .pane = 0, + .serial = 3, + .native = .{ .page = 7, .exact = true, .geometry = .{ + .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, + .dst = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, + } }, + .x = 99, + .y = 4, + .w = 24, + .h = 1, + .rgba = &.{}, + .iw = 240, + .ih = 160, + }; + // 10x20 pixel cells: a whole row, one to one. + const full = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(u16, 0), full.cell_x); + try std.testing.expectEqual(@as(?u16, 24), full.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, 1), full.options.size.?.rows); + try std.testing.expectEqual(@as(?u16, 40), full.options.clip_region.?.y); + try std.testing.expectEqual(@as(?u16, 240), full.options.clip_region.?.width); + try std.testing.expect(full.options.pixel_offset == null); + + // The top of a letterboxed picture: 7 pixels down into the row, 13 + // tall, 35 pixels in, 205 wide, which rounds to 21 cells. Its columns + // only, its source no taller than the 13 pixels left in the row at + // that scale. + place.native.geometry = .{ + .src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }, + .dst = .{ .x = 35, .y = 7, .w = 205, .h = 13 }, + }; + const top = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(u16, 3), top.cell_x); + try std.testing.expectEqual(@as(u16, 5), top.options.pixel_offset.?.x); + try std.testing.expectEqual(@as(u16, 7), top.options.pixel_offset.?.y); + try std.testing.expectEqual(@as(?u16, 21), top.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, null), top.options.size.?.rows); + const w = top.options.clip_region.?.width.?; + const h = top.options.clip_region.?.height.?; + try std.testing.expectEqual(@as(u16, 205), w); + try std.testing.expect(h > 0 and @as(u32, h) * 210 / w <= 13); + + // Narrower than its cells round to: the source is cut to their scale. + place.native.geometry = .{ + .src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }, + .dst = .{ .x = 0, .y = 0, .w = 204, .h = 20 }, + }; + const cut = exactKittyPlacement(place, 100, 30, 1000, 600).?; + try std.testing.expectEqual(@as(?u16, 20), cut.options.size.?.cols); + try std.testing.expectEqual(@as(?u16, 392), cut.options.clip_region.?.width); +} + +test "Kitty PDF fragments never declare pixels beyond their clipped bottom" { + if (comptime !pardes.pdf_enabled) return; + + const base = pardes.ImagePlace{ + .pane = 0, + .serial = 1, + .native = .{ + .revision = 1, + .page = 0, + .fit = .width, + .geometry = .{ + .src = .{ .w = 96, .h = 10 }, + .dst = .{ .y = 195, .w = 304, .h = 29 }, + }, + }, + .x = 0, + .y = 0, + .w = 38, + .h = 14, + .rgba = &.{}, + .iw = 96, + .ih = 64, + }; + const width = kittyPlacement(base, 80, 16, 640, 256) orelse + return error.MissingSafeKittyWidthFragment; + const width_clip = width.options.clip_region.?; + const width_size = width.options.size.?; + try std.testing.expectEqual(@as(u16, 5), width_clip.height.?); + try std.testing.expectEqual(@as(u16, 38), width_size.cols.?); + try std.testing.expectEqual(@as(u16, 3), width.options.pixel_offset.?.y); + const aspect_pixels = (@as(u32, width_size.cols.?) * 8 * width_clip.height.? + + width_clip.width.? - 1) / width_clip.width.?; + const inferred_rows = (aspect_pixels + 15) / 16; + try std.testing.expect(inferred_rows * 16 <= base.native.geometry.?.dst.h); + + var height = base; + height.native.fit = .height; + height.native.geometry.?.src.h = 9; + const height_fragment = kittyPlacement(height, 80, 16, 640, 256) orelse + return error.MissingSafeKittyHeightFragment; + try std.testing.expectEqual(@as(u16, 1), height_fragment.options.size.?.rows.?); + try std.testing.expect(@as(u32, height_fragment.options.size.?.rows.?) * 16 <= + height.native.geometry.?.dst.h); + + height.native.geometry.?.dst.h = 13; + try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); +} + +test "host watch closes initial race and reloads rename-over PDF while idle" { + if (comptime !file_watch.supported or !pardes.pdf_enabled) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const original = try pardes.pdf.makeOutlineTestPdf(gpa); + defer gpa.free(original); + const replacement = try pardes.pdf.makeNoOutlineTestPdf(gpa); + defer gpa.free(replacement); + try tmp.dir.writeFile(io, .{ .sub_path = "live.pdf", .data = original }); + try tmp.dir.writeFile(io, .{ .sub_path = "initial.pdf", .data = replacement }); + try tmp.dir.writeFile(io, .{ .sub_path = "live-replacement.pdf", .data = original }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/live.pdf", .{tmp.sub_path}); + + const fd = file_watch.init(true); + if (fd < 0) return error.WatchInitFailed; + defer _ = libc.close(fd); + var watches: file_watch.Table = @splat(null); + defer for (0..pardes.MAX_PANES) |id| file_watch.watchPane( + fd, + &watches, + @intCast(id), + null, + 0, + .{ .text = 0 }, + ); + + const core = try pardes.Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 }); + defer core.deinit(); + try std.testing.expectEqual(@as(usize, 3), core.panes[0].?.pdf.?.page_count); + + try tmp.dir.rename("initial.pdf", tmp.dir, "live.pdf", io); + var armed = false; + while (core.nextEffect()) |effect| switch (effect) { + .watch => |watch| if (watch.pane == 0 and watch.on) { + armed = true; + try std.testing.expect(!file_watch.applyEffect(core, io, fd, &watches, 0, true, watch.mode)); + }, + else => {}, + }; + try std.testing.expect(armed and watches[0] != null); + try std.testing.expectEqual(@as(usize, 1), core.panes[0].?.pdf.?.page_count); + + try tmp.dir.rename("live-replacement.pdf", tmp.dir, "live.pdf", io); + try std.testing.expect(file_watch.drain(fd)); + + try std.testing.expect(!file_watch.reloadChanged(core, io, gpa, &watches)); + const pane = core.panes[0].?; + try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count); + const disk_identity = try file_watch.identify(io, path); + switch (watches[0].?.generation) { + .pdf => |accepted| try std.testing.expect(accepted != null and accepted.?.eql(disk_identity)), + .text => return error.PdfWatchStoredTextGeneration, + } + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "reloaded") != null); + + core.native_images = true; + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const surface = try core.render(frame.allocator()); + try std.testing.expect(surface.nimages > 0); + try std.testing.expectEqual(@as(u32, 0), surface.images[0].?.native.page); +} + +fn kittyImageRepresentable(place: pardes.ImagePlace) bool { + return place.iw > 0 and place.ih > 0 and + place.iw <= std.math.maxInt(u16) and place.ih <= std.math.maxInt(u16); +} + +fn surfaceHasKittyKey(surface: *const pardes.Surface, key: pardes.ImageCacheKey) bool { + for (surface.images[0..surface.nimages]) |maybe| { + const place = maybe orelse continue; + if (comptime pardes.pdf_enabled) if (!kittyImageRepresentable(place)) continue; + if (place.cacheKey().eql(key)) return true; + } + return false; +} + +const PdfWheelTarget = struct { pane: usize, page: usize }; + +fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWheelTarget { + if (comptime !pardes.pdf_enabled) return null; + if (!core.native_images or mouse.type != .press or + (mouse.button != .wheel_up and mouse.button != .wheel_down) or + mouse.col < 0 or mouse.row < 0) return null; + const col: u16 = @intCast(mouse.col); + const row: u16 = @intCast(mouse.row); + for (core.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const rect = core.rects[id]; + if (col < rect.x or col >= rect.x + rect.w or + row < rect.y or row >= rect.y + rect.h) continue; + const page = pane.pdfPage() orelse return null; + return .{ .pane = id, .page = page }; + } + return null; +} + +/// Where a session's terminal comes from: /dev/tty, as a plain `pardes` +/// opens it; one open already (a session forked off its stub, +/// daemon.forkSession); or none, until one is attached (`--detach`). +/// The terminal a session starts on: /dev/tty, one its stub opened (an +/// upgraded session's is raw already, `termios` the cooked one), or none. +pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, none }; + +pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { + const io = init.io; + const gpa = init.gpa; + + var winch_set = posix.sigemptyset(); + posix.sigaddset(&winch_set, posix.SIG.WINCH); + // Kept by a daemon, a hangup is the terminal's end, not the session's: + // winchWatch takes it, and the session carries on detached. + if (daemon.link >= 0) posix.sigaddset(&winch_set, posix.SIG.HUP); + // FreeBSD drops a signal whose action is to be ignored (WINCH's + // default) as it is sent, sigwait or not: a handler keeps it. + if (comptime builtin.os.tag == .freebsd) + posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); + posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); + + var tty_buf: [0x10000]u8 = undefined; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + defer screen.kitty.deinit(); + switch (term) { + .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), + .fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)), + .none => {}, + } + defer screen.leave(); + + var paste_buf: std.Io.Writer.Allocating = .init(gpa); + defer paste_buf.deinit(); + var loop: Loop = .init(io, &screen.tty, &screen.vx); + + try localSession(init, opts, &screen, &loop, &paste_buf); +} + +/// A replica client's link to its session (`remote`), drawn here. +const Remote = struct { + link: replica.Link, + + /// The client's own view drawn on its terminal, outside any step: the + /// replica's digest stays the session's (views.drawOne). What the host + /// writes in the core as it presents (a frame skipped, one owed) is put + /// back, as the frame statistics are this process's. + fn draw(c: *Remote, s: *Shell) void { + const r = c.link.r; + const core = r.core(); + const skipped = core.present_skipped; + const needs = core.needs_frame; + core.frames.mark_start = pardes.FrameStats.nowNs(); + core.frames.mark_update = core.frames.mark_start; + r.draw(.{ .ctx = s, .f = Shell.present }); + core.frames.mark_render = core.frames.mark_update; + const drew = core.frames.bytes > 0; + c.link.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), false, c.link.owed); + core.present_skipped = skipped; + core.needs_frame = needs; + c.link.drawn(drew); + } +}; + +/// The session's stream, onto the loop: its units, and its end. +fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void { + defer done.store(true, .release); + const Post = struct { + fn post(l: *Loop, said: replica.Said) bool { + l.postEvent(.{ .said = said }) catch return false; + return true; + } + }; + replica.readLink(gpa, fd, rest, loop, Post.post); + loop.postEvent(.link_gone) catch {}; +} + +/// `pardes --attach=:` (and `:`, through +/// ssh, main.zig): this terminal a replica client of a session elsewhere +/// (docs/next-daemon.md, "Phase 5 part B notes"). Its own core, loaded +/// from the session's dump, applies its keys at once (src/replica.zig); +/// the session's units are the truth it rolls back to. Its own view of the +/// session is drawn here, as the session draws its terminals'. +pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far_link: bool) !void { + const io = init.io; + const gpa = init.gpa; + const Said = struct { + fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { + var said: [800]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&said, "pardes: --attach: " ++ fmt ++ "\n", args) catch "pardes: --attach failed\n") catch {}; + std.process.exit(1); + } + }; + var why: [600]u8 = @splat(0); + // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash, + // those it holds kept from the link, and its stream in zstd. A client + // on this machine's own socket is sent the dump whole, as before: a + // hash and a compression there cost more than the bytes. + const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else far_link; + var have_store: replica.Have = if (far) .init(io) else .{ .io = io }; + defer have_store.deinit(); + const have: ?*replica.Have = if (far) &have_store else null; + var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; + var joined = replica.dial(gpa, path, session, &why, have, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words}); + + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + pardes.image.start(io, allocs.image); + if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); + pardes.syntax.start(allocs.tree_sitter); + defer { + pardes.image.stop(); + if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + pardes.syntax.stop(); + } + var o = opts; + o.image_allocator = allocs.image; + o.pdf_allocator = allocs.pdf; + var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + // Its join's time, the dial and the load (PARDES_REPLICA_STATS). + var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); + + var winch_set = posix.sigemptyset(); + posix.sigaddset(&winch_set, posix.SIG.WINCH); + // A hangup ends it the normal way (`quit`), what it made kept on disk + // (`Have.keep`) and its ssh forward's socket unlinked (main.zig). + posix.sigaddset(&winch_set, posix.SIG.HUP); + hangup_quits = true; + if (comptime builtin.os.tag == .freebsd) + posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); + posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); + var tty_buf: [0x10000]u8 = undefined; + var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa), .primary = true }; + defer screen.kitty.deinit(); + try screen.enter(try vaxis.Tty.init(io, &tty_buf)); + defer screen.leave(); + defer screen.glide.deinit(gpa); + var paste_buf: std.Io.Writer.Allocating = .init(gpa); + defer paste_buf.deinit(); + var loop: Loop = .init(io, &screen.tty, &screen.vx); + var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); + defer frame_arena.deinit(); + var remote_link: Remote = .{ .link = .{ .r = r, .fd = joined.fd } }; + const link = &remote_link.link; + try link.fromEnv(gpa, init.environ_map); + defer link.deinit(gpa); + var sh: Shell = .{ + .io = io, + .gpa = gpa, + .lsp_gpa = allocs.lsp, + .core = r.core(), + .prompt_rcs = undefined, + .loop = &loop, + .frame = &frame_arena, + .paste_buf = &paste_buf, + .inotify_fd = -1, + .from = joined.view, + .remote = &remote_link, + }; + + try startInput(&loop, &screen); + defer stopInput(io, &screen.thread); + (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); + (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach(); + try screen.vx.queryTerminalSend(screen.tty.writer()); + // A join a pass: the first, and one after the replica diverged or the + // session let it go to upgrade. The terminal stays as it is. + while (true) { + r.gmtoff = joined.gmtoff; + sh.core = r.core(); + sh.from = joined.view; + sh.terms = @splat(null); + sh.terms[joined.view] = &screen; + screen.feed.view = joined.view; + link.reset(r, joined.fd); + link.joinedAs(&joined, dial_ms); + var reader_done: std.atomic.Value(bool) = .init(false); + const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); + // What it is, then its size, are its view's first inputs. + link.input(.{ .frontend = .{ .windowed = false } }); + screen.size = null; + sh.winched(); + screen.vx.queueRefresh(); + while (!link.quit) { + // Its predicted echo judged and caught up, once a frame. + if (r.echoFrame()) link.dirty = true; + if (link.dirty) remote_link.draw(&sh); + const first = (loop.tryEvent() catch null) orelse idle: { + // Idle, its frame drawn: the next key needs no copy taken. + r.ready(); + break :idle loop.nextEvent() catch break; + }; + var ev = first; + var batch: usize = 1; + while (true) { + _ = sh.apply(ev); + if (link.quit or (!sh.in_paste and batch >= 64)) break; + ev = (loop.tryEvent() catch null) orelse break; + batch += 1; + } + r.settle(); + if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { + screen.caps_pending = false; + screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; + screen.vx.queueRefresh(); + link.dirty = true; + } + if (link.owed or r.echo.changed) link.dirty = true; + // Predictions out: judged a frame at a time while they are. + if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms)); + if (link.quietCheck()) |ms| requestWake(io, ms); + if (r.diverged != null) link.quit = true; + } + if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); + if (!link.gone) replica.bye(joined.fd, r.diverged != null); + // The link's reader ends with the link, posting as it goes: what it + // and the terminal posted is let go until it has. Its end is read + // before the drain, not after: its last post (`link_gone`) comes + // just before it, and left queued it ended the next link at once. + _ = libc.shutdown(joined.fd, 2); + while (true) { + const ended = reader_done.load(.acquire); + while (loop.tryEvent() catch null) |ev| switch (ev) { + .said => |said| switch (said) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, + }, + .paste => |b| gpa.free(@constCast(b)), + else => {}, + }; + if (ended) break; + std.Thread.yield() catch {}; + } + reader.join(); + _ = libc.close(joined.fd); + joined.rest.deinit(gpa); + // Why it joins again, in a line over its frame until a key. + if (!link.rejoins()) { + // What it made since it joined, kept for its next start. + if (have) |h| h.keep(r.core()); + r.deinit(); + if (link.gone) { + screen.leave(); + Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session}); + } + return; + } + // The session again, the core it leaves held meanwhile: its blobs + // are not sent again. + if (have) |h| h.leaving(r.core()); + dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; + joined = replica.Link.redial(gpa, path, session, &why, have, r.diverged == null, joined.view) orelse { + screen.leave(); + Said.no(io, "could not join again: {s}", .{std.mem.sliceTo(&why, 0)}); + }; + if (have) |h| h.left(); + r.deinit(); + r = replica.Link.load(gpa, &joined, o, &why, have) orelse { + screen.leave(); + Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + }; + dial_ms = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); + } +} + + +/// A terminal a session draws on, while it has one: entered (raw, the +/// alternate screen, mouse and paste reports) and left (all of it put back, +/// the terminal closed) at the session's start and end, and at a detach and +/// a reattach in between (daemon.zig). One a view (views.zig): the session's +/// own (`primary`, its stub `daemon.stub`), and one more for each terminal +/// `pardes --attach`ed while it is attached, which keeps its own. +const Screen = struct { + io: std.Io, + gpa: std.mem.Allocator, + env: *std.process.Environ.Map, + buf: []u8, + tty: vaxis.Tty = undefined, + vx: vaxis.Vaxis = undefined, + on: bool = false, + primary: bool = false, + /// The pipe to its stub, an attached one's (the primary's is daemon.stub). + stub: posix.fd_t = -1, + /// Its slot in Killed. + killed: ?usize = null, + feed: Feed = .{}, + thread: ?std.Io.Future(void) = null, + kitty: std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), + caps_pending: bool = true, + /// Its size as last taken (`Shell.resized`). + size: ?vaxis.Winsize = null, + tracks: []const pardes.animation.Track = &.{}, + /// T2: the cursor's jump trail (JumpTrail). + trail: JumpTrail = .{}, + /// The view's glide, the GUI's motion drawn at whole rows (anim 12). + glide: pardes.glide.Glide = .{}, + /// T7: when each pane's view last moved (ThumbFlash). + flash: ThumbFlash = .{}, + + /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a + /// forked session is no controlling terminal of its, which /dev/tty is. + /// An upgraded session's is raw already, `cooked` what it goes back to. + fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t, cooked: ?posix.termios) !vaxis.Tty { + if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty + const termios = cooked orelse try vaxis.Tty.makeRaw(fd); + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) }; + } + + fn enter(sc: *Screen, tty: vaxis.Tty) !void { + sc.tty = tty; + errdefer sc.tty.deinit(); + sc.vx = try vaxis.init(sc.io, sc.gpa, sc.env, .{ .system_clipboard_allocator = sc.gpa }); + errdefer sc.vx.deinit(sc.gpa, sc.tty.writer()); + try sc.vx.enterAltScreen(sc.tty.writer()); + try sc.vx.setMouseMode(sc.tty.writer(), true); + try sc.vx.setBracketedPaste(sc.tty.writer(), true); + if (comptime !builtin.is_test) { + sc.killed = Killed.arm(sc.tty.fd.handle, sc.tty.termios); + // What a panic puts back (vaxis.recover). + if (sc.primary) vaxis.tty.global_tty = sc.tty; + } + const view = sc.feed.view; + sc.feed = .{ .view = view }; + sc.caps_pending = true; + sc.size = null; + sc.on = true; + } + + fn leave(sc: *Screen) void { + if (!sc.on) return; + sc.on = false; + if (sc.killed) |slot| Killed.disarm(slot); + sc.killed = null; + clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); + sc.vx.exitAltScreen(sc.tty.writer()) catch {}; + sc.vx.deinit(sc.gpa, sc.tty.writer()); + if (comptime !builtin.is_test) if (sc.primary) { + vaxis.tty.global_tty = null; + }; + sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets + } + + /// Its stub told the terminal is detached (it ends, and its shell has + /// the terminal back). + fn sayDetached(sc: *Screen) void { + if (sc.primary) return daemon.tellStubDetached(); + daemon.tellDetached(sc.stub); + sc.stub = -1; + } + + /// Its terminal hung up, or the stub that waits on it is gone. + fn hungUp(sc: *const Screen) bool { + const stub = if (sc.primary) daemon.stub else sc.stub; + const handle = if (@TypeOf(sc.tty.fd) == std.Io.File) sc.tty.fd.handle else sc.tty.fd; + var fds = [_]posix.pollfd{ + .{ .fd = handle, .events = 0, .revents = 0 }, + .{ .fd = stub, .events = 0, .revents = 0 }, + }; + _ = posix.poll(fds[0..if (stub >= 0) 2 else 1], 0) catch return false; + const gone = posix.POLL.HUP | posix.POLL.ERR; + return fds[0].revents & gone != 0 or (stub >= 0 and fds[1].revents & gone != 0); + } + + fn setStub(sc: *Screen, fd: posix.fd_t) void { + if (sc.primary) daemon.stub = fd else sc.stub = fd; + } +}; + +/// SIGTERM or SIGHUP: each terminal put back as a clean exit leaves it -- +/// the main screen, no mouse, paste or keyboard modes, the cursor shown, +/// cooked termios -- and then the signal's own death. A nested editor +/// killed in a pane must not leave that pane's terminal wedged. +/// Async-signal-safe: write, tcsetattr, sigaction, raise. +const Killed = struct { + var fds: [pardes.views.max]posix.fd_t = @splat(-1); + var cooked: [pardes.views.max]posix.termios = undefined; + const reset = "\x1b[= 0) { + _ = std.c.write(fd, reset, reset.len); + _ = std.c.tcsetattr(fd, .FLUSH, termios); + }; + // The 9P socket and private prompt files go too: a killed editor + // leaves none behind. Its shells too, the daemon's dups let go. + ninep_io.unlinkOwnSocket(); + host_io.Shell.unlinkOwnedRcs(); + daemon.hangUp(); + // SA_RESETHAND put the default back: the same signal, now fatal. + _ = std.c.raise(sig); + } +}; + +fn localSession( + init: std.process.Init, + opts: pardes.Options, + screen: *Screen, + loop: *Loop, + paste_buf: *std.Io.Writer.Allocating, +) !void { + const io = init.io; + const gpa = init.gpa; + + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + var options = opts; + options.image_allocator = allocs.image; + options.pdf_allocator = allocs.pdf; + options.tree_sitter_allocator = allocs.tree_sitter; + options.frame_allocator = allocs.frame; + + pardes.image.start(io, allocs.image); + if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); + // Pages render on lanes off the loop (pdf_view.workers). + if (comptime pardes.pdf_enabled) pardes.panes.Pdf.workers = io; + pardes.syntax.start(allocs.tree_sitter); + defer { + pardes.image.stop(); + if (comptime pardes.pdf_enabled) pardes.panes.Pdf.dropKept(); + if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + pardes.syntax.stop(); + } + + var core = if (upgrade.resumed) |*rec| + try upgrade.load(gpa, allocs.pardes, options, rec) + else if (options.load_path) |lp| blk: { + const bytes = try filesystem.readFile(gpa, lp); + defer gpa.free(bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); + } else try pardes.Pardes.init(allocs.pardes, options); + defer core.deinit(); + + var prompt_rcs = host_io.Shell.prepare(); + defer prompt_rcs.deinit(); + + var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); + defer frame_arena.deinit(); + + var fs = ninep_io.start(io, gpa, core); + defer if (fs) |f| f.deinit(gpa); + + var sh: Shell = .{ + .io = io, + .gpa = gpa, + .lsp_gpa = allocs.lsp, + .core = core, + .prompt_rcs = &prompt_rcs, + .loop = loop, + .frame = &frame_arena, + .paste_buf = paste_buf, + .inotify_fd = file_watch.init(false), + .fs = fs, + .test_clock = host_io.testClock(), + }; + sh.terms[0] = screen; + sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica }; + defer sh.peers.deinit(); + // Before the core goes: each client sees its link end. + defer sh.peers.dropAll(sh.core); + pardes.lsp.setStatusSink(&sh, lspStatusSink); + host_io.setExitWake(loop, wakeForExit); + defer screen.glide.deinit(gpa); + // The terminals of the other views end with the session: each put back, + // its stub told. + defer for (&sh.terms) |*slot| if (slot.*) |sc| if (!sc.primary) { + stopInput(io, &sc.thread); + sh.dropScreen(sc, .exit); + slot.* = null; + }; + defer { + host_io.setExitWake(null, null); + pardes.lsp.setStatusSink(null, null); + for (&sh.ptys) |*slot| if (slot.*) |*pt| { + pt.reader.cancel(io) catch {}; + _ = libc.close(pt.file.handle); + slot.* = null; + }; + for (sh.adoptions[0..sh.adoptions_len]) |a| _ = libc.close(a.fd); + if (sh.lsp_task) |*t| { + t.future.cancel(io); + sh.lsp_task = null; + } + sh.pipe_tasks.cancelAll(io); + // Its worker may be waiting on the loop's queue for room. + core.stream.cancelTask(); + file_watch.stop(sh.inotify_fd); + if (sh.watch_task) |*t| { + t.cancel(io) catch {}; + sh.watch_task = null; + } + if (sh.inotify_fd >= 0) { + _ = libc.close(sh.inotify_fd); + sh.inotify_fd = -1; + } + while (loop.tryEvent() catch null) |ev| switch (ev) { + .pty_read => |pr| { + tookRead(io, pr.id); + gpa.free(pr.bytes); + }, + .paste => |b| gpa.free(@constCast(b)), + .lsp_done => |d| if (d.rows) |rows| allocs.lsp.free(rows), + .lsp_status => |text| allocs.lsp.free(text), + .pipe_done => |response_value| { + var response = response_value; + response.deinit(gpa); + }, + .search_rows => |b| b.deinit(gpa), + .attach => |a| { + _ = libc.close(a.tty); + if (a.stub >= 0) _ = libc.close(a.stub); + }, + .adopted => |a| _ = libc.close(a.fd), + else => {}, + }; + } + const host = sh.host(); + + core.host = host; + // An upgraded session's terminals, its own again. + if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen); + // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). + sh.setAttended(sh.attached()); + while (core.nextEffect()) |effect| core.perform(effect); + // ...and its shells, once a fresh session's own has a directory to + // adopt them in. + if (upgrade.resumed) |*rec| { + sh.resumePtys(rec); + while (core.nextEffect()) |effect| core.perform(effect); + } + + if (screen.on) try startInput(loop, screen); + defer stopInput(io, &screen.thread); + (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); + (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); + if (fs) |f| try f.watch(loop, wakeFs); + if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); + // Detached from the start, nothing else may wake the first wait. + if (!screen.on) daemon.watch(loop, deliverNote); + // PARDES_TEST_VIEWS: the terminals at these paths are views of the + // session too, from its start, as `pardes --attach`ed ones are (the + // snapshot harness's `start ... views=N`). + if (upgrade.resumed == null) if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { + var it = std.mem.tokenizeScalar(u8, paths, ' '); + while (it.next()) |path| { + var path_buf: [256]u8 = undefined; + const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue; + const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (fd >= 0) sh.attachTerminal(fd, -1, null); + } + }; + + sh.threads_ok = true; + for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = try io.concurrent(readPty, .{ io, gpa, pt.file, id, sh.gens[id], loop }); + }; + if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; + + defer unlinkKittyShm(); + while (!core.quit) { + pardes.turn.bump(&pardes.turn.restores); + try core.pump(host); + // Its unit to each replica client, and theirs taken in. + sh.peers.boundary(core); + upgrade.locate(); + // Asked in the step (the word), done between steps: the session whole. + if (sh.upgrade_asked) |pane| sh.upgradeNow(pane); + // A terminal (`pardes --attach`) or an adopted shell, handed on by + // the daemon's thread to this loop; started after the first frame, + // off a startup's way. + daemon.watch(loop, deliverNote); + if (core.takeRestore()) |rp| blk: { + // ponytail: a Restore replaces the core its clients replicate; + // they are let go, and attach again. + sh.peers.dropAll(core); + const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { + core.reportError(core.active, "Restore", err); + break :blk; + }; + defer gpa.free(bytes); + const nc = dump.restore(core, bytes, rp) catch |err| { + core.reportError(core.active, "Restore", err); + break :blk; + }; + if (sh.lsp_task) |*task| { + task.future.cancel(io); + sh.lsp_task = null; + } + sh.pipe_tasks.cancelAll(io); + for (&sh.gens) |*generation| generation.* +%= 1; + for (&sh.ptys) |*slot| if (slot.*) |*pt| { + pt.reader.cancel(io) catch {}; + _ = libc.close(pt.file.handle); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); + slot.* = null; + }; + for (0..pardes.MAX_PANES) |wid| file_watch.watchPane( + sh.inotify_fd, + &sh.watches, + @intCast(wid), + null, + 0, + .{ .text = 0 }, + ); + _ = file_watch.applyThemeEffect(core, gpa, sh.inotify_fd, &sh.watches, 0, false, false); + // ponytail: a restored session is one view, the live one's + // terminal: the others are let go, as a detach of each. + const live = sh.term().?; + for (&sh.terms) |*slot| if (slot.*) |sc| if (sc != live) { + stopInput(io, &sc.thread); + sh.dropScreen(sc, .detach); + slot.* = null; + }; + sh.terms = @splat(null); + sh.terms[0] = live; + stopInput(io, &live.thread); + live.feed.view = 0; + sh.from = 0; + if (live.on) startInput(loop, live) catch {}; + if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); + nc.native_images = live.on and live.vx.caps.kitty_graphics; + nc.unattended = !live.on; + sh.peers.alone_unattended = !live.on; + if (fs) |f| f.reset(nc); + core.deinit(); + core = nc; + sh.core = nc; + if (comptime pardes.pdf_enabled) if (live.on) { + updateCoreTerminalSize(core, live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix); + }; + } + } + if (fs) |f| { + f.deinit(gpa); + fs = null; + sh.fs = null; + } +} + +fn clearNativeImages( + kitty_handles: *std.AutoHashMap(pardes.ImageCacheKey, vaxis.Image), + vx: *vaxis.Vaxis, + tty: *vaxis.Tty, +) void { + var iterator = kitty_handles.valueIterator(); + while (iterator.next()) |handle| vx.freeImage(tty.writer(), handle.id); + kitty_handles.clearRetainingCapacity(); +} + +const Adoption = struct { pid: posix.pid_t, fd: posix.fd_t, pane: ?u8 }; + +/// The daemon's thread: what it says, onto the loop's queue. +fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { + const loop: *Loop = @ptrCast(@alignCast(ctx)); + switch (note) { + .attach => |a| if (a.tty < 0) { + if (a.stub >= 0) daemon.refuseStub(a.stub, "a terminal session takes a terminal"); + } else loop.postEvent(.{ .attach = .{ .tty = a.tty, .stub = a.stub } }) catch { + _ = libc.close(a.tty); + _ = libc.close(a.stub); + }, + .adopted => |a| { + for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch { + _ = libc.close(fd); + }; + loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {}; + }, + .replica => |j| loop.postEvent(.{ .replica = j }) catch { + _ = libc.close(j.fd); + }, + } +} + +/// A replica reader's post: the session's wait ends, and its step +/// boundary takes the post in. +fn wakeForReplica(ctx: ?*anyopaque) void { + const loop: *Loop = @ptrCast(@alignCast(ctx.?)); + // Never waits: a full queue wakes the loop anyway, and a reader the + // loop is joining (a client let go) must not wait on it. + _ = loop.tryPostEvent(.replica_mail) catch {}; +} + +const Shell = struct { + io: std.Io, + gpa: std.mem.Allocator, + lsp_gpa: std.mem.Allocator, + core: *pardes.Pardes, + prompt_rcs: *const host_io.Shell.PromptFiles, + loop: *Loop, + /// Each view's terminal, by view (views.zig): the session's own first; + /// none in tests. + terms: [pardes.views.max]?*Screen = @splat(null), + /// The view the input taken now is from (`Command.value.from`). + from: u8 = 0, + frame: *std.heap.ArenaAllocator, + paste_buf: *std.Io.Writer.Allocating, + inotify_fd: c_int, + /// Shells a dead session left (Adopt), each waiting for the spawn of + /// the terminal pane made for it. + adoptions: [pardes.MAX_PANES]Adoption = undefined, + adoptions_len: usize = 0, + adopted: usize = 0, + fs: ?*ninep_io.Listener = null, + ptys: [pardes.MAX_PANES]?Pty = @splat(null), + gens: [pardes.MAX_PANES]u32 = @splat(0), + watches: file_watch.Table = @splat(null), + watch_task: ?std.Io.Future(anyerror!void) = null, + lsp_task: ?host_io.Lsp.Task = null, + pipe_tasks: PipeTasks = .{}, + threads_ok: bool = false, + check_files: bool = false, + // ponytail: one bracketed paste at a time for every terminal: keys + // another terminal sends while one pastes join its paste. + in_paste: bool = false, + /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the + /// running-out wait moves it: the core's next wake. + test_clock: ?u64 = null, + /// The tick the last paced frame was due at (waitInput), and whether + /// this wait read an input (its frame is drawn at once). + pace_ns: u64 = 0, + input_seen: bool = false, + wake_to: u64 = 0, + /// waitInput's pacing of output: whether this wait read a pane's output, + /// and when the last frame was written, the last input was read and the + /// focused pane's output last was. + output_seen: bool = false, + drawn_ns: u64 = 0, + input_ns: u64 = 0, + focused_ns: u64 = 0, + /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). + upgrade_asked: ?u8 = null, + /// Its pty readers stopped for it: their end of file is not a shell's. + upgrading: bool = false, + /// The session's replica clients (src/replica.zig), on sockets. + peers: replica.Peers = .{}, + /// This wait took only a replica's post (its input, its join): the + /// pump after it reads no new time, so it moves nothing the replicas' + /// speculations stand on (a replica takes such a unit as is). + mail_only: bool = false, + waited: bool = false, + /// This wait's steps so far, and the input held for the next (`split`). + took_input: bool = false, + took_output: bool = false, + held: ?@TypeOf(Command.value) = null, + /// This process a replica client of a session elsewhere (`remote`): + /// its inputs go to the replica, never straight to the core. + remote: ?*Remote = null, + + const Leaving = enum { detach, exit }; + + /// A terminal's input, to the core, or to a replica client's engine + /// (applied at once there, and sent to the session). + fn feed(s: *Shell, ev: pardes.Event) void { + const c = s.remote orelse return s.core.update(ev); + c.link.input(ev); + } + + /// Whether a terminal of this process's shows the session, or + /// nothing (a test) can. + fn local(s: *const Shell) bool { + for (s.terms) |slot| if (slot != null) return true; + return false; + } + + /// Whether anyone looks at the session: a terminal here, or a replica + /// client (Peers keeps it attended while one is there). + fn setAttended(s: *Shell, on: bool) void { + s.peers.alone_unattended = !on; + s.core.unattended = !on and s.peers.count() == 0; + } + + fn of(ctx: ?*anyopaque) *Shell { + return @ptrCast(@alignCast(ctx.?)); + } + + fn host(s: *Shell) host_io.Host { + return .{ .ctx = s, .vtable = if (comptime pardes.isolated) &isolated_vtable else &vtable }; + } + + const isolated_vtable: host_io.Host.VTable = .{ + .wait_input = waitInput, + .now = clockNow, + .present = present, + .post_present = postPresent, + .poll_frame = stepGlide, + }; + + const vtable: host_io.Host.VTable = .{ + .wait_input = waitInput, + .now = clockNow, + .present = present, + .post_present = postPresent, + .poll_frame = pollFrame, + .watched = watched, + .detach = detach, + .adopt = adopt, + .upgrade = upgradeAsked, + .newer_build = newerBuild, + .spawn = spawn, + .pty_write = ptyWrite, + .pty_resize = ptyResize, + .pty_signal = ptySignal, + .close_pty = closePty, + .tty_taken = ttyTaken, + .fg_name = fgName, + .kill_job = killJob, + .write_file = writeFile, + .write_dump = writeDump, + .watch_file = watchFile, + .watch_theme = watchTheme, + .dump_themes = dumpThemes, + .set_clipboard = setClipboard, + .read_clipboard = readClipboard, + .open_link = openLink, + .lsp = lsp, + .pipe = pipe, + .search = search, + }; + + fn clockNow(ctx: ?*anyopaque) u64 { + const s = of(ctx); + if (s.waited) { + s.waited = false; + if (s.mail_only and s.peers.count() > 0 and s.core.clock_started) return s.core.now_ns; + } + return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + } + + /// The live view's terminal (null in tests). + fn term(s: *const Shell) ?*Screen { + return s.terms[s.core.view]; + } + + fn attached(s: *const Shell) bool { + const screen = s.term() orelse return true; + return screen.on; + } + + /// Drawn only while a terminal shows it: a replica client's view live + /// (its input the last), whichever terminal here shows another. + fn watched(ctx: ?*anyopaque) bool { + const s = of(ctx); + if (s.term() == null and s.local()) { + for (s.terms) |slot| if (slot) |sc| if (sc.on) return true; + return false; + } + return s.attached(); + } + + /// Detach: the terminal put back and let go, the stub told (it ends, + /// and the shell has its terminal again), the session left running. + fn detach(ctx: ?*anyopaque) void { + const s = of(ctx); + // A replica client's: its link ends. + if (s.peers.detach(s.core.view)) return; + if (!s.attached()) return s.core.reportFailure(s.core.active, "Detach: no terminal is attached"); + // One of several: its view goes, and the session stays on the rest. + if (pardes.views.count(s.core) > 1) return s.dropView(s.core.view, .detach); + if (!daemon.kept()) return s.core.reportFailure(s.core.active, "Detach: no pardes daemon keeps this session (it is its terminal's job)"); + s.leaveTerminal(); + } + + /// View `k`'s terminal let go (detached, or gone) while others stay: the + /// view goes with it. + fn dropView(s: *Shell, k: u8, how: Leaving) void { + const sc = s.terms[k] orelse return; + stopInput(s.io, &sc.thread); + s.terms[k] = null; + s.core.closeView(k); + s.dropScreen(sc, how); + } + + /// A terminal put back and its stub told; an attached one's Screen freed + /// (the session's own stays, a view of none). + fn dropScreen(s: *Shell, sc: *Screen, how: Leaving) void { + if (sc.primary) { + sc.leave(); + return sc.sayDetached(); + } + sc.leave(); + switch (how) { + .detach => sc.sayDetached(), + .exit => { + daemon.tellExit(sc.stub, 0); + sc.stub = -1; + }, + } + sc.glide.deinit(s.gpa); + sc.kitty.deinit(); + s.gpa.free(sc.buf); + s.gpa.destroy(sc); + } + + fn leaveTerminal(s: *Shell) void { + const screen = s.term() orelse return; + stopInput(s.io, &screen.thread); + screen.leave(); + s.core.native_images = false; + s.setAttended(false); + // The stub's stdin, stdout and stderr were its terminal too. + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (null_fd >= 0) { + for (0..3) |i| _ = libc.dup2(null_fd, @intCast(i)); + if (null_fd > 2) _ = libc.close(null_fd); + } + screen.sayDetached(); + daemon.setState(true); + } + + /// `pardes --attach`'s terminal: for a detached session its own again, + /// entered as the first one was; for one attached already, a view of + /// its own (views.zig). Sized, asked what it can do, and drawn whole. + fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { + // A replica client's view live (its input the last) has no terminal + // here: the session's own is the one a terminal takes, or joins. + const live = s.term() orelse for (s.terms) |slot| { + if (slot) |sc| if (sc.primary) break sc; + } else { + _ = libc.close(fd); + return refuse(stub, "that session has no terminal of its own to attach to"); + }; + const screen = if (!live.on) live else extra: { + const sc = s.gpa.create(Screen) catch break :extra null; + const buf = s.gpa.alloc(u8, 0x10000) catch { + s.gpa.destroy(sc); + break :extra null; + }; + sc.* = .{ .io = s.io, .gpa = s.gpa, .env = live.env, .buf = buf, .kitty = .init(s.gpa) }; + break :extra sc; + } orelse { + _ = libc.close(fd); + return refuse(stub, "that session has no room for another terminal"); + }; + const extra = screen != live; + const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { + _ = libc.close(fd); + if (extra) s.freeScreen(screen) else daemon.setState(true); + return refuse(stub, "that terminal would not go raw"); + }; + screen.enter(tty) catch { + if (extra) s.freeScreen(screen) else daemon.setState(true); + return refuse(stub, "that terminal would not take the screen"); + }; + if (extra) { + const k = s.core.openView() orelse { + screen.leave(); + s.freeScreen(screen); + return refuse(stub, "that session has as many terminals as it takes"); + }; + screen.feed.view = k; + s.terms[k] = screen; + } + screen.setStub(stub); + s.setAttended(true); + startInput(s.loop, screen) catch {}; + screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; + s.core.needs_frame = true; + daemon.setState(false); + } + + fn freeScreen(s: *Shell, sc: *Screen) void { + sc.kitty.deinit(); + s.gpa.free(sc.buf); + s.gpa.destroy(sc); + } + + /// A terminal refused: its stub told why (a test's has none). + fn refuse(stub: posix.fd_t, why: []const u8) void { + if (stub >= 0) daemon.refuseStub(stub, why); + } + + /// Adopt: the daemon is asked for the shells of sessions that died + /// holding them; each comes back (`adopted`) as a terminal pane here. + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + if (!daemon.kept()) return s.core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); + s.adopted = 0; + daemon.adopt(); + } + + /// 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).remote == null and upgrade.newer(); + } + + fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place"); + s.upgrade_asked = pane; + } + + /// Upgrade, between steps: this process exec'd as the pardes now at the + /// path it was started from, the session in its dump, and its ptys, + /// terminals, stubs and daemon link kept open across (upgrade.zig). + /// Returns only when it could not be, the session going on as it was. + fn upgradeNow(s: *Shell, pane: u8) void { + if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty + s.upgrade_asked = null; + const core = s.core; + var why: [800]u8 = undefined; + const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from"); + // 9P is served while the new binary is asked (its clients' clunks + // and reads after the word are answered), and not after. + pardes.turn.rest(); + const checked = upgrade.check(path, &why); + pardes.turn.wake(); + switch (checked) { + .no => |w| return core.reportFailure(pane, w), + .ok => {}, + } + // Nothing more read from a pty or a terminal, and what was read + // goes in; a reader's cancel posts an end of file, passed over. + s.upgrading = true; + defer s.upgrading = false; + for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; + for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread); + while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); + core.settle(); + // Its replica clients told, their views gone before the dump: each + // dials the session again once it is back. + s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); + var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; + for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); + for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{ + .view = @intCast(k), + .fd = sc.tty.fd.handle, + .stub = if (sc.primary) daemon.stub else sc.stub, + .primary = sc.primary, + .termios = sc.tty.termios, + }); + var popped = false; + var at_buf: [1024:0]u8 = undefined; + const failed: []const u8 = failed: { + const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is"; + const bytes = pardes.dump.dumpBytes(core) catch |err| { + var words: [128]u8 = undefined; + break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump"; + }; + defer s.gpa.free(bytes); + if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written"; + rec.dump = at; + rec.old = upgrade.openSelf(); + // What this process put in its terminals that the next puts in + // again: its images, and its keyboard mode, a stack. + for (s.terms) |slot| if (slot) |sc| if (sc.on) { + clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); + if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[= 0) _ = libc.close(rec.old); + break :failed std.fmt.bufPrint(&why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start"; + }; + // As it was: its ptys read on, its terminals' keys as they were. + for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; + }; + for (s.terms) |slot| if (slot) |sc| if (sc.on) { + if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; + startInput(s.loop, sc) catch {}; + }; + core.reportFailure(pane, failed); + } + + /// An upgraded session's shells, running on: each its pane's pty again, + /// or, when its dump would not load (`fresh`), adopted as new panes. + fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { + for (rec.ptys[0..rec.nptys]) |k| { + const pane = if (rec.fresh) null else s.core.panes[k.pane]; + if (pane == null or !pane.?.isTerminal()) { + s.adoptShell(k.pid, k.fd); + continue; + } + const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } }; + s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; + } + } + + /// An upgraded session's terminals, each its view's again (`primary`, + /// run's, entered already); in a fresh session each but the primary a + /// view of its own, as `--attach` makes one. A view left with none + /// closes, but a replica client's, kept for its rejoin (views.away). + fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void { + if (comptime builtin.is_test) unreachable; + const core = s.core; + if (rec.fresh) { + for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios); + return; + } + s.terms = @splat(null); + if (rec.nttys == 0) { + // The live view alone (never one kept for a rejoin) is the + // session's own. + for (0..pardes.views.max) |k| if (k != core.view and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); + s.terms[core.view] = primary; + primary.feed.view = core.view; + return; + } + for (rec.ttys[0..rec.nttys]) |t| { + if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) { + if (t.primary) continue; + _ = libc.close(t.fd); + if (t.stub >= 0) daemon.tellDetached(t.stub); + continue; + } + const sc = if (t.primary) primary else extra: { + const sc = s.gpa.create(Screen) catch break :extra null; + const buf = s.gpa.alloc(u8, 0x10000) catch { + s.gpa.destroy(sc); + break :extra null; + }; + sc.* = .{ .io = s.io, .gpa = s.gpa, .env = primary.env, .buf = buf, .kitty = .init(s.gpa) }; + const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch { + s.freeScreen(sc); + break :extra null; + }; + sc.enter(tty) catch { + s.freeScreen(sc); + break :extra null; + }; + sc.setStub(t.stub); + startInput(s.loop, sc) catch {}; + sc.vx.queryTerminalSend(sc.tty.writer()) catch {}; + break :extra sc; + } orelse { + _ = libc.close(t.fd); + if (t.stub >= 0) daemon.tellDetached(t.stub); + continue; + }; + sc.feed.view = t.view; + s.terms[t.view] = sc; + } + for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); + if (s.terms[core.view] == null) s.terms[core.view] = primary; + } + + /// One shell of a dead session (`pid` 0: the last of them was told). + fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void { + const core = s.core; + if (pid == 0) { + var buf: [96]u8 = undefined; + return core.setMessage(core.active, if (s.adopted == 0) "Adopt: no shell of a session that died is waiting" else std.fmt.bufPrint(&buf, "Adopt: {d} shell{s} taken in; what they showed is gone", .{ s.adopted, if (s.adopted == 1) "" else "s" }) catch "Adopt: shells taken in"); + } + if (s.adoptions_len < s.adoptions.len) { + // A terminal pane, as the Term word makes one; its spawn takes + // this pty instead of forking a shell (`spawn`). + s.adoptions[s.adoptions_len] = .{ .pid = pid, .fd = fd, .pane = null }; + s.adoptions_len += 1; + if (core.adoptShell()) |id| { + s.adoptions[s.adoptions_len - 1].pane = id; + s.adopted += 1; + return; + } + s.adoptions_len -= 1; + } + // No room for it: its master goes, and the shell with this session. + _ = libc.close(fd); + var buf: [96]u8 = undefined; + core.setMessage(core.active, std.fmt.bufPrint(&buf, "Adopt: no room for shell {d}; it ends with this session", .{pid}) catch "Adopt: no room for a shell"); + } + + fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { + const s = of(ctx); + // The wait is the 9P connections' turn with the core. A timeout (the + // core's next wake) arrives through the same queue (`wakeWatch`). + // While anything moves, a frame a tick (animation.frame_ns) on a grid + // of them, as the GUI paces to its display: the loop ran as fast as + // the terminal answered, a frame every 2 ms, each a write. An input + // ends the wait at once and its frame is drawn then; the ticks after + // it run from it. + var wait = timeout_ms; + // Detached, nobody's key dismisses a message: they go on the clock + // (the pump's, after this wait), which wakes it. + if (!s.attached()) { + for (s.core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + wait = if (wait == 0) 100 else @min(wait, 100); + break; + }; + } + const paced = s.test_clock == null and s.core.continuous(); + var tick: u64 = 0; + if (paced) { + const period = pardes.animation.frame_ns; + const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now; + if (tick < now) tick += (now - tick) / period * period; + s.pace_ns = tick; + wait = @intCast(@max(1, (tick -| now) / std.time.ns_per_ms)); + } + s.input_seen = false; + s.output_seen = false; + s.took_input = false; + s.took_output = false; + s.mail_only = true; + defer s.waited = true; + // Paced, what is not an input (a frame's ack, a pty's output) is + // taken in and the wait goes on to the tick: the acks alone ran the + // loop at the terminal's round trip. + while (true) { + s.waitOnce(wait); + if (!paced or s.input_seen or s.core.quit) break; + const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + if (now + std.time.ns_per_ms > tick) break; + wait = @intCast((tick - now) / std.time.ns_per_ms); + } + if (paced and s.input_seen) s.pace_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + // Output alone is drawn a frame a tick at most, what came in till + // then in one: a flood (`yes`, 4 KB a read) was drawn a read at a + // time, nearly all of its frames written over before they were + // seen. Never while what someone waits on is undrawn: an input + // (its frame held for the terminal's answer, FrameAck), or the + // focused pane's output soon after one, its echo (a remote shell's + // an RTT later). + while (!paced and s.output_seen and !s.input_seen and !s.core.quit and s.test_clock == null) { + if (s.input_ns > s.drawn_ns) break; + if (s.focused_ns > s.drawn_ns and s.focused_ns -| s.input_ns < std.time.ns_per_s) break; + const due = s.drawn_ns + pardes.animation.frame_ns; + const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + if (now + std.time.ns_per_ms > due) break; + s.waitOnce(@intCast((due - now) / std.time.ns_per_ms)); + } + } + + fn waitOnce(s: *Shell, wait: u32) void { + var batch: usize = 0; + const first = if (s.held) |held| held: { + s.held = null; + break :held held; + } else next: { + if (wait != 0) { + // A virtual clock moves a frame a wake while anything moves + // continuously (the glide), as the real one would. + s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0; + requestWake(s.io, wait); + } + pardes.turn.rest(); + const got = s.loop.nextEvent() catch { + pardes.turn.wake(); + s.core.quit = true; + return s.reloadWatched(); + }; + pardes.turn.wake(); + break :next got; + }; + batch = 1; + // A run of queued motions is one move to its last cell: each would + // otherwise redo hover and selection work the next one undoes. + var motion: ?@TypeOf(Command.value) = null; + var ev = first; + while (true) { + if (s.split(ev)) break; + if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) { + if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or + @as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods))) + { + _ = s.apply(m); + }; + motion = ev; + } else { + if (motion) |m| _ = s.apply(m); + motion = null; + if (s.apply(ev)) break; + } + if (!s.in_paste and batch >= 64) break; + ev = (s.loop.tryEvent() catch null) orelse break; + batch += 1; + } + if (motion) |m| _ = s.apply(m); + // An exit's wake (a .nop) or output an exit waited behind: told + // here, inside the step, so the frame after it shows it. + s.takeExits(); + s.reloadWatched(); + } + + /// With replica clients, a wait (one pump, one unit) takes one step of + /// a person's input, and none after a pty's output: a step reads the + /// terminals as the clients' deltas bring them, sent after each unit + /// (docs/next-daemon.md, part B terminal notes). One that must wait is + /// held for the next. Whether `ev` is. + fn split(s: *Shell, ev: @TypeOf(Command.value)) bool { + if (!s.peers.recording) return false; + switch (ev) { + .pty_read => { + s.took_output = true; + return false; + }, + .key_press => if (s.in_paste) return false, + .mouse, .paste, .paste_end, .winsize, .focus_in, .focus_out => {}, + else => return false, + } + if (s.took_output or s.took_input) { + s.held = ev; + s.input_seen = true; + return true; + } + s.took_input = true; + return false; + } + + fn apply(s: *Shell, event: @TypeOf(Command.value)) bool { + const core = s.core; + const tz_event = tracy.zone(@src(), "event"); + defer tz_event.end(); + // A key's or a click's time, for its latency to the frame that + // answers it (FrameStats): when the loop takes it in. + switch (event) { + .key_press => { + core.frames.input(pardes.FrameStats.nowNs()); + s.input_seen = true; + }, + .mouse => |m| if (m.type == .press) { + core.frames.input(pardes.FrameStats.nowNs()); + s.input_seen = true; + }, + .paste, .paste_start, .winsize => s.input_seen = true, + else => {}, + } + if (s.input_seen) s.input_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + if (event != .replica_mail) s.mail_only = false; + // A terminal's input goes into its view; a closed one's last is + // dropped. + switch (event) { + .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { + if (s.terms[s.from] == null and s.local()) { + if (event == .paste) s.gpa.free(@constCast(event.paste)); + return false; + } + if (s.local() and s.remote == null) core.toView(s.from); + }, + else => {}, + } + switch (event) { + .nop => {}, + .from => |k| s.from = k, + .winched => s.winched(), + // A terminal hung up (its stub passes the hangup on) or its stub + // died (a forked session's death signal): that one's input has + // ended. A HUP says not whose: each is asked. + .hangup => for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on and sc.hungUp()) { + s.from = @intCast(k); + if (s.apply(.quit)) return true; + }, + .wake => if (s.test_clock) |*virtual| { + virtual.* = @max(virtual.*, s.wake_to); + }, + .quit => { + if (s.remote) |c| { + c.link.quit = true; + return true; + } + // One of several: its view goes with it. + if (pardes.views.count(core) > 1) { + s.dropView(core.view, .detach); + return true; + } + // The terminal went: a session the daemon keeps carries on + // without it, to be attached again. Gone before the first + // frame, the reader that takes the daemon's `ok` (kept + // waits on it) is not started yet: started here. + daemon.watch(s.loop, deliverNote); + if (daemon.kept()) { + if (s.attached()) s.leaveTerminal(); + return true; + } + core.quit = true; + return true; + }, + .attach => |a| s.attachTerminal(a.tty, a.stub, null), + .adopted => |a| s.adoptShell(a.pid, a.fd), + .replica => |j| { + s.peers.handed(j.fd, j.view); + s.input_seen = true; + }, + .replica_mail => s.input_seen = true, + .said => |said| if (s.remote) |c| { + c.link.take(said); + if (said == .refused) return true; + } else switch (said) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, + }, + .link_gone => if (s.remote) |c| { + c.link.quit = true; + c.link.gone = true; + return true; + }, + .focus_in => s.feed(.{ .focus = true }), + .focus_out => { + s.feed(.pointer_leave); + s.feed(.{ .focus = false }); + }, + .winsize => |ws| if (s.attached()) s.resized(s.terms[s.from], ws), + .pty_read => |pr| { + tookRead(s.io, pr.id); + s.output_seen = true; + if (pr.id == core.active) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + if (s.gens[pr.id] == pr.gen) + core.update(.{ .output = .{ .pane = @intCast(pr.id), .bytes = pr.bytes } }); + s.gpa.free(pr.bytes); + // An exit waiting behind this output may be told now. + s.takeExits(); + return true; + }, + .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) { + if (s.ptys[e.id]) |*pt| { + pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks + // A command's pty stays open until its child has exited: + // closing it would hang up one that runs on without it. + // Its exit, if it came first, is told now its output is in. + if (pt.cmd.watched) { + host_io.commandEof(core, &s.ptys, e.id, s, closeWatched); + return true; + } + _ = libc.close(pt.file.handle); + // Unwatched, a command's exit is read here, as its end, + // and a shell's, for a run waiting on it and the log. + const command = if (core.panes[e.id]) |pn| pn.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status == null) host_io.retireShell(pt.pid); + s.ptys[e.id] = null; + if (command or status != null) core.update(.{ .exited = .{ .pane = @intCast(e.id), .status = status } }); + } + core.update(.{ .eof = .{ .pane = @intCast(e.id) } }); + }, + .key_press => |key| if (s.in_paste) { + const bytes = pasteBytes(key); + const room = max_paste_bytes -| s.paste_buf.written().len; + s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {}; + } else s.feed(vaxis_input.keyEvent(key)), + .mouse => |m| { + const pdf_before = nativePdfWheelTarget(core, m); + if (mouseEvent(m)) |ev| s.feed(ev); + if (pdf_before) |before| { + if (core.panes[before.pane]) |pane| { + if (pane.pdfPage()) |page| { + if (page != before.page) return true; + } + } + } + }, + .paste => |bytes| { + s.feed(.{ .paste = bytes }); + s.gpa.free(@constCast(bytes)); + }, + .paste_start => { + s.in_paste = true; + s.paste_buf.clearRetainingCapacity(); + }, + .paste_end => { + s.in_paste = false; + const pasted = s.paste_buf.written(); + if (pasted.len > 0) s.feed(.{ .paste = pasted }); + s.paste_buf.clearRetainingCapacity(); + }, + .files_changed => s.check_files = true, + .fs_ready => {}, + .lsp_done => |d| { + core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); + if (d.rows) |rows| s.lsp_gpa.free(rows); + if (s.lsp_task) |*t| if (t.id == d.id) { + t.future.await(s.io); + s.lsp_task = null; + }; + }, + .lsp_status => |text| { + var mbuf: [256]u8 = undefined; + core.setStatus(core.active, message.stamp(&mbuf, "lsp", text)); + s.lsp_gpa.free(text); + }, + .pipe_done => |response_value| { + var response = response_value; + core.update(.{ .pipe_resp = .{ + .id = response.id, + .success = response.success, + .outputs = response.outputs, + .failure = response.failure, + } }); + response.deinit(s.gpa); + s.pipe_tasks.finish(s.io, response_value.id); + }, + .search_rows => |b| { + core.update(.{ .search = b }); + b.deinit(s.gpa); + }, + } + return false; + } + + /// Terminal `screen` (the live view's) is `ws` big. + fn resized(s: *Shell, screen: ?*Screen, ws: vaxis.Winsize) void { + if (screen) |sc| { + sc.size = ws; + sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {}; + } + s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } }); + } + + /// A SIGWINCH: each terminal whose size it changed is resized, in its + /// view (a terminal reporting in band says so as input). + fn winched(s: *Shell) void { + for (s.terms, 0..) |slot, k| { + const sc = slot orelse continue; + if (!sc.on or sc.vx.state.in_band_resize) continue; + const ws = sc.tty.getWinsize() catch continue; + if (sc.size) |was| if (std.meta.eql(was, ws)) continue; + if (s.remote == null) s.core.toView(@intCast(k)); + s.resized(sc, ws); + } + } + + fn reloadWatched(s: *Shell) void { + if (!s.check_files) return; + s.check_files = false; + if (file_watch.reloadChanged(s.core, s.io, s.gpa, &s.watches)) + s.loop.postEvent(.files_changed) catch {}; + } + + /// ponytail: a terminal's scrollback under the wheel lands here (the + /// wheel reaches the core as a mouse event, not counted as the GUI's + /// notches are); `wheeled` from the mouse event if it should glide. + fn stepGlide(ctx: ?*anyopaque) void { + const s = of(ctx); + if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null); + } + + fn pollFrame(ctx: ?*anyopaque) void { + const s = of(ctx); + stepGlide(ctx); + if (s.fs) |f| if (f.tick().pending) { + _ = s.loop.tryPostEvent(.fs_ready) catch {}; + }; + for (&s.ptys, 0..) |*slot, id| if (slot.*) |pt| { + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.ttyCwd(pt.pid, pt.file.handle, s.core.settings.shell.effective.get(), &lbuf)) |cwd| s.core.setCwd(id, cwd); + }; + + const sc = s.term() orelse return; + s.core.native_image_patches = sc.feed.shm.load(.acquire); + if (sc.caps_pending and sc.on and sc.vx.queries_done.load(.unordered)) { + sc.caps_pending = false; + sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; + s.core.native_images = sc.vx.caps.kitty_graphics; + if (sc.vx.caps.kitty_graphics) kittyShmProbe(sc.tty.writer(), &sc.feed); + sc.vx.queueRefresh(); + s.core.needs_frame = true; + } + } + + fn present(ctx: ?*anyopaque, canonical: *const pardes.Surface) void { + const s = of(ctx); + const sc = s.term() orelse return; + const vx = &sc.vx; + sc.tracks = canonical.panelTracks(); + // The last frame is not answered yet: this one stays owed, and the + // answer's wake draws the state as it is then. + if (sc.feed.ack.holds(@intCast(std.Io.Clock.awake.now(s.io).nanoseconds), s.io)) { + s.core.present_skipped = true; + return; + } + _ = s.frame.reset(.retain_capacity); + const surface = panel_compositor.compose( + s.frame.allocator(), + @constCast(canonical), + sc.tracks, + s.core.theme().bg, + ) catch return; + const tz_cells = tracy.zone(@src(), "surface->vaxis"); + const win = vx.window(); + const truecolor = vx.caps.rgb or colortermTruecolor(); + // Each of the shell's own motions below asks for frames while it runs. + if (sc.glide.pending) sc.glide.measure(s.gpa, canonical); + if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion); + s.core.shell_continuous = sc.glide.moving(); + s.core.frames.scroll = @round(sc.glide.follow.offset); + const glided = pardes.glide.shifted(&sc.glide, s.frame.allocator(), surface) catch surface; + const shadowed = chipShadows(s.frame.allocator(), glided, s.core, truecolor) catch glided; + const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; + const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; + paintCells(win, trailed.cells, trailed.cols, trailed.rows); + if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), trailed.cols, trailed.rows); + tz_cells.end(); + for (surface.images[0..surface.nimages]) |maybe| { + const place = maybe orelse continue; + if (panel_compositor.hidesAttachment(surface.panelTracks(), place.serial)) continue; + if (comptime pardes.pdf_enabled) { + if (!kittyImageRepresentable(place)) continue; + } + const key = place.cacheKey(); + if (!sc.kitty.contains(key) and vx.caps.kitty_graphics and sc.feed.shm.load(.acquire)) shm: { + var buf: [64]u8 = undefined; + kitty_shm_serial +%= 1; + // Bounded: a segment this many transmissions old was never + // read (a terminal reads one as its command arrives), and a + // tmpfs holds it in memory until it goes. + if (kitty_shm_serial > kitty_shm_window) { + var old_buf: [64]u8 = undefined; + if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {} + } + const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; + if (!kittyShmWrite(name, place.rgba)) break :shm; + if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id) + else + _ = libc.shm_unlink(name); + } + if (!sc.kitty.contains(key) and vx.caps.kitty_graphics) { + const enc = std.base64.standard.Encoder; + if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { + defer s.gpa.free(b64); + _ = enc.encode(b64, place.rgba); + if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.iw), @intCast(place.ih), .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); + } else |_| {} + } + if (sc.kitty.get(key)) |cached| { + if (comptime !pardes.pdf_enabled) { + const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); + cached.draw(child, .{ .scale = .contain }) catch {}; + } else { + if (place.native.exact) { + if (exactKittyPlacement(place, vx.screen.width, vx.screen.height, vx.screen.width_pix, vx.screen.height_pix)) |placement| { + // The cell keeps its own glyph and colours + // (Image.draw would reset them): a fragment + // short of the cell shows the pane under it. + const x = place.x + placement.cell_x; + if (win.readCell(x, place.y)) |under| { + var cell = under; + cell.image = .{ .img_id = cached.id, .options = placement.options }; + win.writeCell(x, place.y, cell); + } + } + } else if (place.native.fit == .contain) { + const child = win.child(.{ .x_off = place.x, .y_off = place.y, .width = place.w, .height = place.h }); + cached.draw(child, .{ .scale = .contain }) catch {}; + } else if (kittyPlacement( + place, + vx.screen.width, + vx.screen.height, + vx.screen.width_pix, + vx.screen.height_pix, + )) |placement| { + const child = win.child(.{ + .x_off = @as(i17, place.x) + placement.cell_x, + .y_off = @as(i17, place.y) + placement.cell_y, + .width = placement.cell_cols, + .height = placement.cell_rows, + }); + cached.draw(child, placement.options) catch {}; + } + } + } + } + while (true) { + var stale: [pardes.MAX_PANES]pardes.ImageCacheKey = undefined; + var stale_len: usize = 0; + var image_iterator = sc.kitty.iterator(); + while (image_iterator.next()) |entry| { + if (surfaceHasKittyKey(surface, entry.key_ptr.*)) continue; + stale[stale_len] = entry.key_ptr.*; + stale_len += 1; + if (stale_len == stale.len) break; + } + for (stale[0..stale_len]) |key| if (sc.kitty.fetchRemove(key)) |removed| + vx.freeImage(sc.tty.writer(), removed.value.id); + if (stale_len < stale.len) break; + } + if (glided.cursor) |cur| paintCursor(win, cur.x, cur.y, cur.bar); + const tz_render = tracy.zone(@src(), "vx.render"); + const before = sc.tty.tty_writer.pos + sc.tty.writer().end; + vx.render(sc.tty.writer()) catch {}; + // The frame's cost to the terminal (FrameStats.Frame.bytes): what + // vaxis's diff of the cells wrote. + s.core.frames.bytes +|= @intCast(@min(std.math.maxInt(u32), sc.tty.tty_writer.pos + sc.tty.writer().end -| before)); + if (sc.tty.tty_writer.pos + sc.tty.writer().end != before) sc.feed.ack.ask(sc.tty.writer(), @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)); + s.drawn_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + tz_render.end(); + } + + fn postPresent(ctx: ?*anyopaque) void { + const s = of(ctx); + if (s.term()) |sc| s.core.acknowledgePanelPresentation(sc.tracks); + tracy.frameMark(); + } + + fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + const s = of(ctx); + for (s.adoptions[0..s.adoptions_len], 0..) |a, i| if (a.pane == pane) { + std.mem.copyForwards(Adoption, s.adoptions[i .. s.adoptions_len - 1], s.adoptions[i + 1 .. s.adoptions_len]); + s.adoptions_len -= 1; + return s.takeShell(pane, a); + }; + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = s.ptys[pane] != null; + const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.screen_h, s.core.screen_w, s.fs) catch |err| { + if (running) return s.core.restartFailed(pane, err); + return s.core.shellFailed(pane, err); + }; + closePty(ctx, pane); // a shell still in the slot goes, reaped + s.gens[pane] +%= 1; + const command = if (s.core.panes[pane]) |pn| pn.command != null else false; + s.ptys[pane] = .{ .file = child.file, .pid = child.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and asked now, before + // its chdir, it would answer this process's, a rename to undo. + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + if (s.threads_ok) { + if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + } + } + } + + /// An adopted shell, running already, as pane `pane`'s: told the size + /// twice (a size it never had, then the pane's), which makes it redraw. + fn takeShell(s: *Shell, pane: u8, a: Adoption) void { + closePty(s, pane); + s.gens[pane] +%= 1; + const file: std.Io.File = .{ .handle = a.fd, .flags = .{ .nonblocking = false } }; + s.ptys[pane] = .{ .file = file, .pid = a.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{} }; + var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); + if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); + if (s.threads_ok) if (s.ptys[pane]) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, @as(usize, pane), s.gens[pane], s.loop }) catch pt.reader; + }; + } + + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const s = of(ctx); + if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); + } + + fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + const s = of(ctx); + if (s.ptys[pane]) |pt| { + const ws = host_io.ptyWinsize(s.core, cols, rows); + _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); + } + } + + fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + const s = of(ctx); + // A command whose exit is recorded is reaped: its group may be + // another's by now. + if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); + } + + /// The pane is gone: hang its pty up, which the kernel passes on to the + /// shell as SIGHUP, and retire the shell. Output still in flight + /// carries the old generation and is dropped. + fn closePty(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + var pt = s.ptys[pane] orelse return; + s.ptys[pane] = null; + s.gens[pane] +%= 1; + pt.reader.cancel(s.io) catch {}; + _ = libc.close(pt.file.handle); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); + } + + fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.ttyTaken(pt.pid, pt.file.handle); + } + + fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { + const s = of(ctx); + const pt = s.ptys[pane] orelse return null; + return host_io.foregroundName(pt.pid, pt.file.handle, buf); + } + + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *@This()) void { + host_io.takeExits(s.core, &s.ptys, s, closeWatched); + } + + fn closeWatched(s: *@This(), id: usize) void { + const pt = &(s.ptys[id] orelse return); + _ = libc.close(pt.file.handle); + s.ptys[id] = null; + } + + fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const s = of(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.killJob(pt.pid, pt.file.handle); + } + + fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { + const s = of(ctx); + host_io.writeFile(s.core, &s.watches, pane, path, bytes); + } + + fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { + host_io.writeDump(of(ctx).core, bytes); + } + + fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { + const s = of(ctx); + if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, &s.watches, pane, on, mode)) + s.loop.postEvent(.files_changed) catch {}; + } + + fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { + const s = of(ctx); + if (file_watch.applyThemeEffect(s.core, s.gpa, s.inotify_fd, &s.watches, generation, on, s.threads_ok)) + s.loop.postEvent(.files_changed) catch {}; + } + + fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + host_io.dumpThemes(s.core, s.io, s.gpa, pane); + } + + fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { + const s = of(ctx); + // Detached, the session keeps it (a 9P read, a paste here). + const sc = s.term() orelse return s.core.fallback.setClipboard(text); + if (!sc.on) return s.core.fallback.setClipboard(text); + copyToClipboard(&sc.vx, &sc.tty, s.gpa, text); + } + + fn readClipboard(ctx: ?*anyopaque) void { + const s = of(ctx); + const sc = s.term() orelse return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + if (!sc.on) return s.core.update(.{ .paste = s.core.fallback.clipboard.items }); + requestClipboard(&sc.vx, &sc.tty); + } + + fn openLink(_: ?*anyopaque, url: []const u8) void { + look.openLink(url); // desktop browser; no terminal in it, so Attach calls this one directly + } + + fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { + const s = of(ctx); + if (!s.threads_ok) { + s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); + } + host_io.Lsp.start(s.io, s.lsp_gpa, s.core, &s.lsp_task, req, s, deliverLspRows); + } + + fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const s = of(ctx); + s.loop.postEvent(.{ .lsp_done = .{ .id = id, .rows = rows } }) catch if (rows) |owned| s.lsp_gpa.free(owned); + } + + fn pipe(ctx: ?*anyopaque, id: u32) void { + const s = of(ctx); + if (!s.threads_ok) { + s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); + return s.core.reportError(s.core.active, "pipe", error.WorkersUnavailable); + } + selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); + } + + 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); + } + + /// The loop's queue waits for room (a wait the worker's cancel ends). + fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { + const s = of(ctx); + s.loop.postEvent(.{ .search_rows = batch }) catch { + batch.deinit(s.gpa); + return false; + }; + return true; + } + + fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { + const s = of(ctx); + var owned = response; + s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); + } +}; + +test "TTY queued results reject old PTY generations and LSP request IDs" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer core.deinit(); + var shell: Shell = .{ + .io = std.testing.io, + .gpa = gpa, + .lsp_gpa = gpa, + .core = core, + .prompt_rcs = undefined, + .loop = undefined, + .frame = undefined, + .paste_buf = undefined, + .inotify_fd = -1, + }; + shell.gens[0] = 2; + _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); + _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); + const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); + try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); + + core.lspRequest(0, .status, ""); + const old_id = core.lsp_wait.?.id; + core.lspRequest(0, .status, ""); + const current_id = core.lsp_wait.?.id; + shell.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; + _ = shell.apply(.{ .lsp_done = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); + try std.testing.expect(shell.lsp_task != null); + try std.testing.expectEqual(current_id, shell.lsp_task.?.id); + try std.testing.expectEqual(current_id, core.lsp_wait.?.id); + _ = shell.apply(.{ .lsp_done = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); + try std.testing.expect(shell.lsp_task == null); + try std.testing.expect(core.lsp_wait == null); +} + +test "TTY worker setup failures finish matching LSP and pipe requests" { + const gpa = std.testing.allocator; + var failing_vtable = std.testing.io.vtable.*; + failing_vtable.concurrent = std.Io.failingConcurrent; + const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; + for (0..2) |failure| { + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("abc"); + var failing = std.testing.FailingAllocator.init(gpa, .{ + .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), + }); + var shell: Shell = .{ + .io = failing_io, + .gpa = failing.allocator(), + .lsp_gpa = failing.allocator(), + .core = core, + .prompt_rcs = undefined, + .loop = undefined, + .frame = undefined, + .paste_buf = undefined, + .inotify_fd = -1, + .threads_ok = true, + }; + core.lspRequest(core.active, .status, ""); + const req: host_io.Lsp.Request = .{ + .id = core.lsp_wait.?.id, + .kind = .status, + .pane = @intCast(core.active), + .offset = 0, + .arg = "", + }; + Shell.lsp(&shell, req); + try std.testing.expect(core.lsp_wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + core.update(.{ .key = .{ .cp = '|' } }); + core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + core.update(.{ .key = .{ .cp = pardes.Key.enter } }); + const pipe_id = core.pipe.wait.?.id; + Shell.pipe(&shell, pipe_id); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(shell.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); + } +} + +fn copyToClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty, gpa: std.mem.Allocator, text: []const u8) void { + if (text.len == 0) return; + vx.copyToSystemClipboard(tty.writer(), text, gpa) catch {}; +} + +fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { + vx.requestSystemClipboard(tty.writer()) catch {}; +} + +fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { + const s: *Shell = @ptrCast(@alignCast(ctx orelse return)); + const copy = s.lsp_gpa.dupe(u8, text) catch return; + const posted = s.loop.tryPostEvent(.{ .lsp_status = copy }) catch false; + if (!posted) s.lsp_gpa.free(copy); +} + +fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { + if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) { + while (file_watch.wait(fd)) loop.postEvent(.files_changed) catch break; + return; + } + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [4096]u8 = undefined; + while (true) { + const n = file.readStreaming(io, &.{&buf}) catch break; + if (n == 0) break; + loop.postEvent(.files_changed) catch break; + } +} + +fn keepSignal(_: posix.SIG) callconv(.c) void {} + +/// A replica client's (`remote`): a hangup is its end, whoever sent it. +var hangup_quits = false; + +fn winchWatch(loop: *Loop) void { + var set = posix.sigemptyset(); + posix.sigaddset(&set, posix.SIG.WINCH); + if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP); + while (true) { + var sig: c_int = 0; + if (libc.sigwait(&set, &sig) != 0) continue; + // The terminals are the loop's: it asks each its size, and takes a + // hangup as the end of the one that hung up. + const ev: @TypeOf(Command.value) = if (sig != @backingInt(posix.SIG.HUP)) .winched else if (hangup_quits) .quit else .hangup; + loop.postEvent(ev) catch {}; + } +} + +/// A wait with a timeout: post one `.wake` when it runs out. The wake joins +/// the input queue, so a key or a click that lands first is handled at once +/// instead of after a blind sleep; vaxis's queue has no timed wait. Each +/// request bumps `wake_gen`, which cuts short a sleep still timing an +/// earlier, longer request (an 800 ms linger interrupted by a key that +/// starts a 16 ms fall) and times the new one instead. +var wake_gen: std.atomic.Value(u32) = .init(0); +var wake_ms: std.atomic.Value(u32) = .init(0); + +fn requestWake(io: std.Io, ms: u32) void { + wake_ms.store(ms, .release); + _ = wake_gen.fetchAdd(1, .acq_rel); + io.futexWake(u32, &wake_gen.raw, 1); +} + +fn wakeWatch(io: std.Io, loop: *Loop) void { + var seen = wake_gen.load(.acquire); + while (true) { + // Asleep until a request. + while (wake_gen.load(.acquire) == seen) io.futexWaitUncancelable(u32, &wake_gen.raw, seen); + seen = wake_gen.load(.acquire); + if (timeWake(io, &seen)) loop.postEvent(.wake) catch {}; + } +} + +/// Sleep out the latest request; true when it ran its course, false when +/// none is pending. A newer request met on the way restarts the timing. +fn timeWake(io: std.Io, seen: *u32) bool { + while (true) { + const ms = wake_ms.load(.acquire); + const deadline = @as(u64, @intCast(std.Io.Clock.awake.now(io).nanoseconds)) + @as(u64, ms) * std.time.ns_per_ms; + while (true) { + const now: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); + if (now >= deadline) return true; + io.futexWaitTimeout(u32, &wake_gen.raw, seen.*, .{ .duration = .{ + .raw = .fromNanoseconds(@intCast(deadline - now)), + .clock = .awake, + } }) catch {}; + const gen = wake_gen.load(.acquire); + if (gen != seen.*) { + seen.* = gen; + break; + } + } + } +} + +test "a short wake request cuts short a long one still sleeping" { + const io = std.testing.io; + var seen = wake_gen.load(.acquire); + requestWake(io, 800); + seen = wake_gen.load(.acquire); + const Timer = struct { + fn run(timer_io: std.Io, start_seen: u32, done: *std.atomic.Value(u64)) void { + var local = start_seen; + _ = timeWake(timer_io, &local); + done.store(@intCast(std.Io.Clock.awake.now(timer_io).nanoseconds), .release); + } + }; + var done: std.atomic.Value(u64) = .init(0); + const start: u64 = @intCast(std.Io.Clock.awake.now(io).nanoseconds); + const thread = try std.Thread.spawn(.{}, Timer.run, .{ io, seen, &done }); + try io.sleep(.fromMilliseconds(50), .awake); + requestWake(io, 16); + thread.join(); + // The 16 ms request lands about 66 ms in: well before the 800 ms one + // would have, however loaded the machine. + try std.testing.expect(done.load(.acquire) - start < 700 * std.time.ns_per_ms); +} + +fn wakeFs(ctx: ?*anyopaque) void { + const loop: *Loop = @ptrCast(@alignCast(ctx.?)); + _ = loop.tryPostEvent(.fs_ready) catch {}; +} + +/// Each pane's reads posted and not yet taken in. Two at most: a flood the +/// loop cannot keep up with waits in its pty, not in the queue ahead of a +/// key and its echo (hundreds of 4 KB reads queued were half a second). +var reads_queued: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)); + +/// A read of pane `id` taken in (or dropped): its reader may read on. Never +/// below zero, for an event no reader posted (a test's). +fn tookRead(io: std.Io, id: usize) void { + var queued = reads_queued[id].load(.acquire); + while (queued > 0) queued = reads_queued[id].cmpxchgWeak(queued, queued - 1, .acq_rel, .acquire) orelse { + if (queued == 2) io.futexWake(u32, &reads_queued[id].raw, 1); + return; + }; +} + +fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; + read: while (true) { + while (true) { + const queued = reads_queued[id].load(.acquire); + if (queued < 2) break; + io.futexWait(u32, &reads_queued[id].raw, queued) catch break :read; + } + const n = pty.readStreaming(io, &.{&buf}) catch break; + if (n == 0) break; + const bytes = try gpa.dupe(u8, buf[0..n]); + _ = reads_queued[id].fetchAdd(1, .acq_rel); + loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { + tookRead(io, id); + gpa.free(bytes); + break; + }; + } + _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; +} + +const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; + +fn pasteBytes(key: vaxis.Key) []const u8 { + const text = key.text orelse ""; + if (text.len > 0) return text; + const cp = vaxis_input.mapKey(vaxis_input.effCp(key)); + if (cp == pardes.Key.tab) return "\t"; + if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n"; + return ""; +} + +test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { + if (comptime builtin.os.tag == .windows) return error.SkipZigTest; + const gpa = std.testing.allocator; + const io = std.testing.io; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(io, gpa, &env, .{}); + var output: std.Io.Writer.Allocating = .init(gpa); + defer output.deinit(); + defer vx.deinit(gpa, &output.writer); + vx.queries_done.store(false, .unordered); + var tty: vaxis.Tty = undefined; + var loop: Loop = .init(io, &tty, &vx); + var feed: Feed = .{}; + const Reader = struct { + parts: []const []const u8, + next: usize = 0, + fn getWinsize(_: *@This()) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + pub fn inputFollows(self: *@This(), _: u32) bool { + return self.next < self.parts.len; + } + fn read(self: *@This(), buf: []u8) !usize { + if (self.next == self.parts.len) return 0; + const part = self.parts[self.next]; + self.next += 1; + @memcpy(buf[0..part.len], part); + return part.len; + } + }; + var reader: Reader = .{ + .parts = &.{ + // The startup width queries' answers from a terminal without + // explicit width (foot, ghostty, tmux): two F3s, typed at the prompt. + "\x1b[1;1R\x1b[1;1R\x1b[?62;c", + // Kitty reports Ctrl and Shift pressed on their own: the Ctrl of a + // Ctrl-V typed `\x1b[57442;5u` into the shell. + "\x1b[57442;5u\x1b[57441;2u\x1b[57358u", + // F3, F5 and Insert the kitty way, F3 the legacy way and the + // keypad's Up: once typed as private-use junk, now what htop, + // mc and vim read them as. + "\x1b[13~\x1b[15~\x1b[2~\x1bOR\x1b[57419u", + "\x1b[104;;104u", + }, + }; + try readInput(&loop, &reader, &vx, &feed); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.body.mode = .tty; + while (core.nextEffect()) |_| {} + while (try loop.tryEvent()) |event| switch (event) { + .key_press => |key| core.update(vaxis_input.keyEvent(key)), + else => {}, + }; + var written: std.Io.Writer.Allocating = .init(gpa); + defer written.deinit(); + while (core.nextEffect()) |effect| { + if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); + } + try std.testing.expectEqualStrings("\x1bOR\x1b[15~\x1b[2~\x1bOR\x1b[Ah", written.written()); +} + +test "the terminal's keys reach a program as its cursor keys' mode and keyboard flags say" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.body.mode = .tty; + while (core.nextEffect()) |_| {} + var written: std.Io.Writer.Allocating = .init(gpa); + defer written.deinit(); + // What the outer terminal sends, what the program asked for, and what + // it should read. + const Case = struct { modes: []const u8, in: []const u8, sent: []const u8 }; + const cases = [_]Case{ + .{ .modes = "", .in = "\x1b[A\x1b[H\x1bOP\x1b[15~", .sent = "\x1b[A\x1b[H\x1bOP\x1b[15~" }, + .{ .modes = "\x1b[?1h", .in = "\x1b[A\x1b[F\x1b[1;5D", .sent = "\x1bOA\x1bOF\x1b[1;5D" }, + .{ .modes = "\x1b[?1l\x1b[>7u", .in = "\x1b[99;5u\x1b[97;3u\x1b[A", .sent = "\x1b[99;5u\x1b[97;3u\x1b[1;1:1A" }, + }; + for (cases) |case| { + core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); + while (core.nextEffect()) |_| {} + var parser: vaxis.Parser = .{}; + var bytes = case.in; + while (bytes.len > 0) { + const result = try parser.parse(bytes, gpa); + if (result.n == 0) break; + bytes = bytes[result.n..]; + if (result.event) |event| switch (event) { + .key_press => |key| core.update(vaxis_input.keyEvent(key)), + else => {}, + }; + } + written.clearRetainingCapacity(); + while (core.nextEffect()) |effect| { + if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); + } + try std.testing.expectEqualStrings(case.sent, written.written()); + } +} + +test "keypad Enter matches Return for editor input terminal writes and paste" { + for ([_]u21{ vaxis.Key.enter, vaxis.Key.kp_enter }) |codepoint| { + const key: vaxis.Key = .{ .codepoint = codepoint }; + const event = vaxis_input.keyEvent(key); + try std.testing.expectEqual(pardes.Key.enter, event.key.cp); + try std.testing.expectEqualStrings("\n", pasteBytes(key)); + { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("ab"); + core.update(.{ .key = .{ .cp = 'i' } }); + core.update(event); + try std.testing.expectEqualStrings("\nab", pane.file.?.content); + } + { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.body.mode = .tty; + while (core.nextEffect()) |_| {} + core.update(event); + var written: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer written.deinit(); + while (core.nextEffect()) |effect| { + if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); + } + try std.testing.expectEqualStrings("\r", written.written()); + } + } +} + +fn mouseEvent(m: vaxis.Mouse) ?pardes.Event { + const button: pardes.Mouse.Button = switch (m.button) { + .left => .left, + .middle => .middle, + .right => .right, + .wheel_up => .wheel_up, + .wheel_down => .wheel_down, + .wheel_left => .wheel_left, + .wheel_right => .wheel_right, + // A mouse's side buttons, as xterm reports them: Back and Forward. + .button_8 => .back, + .button_9 => .forward, + .none => .none, // button-less motion: hover tracking + else => return null, + }; + return .{ .mouse = .{ + .button = button, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + .col = cellOf(m.col), + .row = cellOf(m.row), + .ctrl = m.mods.ctrl, + .shift = m.mods.shift, + .alt = m.mods.alt, + } }; +} + +/// A report's cell, 0-based: one before the first (SGR's 0, a drag past +/// the window's top or left edge, in cells or in 1016's pixels) is the +/// first, never a panic; past the far edge the core clamps it. +pub fn cellOf(v: i16) u16 { + return @intCast(@max(0, v)); +} + +test "a mouse report at row or column 0, or before it, is the window's edge, never a panic" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + for ([_][]const u8{ "\x1b[<1;42;0M", "\x1b[<0;0;5M", "\x1b[<32;0;0M", "\x1b[<0;0;0m" }) |sequence| { + var parser: vaxis.Parser = .{}; + const result = try parser.parse(sequence, std.testing.allocator); + const m = result.event.?.mouse; + const event = mouseEvent(m) orelse continue; + try std.testing.expect(event.mouse.col <= 41 and event.mouse.row <= 4); + p.update(event); + } +} + +test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 and X2 are" { + for ([_]vaxis.Mouse.Button{ .button_8, .button_9 }, [_]pardes.Mouse.Button{ .back, .forward }) |from, to| { + const event = mouseEvent(.{ .col = 3, .row = 2, .button = from, .mods = .{}, .type = .press }).?; + try std.testing.expectEqual(to, event.mouse.button); + } +} + +/// A replica client's own line over its frame's last row (`Remote.notify`), +/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps +/// the slices). +fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { + if (rows == 0) return; + for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ + .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, + .style = .{ .reverse = true }, + }); +} + +/// A blank whose ink alone changed is not sent: vaxis's render skips it +/// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows +/// nowhere. Deciding that here cost every cell of every frame a look at the +/// frame before; vaxis already makes that comparison. +fn paintCells(win: vaxis.Window, cells: []const pardes.Cell, cols: u16, rows: u16) void { + win.clear(); + var y: u16 = 0; + while (y < rows) : (y += 1) { + var x: u16 = 0; + while (x < cols) : (x += 1) { + const cell = &cells[@as(usize, y) * cols + x]; + if (cell.default) continue; + win.writeCell(x, y, .{ + .char = .{ .grapheme = cell.grapheme() }, + .style = vaxisStyle(cell.style), + }); + } + } +} + +test "a fade sends the text it dims, not the blanks beside it" { + const gpa = std.testing.allocator; + var env = try std.testing.environ.createMap(gpa); + defer env.deinit(); + var vx = try vaxis.init(std.testing.io, gpa, &env, .{}); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + defer vx.deinit(gpa, &out.writer); + try vx.resize(gpa, &out.writer, .{ .rows = 1, .cols = 32, .x_pixel = 0, .y_pixel = 0 }); + // `a`, a gap, `b`, a two-cell gap, `c`, a gap, an underlined blank + // (which shows its ink) and one more blank. + var cells: [32]pardes.Cell = @splat(.{ .default = false }); + cells[0].text[0] = 'a'; + cells[12].text[0] = 'b'; + cells[15].text[0] = 'c'; + cells[30].style.ul = .single; + var sent: [2][]u8 = .{ &.{}, &.{} }; + defer for (sent) |bytes| gpa.free(bytes); + for ([_][3]u8{ .{ 200, 200, 200 }, .{ 90, 90, 90 } }, 0..) |ink, frame| { + for (&cells) |*cell| cell.style.fg = .{ .rgb = ink }; + out.clearRetainingCapacity(); + paintCells(vx.window(), &cells, 32, 1); + try vx.render(&out.writer); + sent[frame] = try out.toOwnedSlice(); + } + // Against a cleared screen every cell goes. After the fade the letters + // go and the underlined blank; every plain blank is jumped. + try std.testing.expectEqual(@as(usize, 29), std.mem.count(u8, sent[0], " ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, sent[1], " ")); + try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'b') != null); + try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'c') != null); + try std.testing.expect(std.mem.indexOf(u8, sent[1], "90:90:90") != null); + try std.testing.expect(std.mem.indexOfScalar(u8, sent[1], 'a') != null); +} + +/// T1 (§9.2): each notice chip casts a shadow one cell right and one down, +/// inside its own pane's body: its ground 35% toward black in OKLab on a +/// cell with text; on a blank one a half block (▌ on the right, ▀ below, +/// ▘ at the corner) in the darker colour, so the shadow is half a cell +/// thick and reads as one. Never the cursor's cell, a selection, a tag or +/// another chip. Truecolor terminals only. +fn chipShadows(arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { + if (!core.settings.chip_shadow or !truecolor) return surface; + const regions = surface.regionList(); + const any = for (regions) |region| { + if (region.kind == .notice) break true; + } else false; + if (!any) return surface; + const out = try arena.create(pardes.Surface); + out.* = surface.*; + out.cells = try arena.dupe(pardes.Cell, surface.cells); + const theme = core.theme(); + const page = theme.bg orelse pardes.colors.null_page; + for (regions) |chip| { + if (chip.kind != .notice or chip.rect.w == 0) continue; + const body = for (regions) |region| { + if (region.kind == .body and region.owner == chip.owner) break region.rect; + } else continue; + const right = chip.rect.x + chip.rect.w; + const below = chip.rect.y + chip.rect.h; + // The column right of it (from its second row), the row below (from + // its second column), and the corner. + var y = chip.rect.y; + while (y <= below) : (y += 1) { + var x = chip.rect.x; + while (x <= right) : (x += 1) { + const side = x == right and y > chip.rect.y and y < below; + const foot = y == below and x > chip.rect.x and x < right; + const corner = x == right and y == below; + if (!side and !foot and !corner) continue; + if (x < body.x or y < body.y or x >= body.x + body.w or y >= body.y + body.h or x >= out.cols or y >= out.rows) continue; + if (surface.cursor) |cu| if (cu.x == x and cu.y == y) continue; + const covered = for (regions) |region| { + if ((region.kind == .notice or region.kind == .tag or region.kind == .grip) and x >= region.rect.x and x < region.rect.x + region.rect.w and y >= region.rect.y and y < region.rect.y + region.rect.h) break true; + } else false; + if (covered) continue; + const cell = &out.cells[@as(usize, y) * out.cols + x]; + const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue; + const dark = pardes.colors.mixOklab(ground, .{ 0, 0, 0 }, 0.35); + const blank = cell.default or cell.len == 0 or (cell.len == 1 and cell.text[0] == ' '); + if (blank) { + const glyph: []const u8 = if (corner) "▘" else if (side) "▌" else "▀"; + cell.* = .{ .default = false, .style = .{ .fg = .{ .rgb = dark }, .bg = .{ .rgb = ground } } }; + @memcpy(cell.text[0..glyph.len], glyph); + cell.len = @intCast(glyph.len); + } else { + cell.default = false; + cell.style.bg = .{ .rgb = dark }; + } + } + } + } + return out; +} + +/// T7 (§9.2): a pane whose view moved (Region.line) has its scroll thumb +/// brighten, drawn most of the way to the text's colour, and fade back +/// over 250 ms with an ease-out: where you are in the file, as you move. +/// The rail is chrome, not a focus indicator. Truecolor terminals only. +const ThumbFlash = struct { + lines: [pardes.MAX_PANES]i32 = @splat(std.math.minInt(i32)), + since: [pardes.MAX_PANES]u64 = @splat(0), + + const life_ns: u64 = 250 * std.time.ns_per_ms; + + fn apply(flash: *ThumbFlash, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { + const on = core.settings.thumb_flash and truecolor and core.settings.motion != .off; + var out: ?*pardes.Surface = null; + const theme = core.theme(); + const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc }; + for (surface.regionList()) |body| { + if (body.kind != .body or body.owner >= flash.lines.len) continue; + const id = body.owner; + if (flash.lines[id] != std.math.minInt(i32) and flash.lines[id] != body.line) flash.since[id] = core.now_ns; + flash.lines[id] = body.line; + const age = core.now_ns -| flash.since[id]; + if (!on or flash.since[id] == 0 or age >= life_ns) continue; + const rail = for (surface.regionList()) |region| { + if (region.kind == .rail and region.owner == id) break region; + } else continue; + if (rail.thumb_h == 0) continue; + const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); + const strength = 0.6 * (1 - t) * (1 - t); + if (out == null) { + const copy = try arena.create(pardes.Surface); + copy.* = surface.*; + copy.cells = try arena.dupe(pardes.Cell, surface.cells); + out = copy; + } + const o = out.?; + var y = rail.rect.y + rail.thumb_y; + while (y < rail.rect.y + rail.thumb_y + rail.thumb_h and y < o.rows) : (y += 1) { + var x = rail.rect.x; + while (x < rail.rect.x + rail.rect.w and x < o.cols) : (x += 1) { + const cell = &o.cells[@as(usize, y) * o.cols + x]; + const ground: [3]u8 = switch (cell.style.bg) { + .rgb => |rgb| rgb, + else => continue, + }; + if (!std.mem.eql(u8, &ground, &core.chromeTheme().scroll_thumb)) continue; + cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) }; + } + } + core.shell_continuous = true; + } + return out orelse surface; + } +}; + +/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does +/// not answer vaxis's query (§9.2: vaxis caps or COLORTERM). +fn colortermTruecolor() bool { + const value = std.mem.span(std.c.getenv("COLORTERM") orelse return false); + return std.mem.eql(u8, value, "truecolor") or std.mem.eql(u8, value, "24bit"); +} + +/// T2 (docs/render-pipeline.md §9.2): the cursor jumping three cells or +/// more leaves a trail of three to five cells along its path, just behind +/// it, their ground drawn toward the text's colour, most beside the +/// cursor, all fading out over 120 ms. Truecolor terminals only; a cell a +/// frame changes, a few bytes. Never the cursor's own cell, a selection or +/// anything outside the focused pane's body; off with Motion off. +const JumpTrail = struct { + last: ?[2]u16 = null, + from: [2]u16 = .{ 0, 0 }, + to: [2]u16 = .{ 0, 0 }, + start_ns: u64 = 0, + active: bool = false, + + const life_ns: u64 = 120 * std.time.ns_per_ms; + + fn apply(trail: *JumpTrail, arena: std.mem.Allocator, surface: *pardes.Surface, core: *pardes.Pardes, truecolor: bool) !*pardes.Surface { + defer core.shell_continuous = trail.active or core.shell_continuous; + const on = core.settings.jump_trail and truecolor and core.settings.motion != .off; + const cursor = surface.cursor orelse { + trail.active = false; + return surface; + }; + const here: [2]u16 = .{ cursor.x, cursor.y }; + if (trail.last) |was| { + const dx = @as(i32, here[0]) - was[0]; + const dy = @as(i32, here[1]) - was[1]; + if (on and @max(@abs(dx), @abs(dy)) >= 3) { + trail.* = .{ .last = here, .from = was, .to = here, .start_ns = core.now_ns, .active = true }; + } + } + trail.last = here; + if (!on or !trail.active) { + trail.active = false; + return surface; + } + const age = core.now_ns -| trail.start_ns; + if (age >= life_ns or !std.meta.eql(trail.to, here)) { + trail.active = false; + return surface; + } + const out = try arena.create(pardes.Surface); + out.* = surface.*; + out.cells = try arena.dupe(pardes.Cell, surface.cells); + const theme = core.theme(); + const ink = theme.fg orelse .{ 0xcc, 0xcc, 0xcc }; + const page = theme.bg orelse pardes.colors.null_page; + const body = for (surface.regionList()) |region| { + if (region.kind == .body and region.owner == core.active) break region.rect; + } else return out; + const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); + const fade = (1 - t) * (1 - t); + const dx = @as(f32, @floatFromInt(@as(i32, trail.from[0]) - trail.to[0])); + const dy = @as(f32, @floatFromInt(@as(i32, trail.from[1]) - trail.to[1])); + const span = @max(@abs(dx), @abs(dy)); + const n: usize = @intFromFloat(std.math.clamp(@round(span / 4), 3, 5)); + var k: usize = 1; + var last_cell: ?[2]i32 = null; + var step: f32 = 1; + while (k <= n and step <= span) : (step += 1) { + const x: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[0])) + dx * step / span)); + const y: i32 = @intFromFloat(@round(@as(f32, @floatFromInt(trail.to[1])) + dy * step / span)); + if (last_cell) |seen| if (seen[0] == x and seen[1] == y) continue; + last_cell = .{ x, y }; + defer k += 1; + if (x < body.x or y < body.y or x >= @as(i32, body.x) + body.w or y >= @as(i32, body.y) + body.h) continue; + const cell = &out.cells[@as(usize, @intCast(y)) * out.cols + @as(usize, @intCast(x))]; + const ground: [3]u8 = if (cell.default) page else switch (cell.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (std.mem.eql(u8, &ground, &theme.sel_bg)) continue; + const strength = 0.55 * fade * (1 - @as(f32, @floatFromInt(k - 1)) / @as(f32, @floatFromInt(n))); + if (strength < 0.02) continue; + const was_default = cell.default; + cell.default = false; + if (was_default) cell.style = .{}; + cell.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, strength) }; + } + return out; + } +}; + +fn paintCursor(win: vaxis.Window, x: u16, y: u16, bar: bool) void { + win.showCursor(x, y); + win.setCursorShape(if (bar) .beam else .default); +} + +fn vaxisStyle(s: pardes.CellStyle) vaxis.Style { + return .{ + .fg = vaxisColor(s.fg), + .bg = vaxisColor(s.bg), + .bold = s.bold, + .dim = s.dim, + .italic = s.italic, + .blink = s.blink, + .reverse = s.reverse, + .invisible = s.invisible, + .strikethrough = s.strikethrough, + .ul_style = switch (s.ul) { + .off => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + }; +} + +fn vaxisColor(c: pardes.Color) vaxis.Color { + return switch (c) { + .default => .default, + .index => |i| .{ .index = i }, + .rgb => |rgb| .{ .rgb = rgb }, + }; +} + +test "a jump leaves a trail of a few cells behind the cursor that fades in 120 ms" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); + try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); + core.settings.jump_trail = true; + for (0..40) |_| core.update(.tick); + core.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try core.render(arena.allocator()); + const body = for (s.regionList()) |region| { + if (region.kind == .body) break region.rect; + } else return error.NoBody; + var trail: JumpTrail = .{}; + core.now_ns = std.time.ns_per_s; + s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; + _ = try trail.apply(arena.allocator(), s, core, true); + // Ten cells right: a trail back toward where it was. + s.cursor = .{ .x = body.x + 12, .y = body.y + 1 }; + core.now_ns += 16 * std.time.ns_per_ms; + const lit = try trail.apply(arena.allocator(), s, core, true); + try std.testing.expect(trail.active and core.shell_continuous); + var changed: usize = 0; + for (lit.cells, s.cells, 0..) |a, b, i| { + if (std.meta.eql(a.style.bg, b.style.bg)) continue; + changed += 1; + // On the cursor's row, behind it, never its own cell. + try std.testing.expectEqual(@as(usize, body.y + 1), i / s.cols); + try std.testing.expect(i % s.cols < body.x + 12 and i % s.cols > body.x + 2); + } + try std.testing.expect(changed >= 3 and changed <= 5); + // Gone by 120 ms; a step of a cell leaves none; nor a terminal without + // truecolor. + core.now_ns += 130 * std.time.ns_per_ms; + core.shell_continuous = false; + const faded = try trail.apply(arena.allocator(), s, core, true); + try std.testing.expect(faded == s and !trail.active and !core.shell_continuous); + s.cursor = .{ .x = body.x + 13, .y = body.y + 1 }; + try std.testing.expect(try trail.apply(arena.allocator(), s, core, true) == s); + s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; + try std.testing.expect(try trail.apply(arena.allocator(), s, core, false) == s); +} + +test "a notice chip casts a cell's shadow right and down, inside its body, off the cursor" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.setTestFile(std.mem.asBytes(&@as([20][20]u8, @splat("some text on a line\n".*)))); + try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); + core.settings.chip_shadow = true; + try std.testing.expect(core.executeBuiltinLine(0, "Msg a notice")); + for (0..60) |_| core.update(.tick); + core.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try core.render(arena.allocator()); + const chip = for (s.regionList()) |region| { + if (region.kind == .notice) break region.rect; + } else return error.NoNotice; + s.cursor = null; + const out = try chipShadows(arena.allocator(), s, core, true); + try std.testing.expect(out != s); + var changed: usize = 0; + for (out.cells, s.cells, 0..) |a, b, i| { + if (std.meta.eql(a, b)) continue; + changed += 1; + const x = i % s.cols; + const y = i / s.cols; + // Right of the chip or below it, never inside it. + try std.testing.expect(x == chip.x + chip.w or y == chip.y + chip.h); + try std.testing.expect(!(x >= chip.x and x < chip.x + chip.w and y >= chip.y and y < chip.y + chip.h)); + } + try std.testing.expect(changed >= chip.w - 1); + // Off, or without truecolor: the frame as it was. + try std.testing.expect(try chipShadows(arena.allocator(), s, core, false) == s); + core.settings.chip_shadow = false; + try std.testing.expect(try chipShadows(arena.allocator(), s, core, true) == s); +} + +test "a scrolled pane's thumb brightens and fades back in 250 ms" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([200][20]u8, @splat("some text on a line\n".*)))); + try std.testing.expect(core.executeBuiltinLine(0, "Theme forge")); + core.settings.thumb_flash = true; + for (0..40) |_| core.update(.tick); + core.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var flash: ThumbFlash = .{}; + core.now_ns = std.time.ns_per_s; + const first = try core.render(arena.allocator()); + try std.testing.expect(try flash.apply(arena.allocator(), first, core, true) == first); + pane.scrollBy(20); + core.now_ns += 16 * std.time.ns_per_ms; + const moved = try core.render(arena.allocator()); + const lit = try flash.apply(arena.allocator(), moved, core, true); + try std.testing.expect(lit != moved and core.shell_continuous); + var brighter: usize = 0; + for (lit.cells, moved.cells) |a, b| { + if (!std.meta.eql(a.style.bg, b.style.bg)) brighter += 1; + } + try std.testing.expect(brighter >= 1); + core.now_ns += 300 * std.time.ns_per_ms; + core.shell_continuous = false; + const later = try core.render(arena.allocator()); + try std.testing.expect(try flash.apply(arena.allocator(), later, core, true) == later); + try std.testing.expect(!core.shell_continuous); +} diff --git a/src/tutor.txt b/src/tutor.txt index 5cfb245b..1de2a4e6 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -60,11 +60,11 @@ and an image's: | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| Save Tty Collapse Del -| Tty Save Mode Filter Collapse Del -| Tty PdfSections PdfTint PdfFit Collapse Del -| Tty Collapse Del +| New Term Find Grep Joincol Delcol +| Save Term Collapse Del +| Term Save Mode Filter Collapse Del +| Term PdfSections PdfTint PdfFit Collapse Del +| Term Collapse Del 1. Press : here: the keyboard goes to this pane's tag, on `Save`. Press A, type a space and Help, press Esc, then Tab: `Help` diff --git a/test/agent_session.py b/test/agent_session.py index aa87c845..8a62bf26 100644 --- a/test/agent_session.py +++ b/test/agent_session.py @@ -47,7 +47,7 @@ def run(args, command, status): signal.setitimer(signal.ITIMER_REAL, args.timeout) try: context = session(str(args.binary.resolve()), root, 'agent-session', tty=True, - socket_name='agent-session', launch=['--tty', '--9p=agent-session'], + socket_name='agent-session', launch=['--tui', '--9p=agent-session'], inherited={'PARDES_TEST_GRID': '1'} if args.gui_grid else {}) client, _ = context.__enter__() try: diff --git a/test/appearance_gallery.py b/test/appearance_gallery.py index 98420a15..8672de71 100644 --- a/test/appearance_gallery.py +++ b/test/appearance_gallery.py @@ -16,7 +16,7 @@ THEMES = ('forge', 'lagoon', 'solarium', 'spectrum', 'harvest', 'clay') NOTES = b'''Pardes / workspace review New belongs to the column. -Tty opens a terminal. +Term opens a terminal. Mode switches its input mode. Font MartianMono-NrRg:18 @@ -84,7 +84,7 @@ def run(args): client.write(f'/pane/{right}/body', PREFERENCE_NOTES if args.theme_selector else NOTES, truncate=True) client.write(f'/pane/{right}/dirty', b'0\n') before = set(panes(client)) - command(client, right, 'Tty') + command(client, right, 'Term') terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') client.write(f'/pane/{terminal}/pty/data', b"PS1='$ '; printf '\\033[2J\\033[H\\033[1;36mPardes workspace\\033[0m\\n\\n'; printf 'Agave source: read-only\\nTerminal: ready\\n\\n'; printf '\\033[32mSmall touches. Same workflow.\\033[0m\\n'\r") require(wait_for(lambda: b'Small touches. Same workflow.' in client.read(f'/pane/{terminal}/body')), 'terminal output missing') diff --git a/test/behaviour/columns_and_tags.zig b/test/behaviour/columns_and_tags.zig index 22f55774..d5820610 100644 --- a/test/behaviour/columns_and_tags.zig +++ b/test/behaviour/columns_and_tags.zig @@ -57,11 +57,11 @@ test "columns-and-tags: Newcol makes an empty column with the keyboard on its ta const left, const col = .{ try s.column(0), try s.column(1) }; try expectEqualStrings(s.at("{d}:{d} {d}:", .{ left, first, col }), try s.columns()); try s.expect("/focus", ""); - try s.write(s.at("/pane/{d}/exec", .{first}), "Tty\n"); + try s.write(s.at("/pane/{d}/exec", .{first}), "Term\n"); const shell = try s.focused(); try expectEqualStrings(s.at("{d}:{d} {d}:{d}", .{ left, first, col, shell }), try s.columns()); - // The next Tty splits as it always has: nothing is empty any more. - try s.write(s.at("/pane/{d}/exec", .{shell}), "Tty\n"); + // The next Term splits as it always has: nothing is empty any more. + try s.write(s.at("/pane/{d}/exec", .{shell}), "Term\n"); try expectEqualStrings(s.at("{d}:{d} {d}:{d},{d}", .{ left, first, col, shell, try s.focused() }), try s.columns()); } @@ -160,7 +160,7 @@ test "columns-and-tags: New is a column tag's word, in no pane's tag nor the wor var words = std.mem.tokenizeScalar(u8, tag, ' '); while (words.next()) |word| try std.testing.expect(!std.mem.eql(u8, word, "New")); } - try expectEqualStrings("New Tty Find Grep Joincol Delcol", try s.read(s.at("/col/{d}/tag", .{try s.column(0)}))); + try expectEqualStrings("New Term Find Grep Joincol Delcol", try s.read(s.at("/col/{d}/tag", .{try s.column(0)}))); } test "columns-and-tags: a click past a column tag's text types after it, a newline typed there a space, and a long tag scrolls to its caret" { @@ -168,12 +168,12 @@ test "columns-and-tags: a click past a column tag's text types after it, a newli defer s.deinit(); const tag = s.at("/col/{d}/tag", .{try s.column(0)}); // Its row, then the pane's tag: the column's stays one row. - const rows = " New Tty Find Grep Joincol Delcol"; + const rows = " New Term Find Grep Joincol Delcol"; try std.testing.expect(std.mem.indexOf(u8, try s.screen(), rows ++ " ") != null); try s.click("Delcol", 20, 1); // A clicked tag is in normal mode: `i` types where it was clicked. try s.keys("i\nSnarf"); - try expectEqualStrings("New Tty Find Grep Joincol Delcol Snarf", try s.read(tag)); + try expectEqualStrings("New Term Find Grep Joincol Delcol Snarf", try s.read(tag)); try std.testing.expect(std.mem.indexOf(u8, try s.screen(), rows ++ " Snarf ") != null); // The pane's tag on the row right under it: the column's is one row. try std.testing.expectEqual((try s.where(rows))[1] + 1, (try s.where("/test.txt Save"))[1]); @@ -265,7 +265,7 @@ test "columns-and-tags: a column tag lights the word under the mouse, is clicked try s.write("/mousein", s.at("m {d} 1 0\n", .{x})); const lit = try s.bg(x, 1); try std.testing.expect(!std.mem.eql(u8, plain, lit)); - try expectEqualStrings(plain, try s.bg(x + 4, 1)); // Tty, another word + try expectEqualStrings(plain, try s.bg(x + 4, 1)); // Term, another word // Pressed, the keyboard is on the tag, its caret where it was pressed. try s.write("/mousein", s.at("m {d} 1 1\n", .{x})); try s.expect("/focus", ""); @@ -277,7 +277,7 @@ test "columns-and-tags: a column tag lights the word under the mouse, is clicked try std.testing.expect(!std.mem.eql(u8, lit, try s.bg(x + 4, 1))); // A clicked tag is in normal mode: `i` types at its caret. try s.keys("\u{F00D}iHelp "); - try std.testing.expect(std.mem.startsWith(u8, try s.read(tag), "Help New Tty")); + try std.testing.expect(std.mem.startsWith(u8, try s.read(tag), "Help New Term")); try std.testing.expectEqual(x + 5, (try s.cursor()).?[0]); // A tag one short of its room: its caret at the end is drawn on the // last cell, and one more letter scrolls the text, never the caret. diff --git a/test/behaviour/look_and_exec.zig b/test/behaviour/look_and_exec.zig index c46ca394..ee9554cc 100644 --- a/test/behaviour/look_and_exec.zig +++ b/test/behaviour/look_and_exec.zig @@ -135,7 +135,7 @@ test "look-and-exec: look and exec read back what the last command touched, a ct try s.write("/exec", "Msg first\n"); try s.expect("/exec", s.at("{d}\n", .{n})); // A pane made through ctl is what both read next, not the Msg's pane. - try s.write(s.at("/pane/{d}/ctl", .{n}), "Tty\n"); + try s.write(s.at("/pane/{d}/ctl", .{n}), "Term\n"); const made = try s.focused(); try std.testing.expect(made != n); try s.expect("/exec", s.at("{d}\n", .{made})); @@ -159,7 +159,7 @@ test "look-and-exec: a line starting with # runs as nothing at an exec or a ctl, const log = try s.read("/log"); const col = std.mem.sliceTo(try s.read("/layout"), ' '); for ([_][]const u8{ "/exec", s.at("/pane/{d}/exec", .{n}), "/ctl", s.at("/pane/{d}/ctl", .{n}), s.at("/col/{s}/ctl", .{col}) }) |path| - try s.write(path, "# Platform: tty\n # indented too\n"); + try s.write(path, "# Platform: tui\n # indented too\n"); try s.expect("/index", index); try s.expect("/log", log); } diff --git a/test/behaviour/modes.zig b/test/behaviour/modes.zig index ba792086..961ca788 100644 --- a/test/behaviour/modes.zig +++ b/test/behaviour/modes.zig @@ -32,7 +32,7 @@ test "modes: Esc in a column or the workspace tag gives the keyboard back to a p var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); _ = try s.newPane(); - for ([_][]const u8{ "New Tty", "Newcol" }) |tag| { + for ([_][]const u8{ "New Term", "Newcol" }) |tag| { const was = try s.focused(); // A click puts the tag in normal mode, the keyboard there; Esc is // out of it. @@ -96,7 +96,7 @@ test "modes: Esc back into a file leaves its view where it was, and a look centr // The other arm still centres: a look's `:NN`. const line = 60; try s.write(s.at("/pane/{d}/look", .{doc}), s.at(":{d}\n", .{line})); - const rows = (try s.where("Tty Save Mode"))[1] - (try s.where("/test.txt"))[1] - 1; + const rows = (try s.where("Term Save Mode"))[1] - (try s.where("/test.txt"))[1] - 1; // Drawn mid-pane, a row either way. const drawn_at = line - try topLine(&s, "/test.txt"); try std.testing.expect(drawn_at + 1 >= rows / 2 and drawn_at <= rows / 2 + 1); @@ -468,7 +468,7 @@ test "modes: hopping between two panes by Esc, window mode or a click makes no p try expectEqual(want, try s.focused()); } const doc_row = (try s.where("row"))[1]; - const shell_row = (try s.where("Tty Save Mode"))[1] + 1; + const shell_row = (try s.where("Term Save Mode"))[1] + 1; for (0..8) |_| { const other = if (try s.focused() == doc) shell else doc; const row = if (other == doc) doc_row else shell_row; diff --git a/test/behaviour/mouse.zig b/test/behaviour/mouse.zig index d7da46e8..a0ac7a23 100644 --- a/test/behaviour/mouse.zig +++ b/test/behaviour/mouse.zig @@ -129,7 +129,7 @@ test "mouse: a B1 sweep over several lines is a stream, as acme's, in a body and const tx, const ty = try s.where("Collapse"); const lx, const ly = try s.where("Look Edit"); try mouse(&s, "m {d} {d} 1\nm {d} {d} 1\nm {d} {d} 3\nm {d} {d} 0\n", .{ tx + 3, ty, lx + 1, ly, lx + 1, ly, lx + 1, ly }); - try s.expect(tag, "/test.txt Save Tty Colok Edit"); + try s.expect(tag, "/test.txt Save Term Colok Edit"); } test "mouse: a click on either half of a wide character lands before it, in the text and on a tag's path, and the caret steps over it whole" { diff --git a/test/behaviour/tags.zig b/test/behaviour/tags.zig index 8609e134..71faed3a 100644 --- a/test/behaviour/tags.zig +++ b/test/behaviour/tags.zig @@ -41,9 +41,9 @@ test "tags: ms and md edit a tag's own text, and the text the edit made is read defer s.deinit(); const n = try s.focused(); try s.keys(":miwms("); - try std.testing.expectEqualStrings("/test.txt (Save) Tty Collapse Del", try tag(&s, n)); + try std.testing.expectEqualStrings("/test.txt (Save) Term Collapse Del", try tag(&s, n)); try s.keys("md("); - try std.testing.expectEqualStrings("/test.txt Save Tty Collapse Del", try tag(&s, n)); + try std.testing.expectEqualStrings("/test.txt Save Term Collapse Del", try tag(&s, n)); } test "tags: the keyboard reaches a tag's path, which it can select and yank but not edit" { @@ -66,7 +66,7 @@ test "tags: the keyboard reaches a tag's path, which it can select and yank but try s.expect(s.at("/pane/{d}/name", .{n}), "/test.txt\n"); // After the path, the text is the tag's own to edit. try s.keys(":A!\x1b"); - try std.testing.expectEqualStrings("/test.txt Save Tty Collapse Del!", try tag(&s, n)); + try std.testing.expectEqualStrings("/test.txt Save Term Collapse Del!", try tag(&s, n)); // What it yanked was the path. try s.keys(":P"); try s.expect(s.at("/pane/{d}/body", .{n}), "/test.txtbody\n"); @@ -102,7 +102,7 @@ test "tags: a tag remembers its cursor, starts on Save, and a click moves it" { try std.testing.expectEqual(@as(usize, 5), try tagCol(&s, "/second.txt")); try s.keys(":"); // A click in the tag puts its cursor there, the pane's keyboard with it. - try s.click("Save Tty", 6, 1); + try s.click("Save Term", 6, 1); try std.testing.expectEqual(first, try s.focused()); try std.testing.expectEqual(@as(usize, "/test.txt Save T".len), try tagCol(&s, "/test.txt")); // A prompt opened and left from the body leaves it there (a clicked @@ -187,7 +187,7 @@ test "tags: a tag's normal mode is the body's: motions stay in the tag and inser try s.keys(window ++ "h\n"); try std.testing.expectEqual(first, try s.focused()); try s.keys(":i\u{F018}hjklHJKL:"); - try std.testing.expectEqualStrings("/test.txt Save Tty Collapse DelhjklHJKL:", try tag(&s, first)); + try std.testing.expectEqualStrings("/test.txt Save Term Collapse DelhjklHJKL:", try tag(&s, first)); try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{first})), " mode:normal ")); try s.expect(s.at("/pane/{d}/body", .{first}), "body\n"); try std.testing.expectEqual(first, try s.focused()); @@ -202,7 +202,7 @@ test "tags: a tag with a newline in it is as tall as its lines, and each line is if (bottom) try s.write("/ctl", "Tagbottom on\n"); // Insert mode in a tag is a body's: Enter is a new line. try s.keys(":A\nSecond"); - try std.testing.expectEqualStrings("/test.txt Save Tty Collapse Del\nSecond", try tag(&s, n)); + try std.testing.expectEqualStrings("/test.txt Save Term Collapse Del\nSecond", try tag(&s, n)); const x, const y = try s.where("/test.txt"); try std.testing.expectEqual(.{ x, y + 1 }, try s.where("Second")); // The caret is on the second line, after what was typed. @@ -216,7 +216,7 @@ test "tags: a tag with a newline in it is as tall as its lines, and each line is try std.testing.expectEqual(.{ x + 2, y + 1 }, (try s.cursor()).?); // A clicked tag is in normal mode: `i` types where it was clicked. try s.keys("iX"); - try std.testing.expectEqualStrings("/test.txt Save Tty Collapse Del\nSeXcond", try tag(&s, n)); + try std.testing.expectEqualStrings("/test.txt Save Term Collapse Del\nSeXcond", try tag(&s, n)); try s.expect(s.at("/pane/{d}/body", .{n}), "body\n"); } } @@ -311,14 +311,14 @@ test "tags: a name drafted in the tag commits with Enter, cancels with two Escs, try clickPathEnd(&s, path); try s.keys("\x15/new name.zig"); try s.expect(name, s.at("{s}\n", .{path})); - _ = try s.where("/new name.zig Save Tty Collapse Del SyntaxBold"); + _ = try s.where("/new name.zig Save Term Collapse Del SyntaxBold"); try s.expect(s.at("/pane/{d}/body", .{n}), "original body\n"); // Esc keeps the draft pending; a second drops it. try s.keys(if (commit) "\n" else "\x1b\x1b"); try s.expect(name, if (commit) "/new name.zig\n" else "/test.txt\n"); - try std.testing.expectEqualStrings(s.at("{s} Save Tty Collapse Del SyntaxBold", .{if (commit) "/new name.zig" else "/test.txt"}), try tag(&s, n)); + try std.testing.expectEqualStrings(s.at("{s} Save Term Collapse Del SyntaxBold", .{if (commit) "/new name.zig" else "/test.txt"}), try tag(&s, n)); // The keyboard is the body's again. - try std.testing.expect((try s.cursor()).?[1] != (try s.where("Save Tty"))[1]); + try std.testing.expect((try s.cursor()).?[1] != (try s.where("Save Term"))[1]); } try std.testing.expectEqual(@as(usize, 0), s.saved); // A name alone is no edit: the pane stays clean. @@ -365,9 +365,9 @@ test "tags: middle clicking Save commits the drafted name before saving" { const n = try s.focused(); try clickPathEnd(&s, "/test.txt"); try s.keys("\x15/renamed.txt"); - try s.click("Save Tty", 0, 2); + try s.click("Save Term", 0, 2); try s.expect(s.at("/pane/{d}/name", .{n}), "/renamed.txt\n"); - try std.testing.expectEqualStrings("/renamed.txt Save Tty Collapse Del", try tag(&s, n)); + try std.testing.expectEqualStrings("/renamed.txt Save Term Collapse Del", try tag(&s, n)); try s.expect(s.at("/pane/{d}/body", .{n}), "untouched\n"); try std.testing.expectEqual(@as(usize, 1), s.saved); } diff --git a/test/column_tags.py b/test/column_tags.py index ba638b7d..838dbd9a 100644 --- a/test/column_tags.py +++ b/test/column_tags.py @@ -114,9 +114,9 @@ def run(args): launch=launch, inherited=env, terminal=handles) as (client, address), contextlib.ExitStack() as connections: print('socket', address, flush=True) keys = Input(handles['input_fd']) - await_text(client, 1, 'New Tty Find Grep Joincol') - require(locate(client, 'New Tty', row=1) == (0, 1), 'left column tag does not start flush-left') - require(tag(client, 1).startswith(str(source) + ' Save Tty Del'), + await_text(client, 1, 'New Term Find Grep Joincol') + require(locate(client, 'New Term', row=1) == (0, 1), 'left column tag does not start flush-left') + require(tag(client, 1).startswith(str(source) + ' Save Term Del'), 'generated gap still separates the filename from pane commands') checks.append('pane commands follow the filename with one space') @@ -147,14 +147,14 @@ def run(args): right_body = b'// Column-local scratch\nfn main() {\n let ready = true;\n}\n' client.write(f'/pane/{right}/body', right_body) client.write(f'/pane/{right}/dirty', b'0\n') - require(wait_for(lambda: locate(client, 'New Tty', row=1, minimum_col=75)), 'right column tag missing') - require(locate(client, 'New Tty', row=1, minimum_col=75) == (75, 1), + require(wait_for(lambda: locate(client, 'New Term', row=1, minimum_col=75)), 'right column tag missing') + require(locate(client, 'New Term', row=1, minimum_col=75) == (75, 1), 'right column tag retains an inset') checks.append('column tags start at the first cell of each column') # Column header uses half-open drag ranges; replacement must not leak # into its neighbour, the global header, or the active pane's body. - col_start, _ = locate(client, 'New Tty', row=1, minimum_col=75) + col_start, _ = locate(client, 'New Term', row=1, minimum_col=75) keys.click(col_start, 1) keys.send(b'\x1b[F') keys.send(' Scope λ界') @@ -181,7 +181,7 @@ def run(args): # An owned short-path file makes its complete tag visible. Pane-tag # selections retain the existing inclusive endpoint convention. - save_x, pane_y = require(wait_for(lambda: locate(client, 'Save Tty', minimum_col=75)), 'right pane actions missing') + save_x, pane_y = require(wait_for(lambda: locate(client, 'Save Term', minimum_col=75)), 'right pane actions missing') keys.click(save_x, pane_y) keys.send(b'\x1b[F') keys.send(' TailMark') @@ -206,9 +206,9 @@ def run(args): # Keep a real embedded shell in the right column for useful captures. keys.click(12, 4) before = panes(client) - keys.click(*require(locate(client, 'Tty', row=1, minimum_col=75), 'Tty missing'), button=1) - terminal = require(wait_for(lambda: new_serial(client, before)), 'column Tty did not create a pane') - require('pty' in client.list(f'/pane/{terminal}'), 'Tty created a non-terminal pane') + keys.click(*require(locate(client, 'Term', row=1, minimum_col=75), 'Term missing'), button=1) + terminal = require(wait_for(lambda: new_serial(client, before)), 'column Term did not create a pane') + require('pty' in client.list(f'/pane/{terminal}'), 'Term created a non-terminal pane') client.write(f'/pane/{terminal}/pty/data', b"printf 'Column-local terminal ready\\n'; pwd\r") require(wait_for(lambda: b'\nColumn-local terminal ready\n' in client.read(f'/pane/{terminal}/body').replace(b'\r', b'')), 'terminal command output missing') checks.append('right-column embedded terminal executes harmless commands') @@ -222,7 +222,7 @@ def run(args): saved_global = re.search(rb'\.topbar_custom\s*=\s*"((?:[^"\\]|\\.)*)"', dumped) require(saved_global and codecs.escape_decode(saved_global[1])[0].decode() == global_text, 'global custom tag absent from dump') - require(b'New Tty Find Grep Joincol Work' in dumped, 'column custom tag absent from dump') + require(b'New Term Find Grep Joincol Work' in dumped, 'column custom tag absent from dump') keys.click(1, 0) keys.send(b'\x1b[F') keys.send(' TEMP') @@ -256,19 +256,19 @@ def run(args): keys.send(clean_global) require(wait_for(lambda: row_text(client, 0) == clean_global), 'clean global tag replacement failed') keys.escape() - col_start, _ = require(locate(client, 'New Tty', row=1, minimum_col=75), 'right column tag missing after restore') + col_start, _ = require(locate(client, 'New Term', row=1, minimum_col=75), 'right column tag missing after restore') keys.click(col_start, 1) keys.send(b'\x1b[H\x1b[1;2F') - keys.send('New Tty Find Grep Joincol Work') - require(wait_for(lambda: row_text(client, 1).endswith('New Tty Find Grep Joincol Work')), + keys.send('New Term Find Grep Joincol Work') + require(wait_for(lambda: row_text(client, 1).endswith('New Term Find Grep Joincol Work')), 'clean column tag replacement failed') keys.escape() - clean_pane = str(right_name) + ' Save Tty Del Collapse' + clean_pane = str(right_name) + ' Save Term Del Collapse' current_pane = tag(client, right) require(current_pane.startswith(clean_pane), 'unexpected scratch tag before presentation cleanup') suffix = current_pane[len(clean_pane):] require(suffix.isascii(), 'presentation cleanup expects its own ASCII test suffix') - keys.click(*require(locate(client, 'Save Tty', minimum_col=75), 'scratch pane commands missing')) + keys.click(*require(locate(client, 'Save Term', minimum_col=75), 'scratch pane commands missing')) keys.send(b'\x1b[F') keys.send(b'\x7f' * len(suffix)) require(wait_for(lambda: tag(client, right) == clean_pane), 'clean pane command tail replacement failed') @@ -282,7 +282,7 @@ def run(args): source_tag = tag(client, source_serial) keys.click(12, 2) keys.send(b'\x1b[F') - require(wait_for(lambda: (point := locate(client, 'Save Tty Del', row=2)) + require(wait_for(lambda: (point := locate(client, 'Save Term Del', row=2)) and point[0] < 75), 'long-path tag did not reveal its command tail at End') require(tag(client, source_serial) == source_tag, 'caret movement changed the source tag') capture(client, root, 'columns-tag-reveal', not args.tty) diff --git a/test/daemon.py b/test/daemon.py index 954433a9..7db7e055 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -449,7 +449,7 @@ def clients(binary): assert b'let this client go' in ta.text(), ta.text()[-300:] # A third client, a shell: its keys wait for the session (a pty # write), its output comes back in units, the same on both sides. - nine.write(f'/pane/{pane}/exec', b'Tty\n') + nine.write(f'/pane/{pane}/exec', b'Term\n') shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'term'), None)) wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body')) @@ -522,7 +522,7 @@ def manage(binary): status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines()) sessions[name] = int(status['pid']) started.append(sessions[name]) - c.write('/pane/1/exec', b'Tty\n') + c.write('/pane/1/exec', b'Term\n') wait_for(f'session {name}\'s shell', lambda: terminals(c)) shell = terminals(c)[0] wait_for(f'session {name}\'s shell answers', lambda: run(c, shell, b'true\n') == b'exit 0\n') @@ -1078,7 +1078,7 @@ def main(binary, cycles): started = [] try: term = Term() - stub = term.spawn([binary, '--tty', '--9p=work'], env) + stub = term.spawn([binary, '--tui', '--9p=work'], env) started.append(stub.pid) sock = root / 'pardes-9p-work.sock' wait_for('the session\'s 9P socket', sock.exists) @@ -1181,7 +1181,7 @@ def main(binary, cycles): term = Term() stub_pid = root / 'stub.pid' shell = term.spawn(['sh', '-c', '"$@" & echo $! > "$0"; wait; exec sleep 600', - str(stub_pid), binary, '--tty', '--9p=fresh'], env) + str(stub_pid), binary, '--tui', '--9p=fresh'], env) started.append(shell.pid) sock = root / 'pardes-9p-fresh.sock' wait_for('the second session', sock.exists) @@ -1403,7 +1403,7 @@ def install(binary, at): def upgrades(old, new): - """Upgrade (docs/next-daemon.md, phase 6): a tty session with an unsaved + """Upgrade (docs/next-daemon.md, phase 6): a tui session with an unsaved edit, a shell running `sleep 1000; echo done` and two terminals (two views) moved onto another build installed at the path it started from, the daemon with it; then a build that refuses the dump, which falls back @@ -1425,7 +1425,7 @@ def upgrades(old, new): started = [] try: term = Term() - stub = term.spawn([str(binary), '--tty', '--9p=work'], env) + stub = term.spawn([str(binary), '--tui', '--9p=work'], env) started.append(stub.pid) sock = root / 'pardes-9p-work.sock' wait_for('the session\'s 9P socket', sock.exists) @@ -1610,7 +1610,7 @@ def upgrades(old, new): time.sleep(.3) assert alive(shell_pid) and alive(daemon) term = Term() - stub = term.spawn([str(binary), '--tty', '--9p=again'], env) + stub = term.spawn([str(binary), '--tui', '--9p=again'], env) started.append(stub.pid) sock = root / 'pardes-9p-again.sock' wait_for('the next session', sock.exists) diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 6011ba16..6d0a43ca 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -91,7 +91,7 @@ pub const Harness = struct { return initArgs(gpa, exe, rows, cols, null); } - /// Like init, but passes one extra CLI arg to the app (e.g. "--tty"). + /// Like init, but passes one extra CLI arg to the app (e.g. "--tui"). pub fn initArgs(gpa: std.mem.Allocator, exe: [*:0]const u8, rows: u16, cols: u16, arg: ?[*:0]const u8) !Harness { var argv: [2]?[*:0]const u8 = .{ null, null }; if (arg) |a| argv[0] = a; @@ -221,7 +221,7 @@ pub const Harness = struct { /// The app's output into the emulator. The one query answered is the /// device status request (`CSI 5 n` → `CSI 0 n`), as every terminal /// does: the tty asks it after each frame and draws no other until the - /// answer (FrameAck in src/tty/tty.zig). + /// answer (FrameAck in src/tui/tui.zig). fn feed(self: *Harness, bytes: []const u8) void { self.stream.nextSlice(bytes); const request = "\x1b[5n"; diff --git a/test/fs.py b/test/fs.py index a2b67cbc..f36f1039 100644 --- a/test/fs.py +++ b/test/fs.py @@ -45,7 +45,7 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False master, slave = os.openpty() fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0)) env['TERM'] = 'xterm-256color' - args = [binary, '--tty', '--9p=' + (socket_name or name), *options, str(file or fixture)] + args = [binary, '--tui', '--9p=' + (socket_name or name), *options, str(file or fixture)] preexec = lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0) if launch is not None: args = [binary, *launch] diff --git a/test/gui_golden.py b/test/gui_golden.py index 24fc5986..9afc9c19 100644 --- a/test/gui_golden.py +++ b/test/gui_golden.py @@ -208,8 +208,8 @@ def run(args): client.write('/ctl', b'Debug\n') # A terminal pane: raw rows, ANSI colours, a hidden prompt. before = set(panes(client)) - client.write(f'/pane/{first}/exec', b'Tty\n') - terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Tty missing') + client.write(f'/pane/{first}/exec', b'Term\n') + terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Term missing') client.write(f'/pane/{terminal}/pty/data', b"PS1='$ '; clear; printf '\\033[1;36mcolour\\033[0m plain \\033[32mgreen\\033[0m\\n'\r") require(wait_for(lambda: b'green' in client.read(f'/pane/{terminal}/body')), 'terminal output missing') scene('17-terminal') diff --git a/test/image_harness.zig b/test/image_harness.zig index b45851cc..18392851 100644 --- a/test/image_harness.zig +++ b/test/image_harness.zig @@ -58,7 +58,7 @@ pub fn main(init: std.process.Init) !void { _ = setenv("TERM", "xterm-256color", 1); _ = setenv("LC_ALL", "C", 1); - if (std.mem.eql(u8, backend, "tty")) { + if (std.mem.eql(u8, backend, "tui")) { if (pdf_mode) try runKittyPdf(arena, exe, base) else diff --git a/test/kitty.zig b/test/kitty.zig index 1e1e8331..f5de44e7 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -1,6 +1,6 @@ //! Kitty graphics protocol conformance for terminal panes, at the core. //! -//! zig build kitty-test -Dplatform=tty|gui these cases alone +//! zig build kitty-test -Dplatform=tui|gui these cases alone //! zig build unit-test they run with the rest //! //! ghostty-vt implements the protocol; what pardes owns is the proxy around diff --git a/test/kitty_harness.zig b/test/kitty_harness.zig index 652395b8..204dae69 100644 --- a/test/kitty_harness.zig +++ b/test/kitty_harness.zig @@ -1,6 +1,6 @@ //! Kitty graphics end to end through a terminal pane. //! -//! zig build kitty-harness -Dplatform=tty a fake kitty terminal outside +//! zig build kitty-harness -Dplatform=tui a fake kitty terminal outside //! zig build kitty-harness -Dplatform=gui the SDL renderer's capture //! //! test/kitty.zig checks the proxy at the core; this checks it through the @@ -67,7 +67,7 @@ pub fn main(init: std.process.Init) !void { try run.start(); if (std.c.getenv("PARDES_KITTY_EXPLORE")) |list| return run.explore(std.mem.span(list)); - std.debug.print("kitty harness ({s}):\n", .{if (gui) "gui" else "tty"}); + std.debug.print("kitty harness ({s}):\n", .{if (gui) "gui" else "tui"}); try run.query(); try run.place(); try run.media(); diff --git a/test/monkey.zig b/test/monkey.zig index 2e19cb21..70a4b4e4 100644 --- a/test/monkey.zig +++ b/test/monkey.zig @@ -1,6 +1,6 @@ // pardes-monkey: random snapshot scripts against the tty, hunting panics. // -// zig build monkey -Dplatform=tty -- [steps] [--from=N] [--out=DIR] [--keep] [--views=N] +// zig build monkey -Dplatform=tui -- [steps] [--from=N] [--out=DIR] [--keep] [--views=N] // // Each seed makes one script (a fixed seed makes the same script, so a hit // replays): keys and leader bursts, typing, mouse presses, drags and wheel, diff --git a/test/monkey9p.zig b/test/monkey9p.zig index 45c5d12f..8870e389 100644 --- a/test/monkey9p.zig +++ b/test/monkey9p.zig @@ -4,8 +4,8 @@ //! /log said meanwhile. It was test/monkey9p.py, which drove a real //! `pardes --detach` over its socket. //! -//! zig build monkey-session -Dplatform=tty -- [--seed N]... [--steps M] [--only i,j,k] [--no-shrink] [-v] -//! zig build monkey-session-smoke -Dplatform=tty (part of behaviour-test) +//! zig build monkey-session -Dplatform=tui -- [--seed N]... [--steps M] [--only i,j,k] [--no-shrink] [-v] +//! zig build monkey-session-smoke -Dplatform=tui (part of behaviour-test) //! //! A step's op is drawn from the seed alone: the panes, columns and held //! files it names are tokens (`{p3}`: /index's 4th serial, mod its length, @@ -72,7 +72,7 @@ const shell_lines = [_][]const u8{ "true", "false", "echo hi", "echo m9p", "slee const builtins = [_][]const u8{ "Look", "Exec", "Kill", "Dump", "Msg", "NextColor", "Themes", "DumpThemes", "TreeContext", "PdfFit", "PdfTint", "PdfSections", "Petscii", "Palette", "Ascii", "Save", "New", "Newcol", "Del", "Filter", "Mode", "Togglettymode", "Edit", "Undo", "Redo", "Collapse", - "Delcol", "DelAbove", "DelBelow", "Tty", "Repl", "Joincol", "Config", "LocationsConfig", "Messages", "Mini", "Find", "Grep", "Left", + "Delcol", "DelAbove", "DelBelow", "Term", "Repl", "Joincol", "Config", "LocationsConfig", "Messages", "Mini", "Find", "Grep", "Left", "Down", "Up", "Right", "Back", "Forward", "Last", "Recent", "Jumplist", "Colors", "Wrap", "Tagbottom", "Debug", "FocusTint", "Verbose", "Motion", "InactiveDim", "DumpDir", "Theme", "Placement", "BootShell", "LookWord", "Get", "Put", "Undo", "Redo", "Zerox", "Snarf", "Paste", "Cut", "Sort", "Font", "Local", @@ -426,7 +426,7 @@ fn gen(r: Random, a: Allocator) Op { const s = pickSerial(r, a); const line = shellSafe(a, pick(r, &shell_lines)); const x = chance(r); - if (x < 0.25) return .{ .write = .{ .path = print(a, "/pane/{s}/ctl", .{s}), .data = "Tty\n" } }; + if (x < 0.25) return .{ .write = .{ .path = print(a, "/pane/{s}/ctl", .{s}), .data = "Term\n" } }; if (x < 0.45) return .{ .write = .{ .path = print(a, "/pane/{s}/pty/run", .{s}), .data = cat(a, &.{ line, "\n" }), .mode = ORDWR } }; if (x < 0.6) return .{ .write = .{ .path = print(a, "/pane/{s}/pty/data", .{s}), .data = cat(a, &.{ line, "\r" }) } }; if (x < 0.75) return .{ .write = .{ .path = print(a, "/pane/{s}/pty/ctl", .{s}), .data = pick(r, &[_][]const u8{ "sig INT\n", "sig TERM\n", "sig KILL\n", "sig HUP\n" }) } }; @@ -1603,7 +1603,7 @@ fn shrink(gpa: Allocator, seed: u64, f: Found, budget: usize) !void { const small = try ddmin(gpa, body, &trial, Trial.fails); var text: std.ArrayList(u8) = .empty; for (small, 0..) |n, i| try text.print(gpa, "{s}{d}", .{ if (i > 0) "," else "", n }); - std.debug.print(" shrunk {d} -> {d} ops: zig build monkey-session -Dplatform=tty -- --seed {d} --steps {d} --only {s} -v\n", .{ body.len, small.len, seed, f.step + 1, text.items }); + std.debug.print(" shrunk {d} -> {d} ops: zig build monkey-session -Dplatform=tui -- --seed {d} --steps {d} --only {s} -v\n", .{ body.len, small.len, seed, f.step + 1, text.items }); } fn usage() noreturn { diff --git a/test/output.zig b/test/output.zig index 876cd8fc..f484c3e6 100644 --- a/test/output.zig +++ b/test/output.zig @@ -578,7 +578,7 @@ test "EffectCode lists readable virtual sources used by this backend" { try std.testing.expect(out.content.len < 1024); try std.testing.expect(std.mem.indexOf(u8, out.content, "/virtual/src/layout.zig\n") != null); const backend_source = switch (platform) { - .tty => "/virtual/src/tty/panel_compositor.zig", + .tui => "/virtual/src/tui/panel_compositor.zig", .gui => "/virtual/shaders/ui.vert.glsl", .macos => "/virtual/src/macos/Sources/ScenePostprocessor.swift", .web, .esp32p4 => unreachable, diff --git a/test/pdf_scroll_bench.zig b/test/pdf_scroll_bench.zig index 0f93068d..f3d47b1e 100644 --- a/test/pdf_scroll_bench.zig +++ b/test/pdf_scroll_bench.zig @@ -21,7 +21,7 @@ //! the single render — not on one notch. Every timed region below is exactly //! that: `ticks_per_frame` real `Mouse.wheel_down`/`wheel_up` presses through //! `Pardes.update`, one `render()` into a reset frame arena, and the effect -//! drain, which is the loop src/tty/tty.zig and src/gui/gui.zig both run. +//! drain, which is the loop src/tui/tui.zig and src/gui/gui.zig both run. //! //! Rows are per-FRAME latency, not per-notch: a dropped frame is what a reader //! feels, and the batch is indivisible from the reader's point of view. @@ -60,7 +60,7 @@ const gpa = std.heap.smp_allocator; // A reading-sized window. Wide enough that fit-width pages are taller than the // viewport (so a fling genuinely crosses page boundaries) and small enough // that the Kitty raster policy's 1200px cap is the binding quality term, which -// is what the tty shell actually ships. +// is what the tui shell actually ships. const bench_cols: u16 = 120; const bench_rows: u16 = 40; const default_cell_pixels: pardes.CellPixels = .{ .w = 8, .h = 16 }; @@ -383,7 +383,7 @@ fn measure(config: Config, plan: Plan) !Result { total += elapsed; recorder.observe(frame, surface); peak_raster_bytes = @max(peak_raster_bytes, rasterBytes(pv)); - // The same frame boundary src/tty/tty.zig marks, so a Tracy capture + // The same frame boundary src/tui/tui.zig marks, so a Tracy capture // of this benchmark reads like a capture of the real shell. pardes.frameMark(); if (round >= config.warmup) { diff --git a/test/perf.zig b/test/perf.zig index 31a48cc7..31a813cb 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1319,7 +1319,7 @@ fn liveYes(l: *Live, exe: [:0]const u8) !void { var h = try eh.Harness.initArgv(gpa, exe, screen_rows, screen_cols, &.{ "-n", "1" }); errdefer h.dump("live yes"); // The prompt shows in tty mode only: the shell's tag, then Ctrl-b in. - if (!try h.waitFor("Tty+bash", 20_000)) return error.LiveNoPrompt; + if (!try h.waitFor("Term+bash", 20_000)) return error.LiveNoPrompt; try h.pump(500); try h.send("\x02"); if (!try h.waitFor("$ ", 20_000)) return error.LiveNoPrompt; @@ -1387,7 +1387,7 @@ fn measureLive(io: std.Io, exe: []const u8, gui: bool, reps: usize, json: bool) try liveOpen(&l, exe_z); liveSweep(io); } - const frontend = if (gui) "gui" else "tty"; + const frontend = if (gui) "gui" else "tui"; const out = std.Io.File.stdout(); var buf: [256]u8 = undefined; for (live_phases, &l.samples, &l.core) |name, *samples, *core| { diff --git a/test/process.zig b/test/process.zig index 21bc8e31..94dfd313 100644 --- a/test/process.zig +++ b/test/process.zig @@ -507,13 +507,13 @@ pub fn of(gpa: std.mem.Allocator, h: *const eh.Harness) Files { /// of the user's is reached. No daemon (PARDES_DAEMON=off, as the pty /// harness starts one): the process is the session, and nothing outlives it. /// Which build the process tests drive (`zig build process-test -/// -Dplatform=tty|gui`, the runner's --backend): a session's effects +/// -Dplatform=tui|gui`, the runner's --backend): a session's effects /// (saves, shells, watches, dumps) are its host's, so each case runs on the /// host it was built with. -pub const Backend = enum { tty, gui }; -pub var backend: Backend = .tty; +pub const Backend = enum { tui, gui }; +pub var backend: Backend = .tui; -/// A case about one frontend's own behaviour (`--tty`, a killed terminal +/// A case about one frontend's own behaviour (`--tui`, a killed terminal /// editor) skips on the other. pub fn only(b: Backend) !void { if (backend != b) return error.SkipZigTest; @@ -725,15 +725,15 @@ pub const Detached = struct { return std.fmt.allocPrintSentinel(d.files.arena.allocator(), "{s}/{s}", .{ d.root(), rel }, 0) catch @panic("out of memory"); } - /// Another session in this root, in a pty, as fs.py's tty sessions: - /// `pardes --tty --9p= /.txt` (holding + /// Another session in this root, in a pty, as fs.py's tui sessions: + /// `pardes --tui --9p= /.txt` (holding /// "initial\n"), back once its socket (`abs("pardes-9p-.sock")`) /// is there. - pub fn startTty(d: *Detached, exe: [:0]const u8, name: []const u8, args: []const [:0]const u8) !Child { + pub fn startTui(d: *Detached, exe: [:0]const u8, name: []const u8, args: []const [:0]const u8) !Child { const a = d.files.arena.allocator(); try d.put(try std.fmt.allocPrint(a, "{s}.txt", .{name}), "initial\n"); var argv: std.ArrayList([:0]const u8) = .empty; - try argv.appendSlice(a, &.{ exe, "--tty", try std.fmt.allocPrintSentinel(a, "--9p={s}", .{name}, 0) }); + try argv.appendSlice(a, &.{ exe, "--tui", try std.fmt.allocPrintSentinel(a, "--9p={s}", .{name}, 0) }); try argv.appendSlice(a, args); try argv.append(a, d.abs(try std.fmt.allocPrint(a, "{s}.txt", .{name}))); const env = try a.dupe([2][:0]const u8, &.{.{ "PARDES_DUMP", d.abs(try std.fmt.allocPrint(a, "{s}.dump.zon", .{name})) }}); diff --git a/test/process/builtins.zig b/test/process/builtins.zig index 410a3f54..0d8ef5d4 100644 --- a/test/process/builtins.zig +++ b/test/process/builtins.zig @@ -11,16 +11,16 @@ pub const cases = .{ }; fn lspinfo(gpa: std.mem.Allocator, exe: [:0]const u8) !void { - for ([_]bool{ false, true }) |tty| { + for ([_]bool{ false, true }) |tui| { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); - const name = if (tty) "lsp-tty" else "lsp-detached"; - var d = try process.Detached.start(gpa, exe, if (tty) "lsp-root" else name, .{}); + const name = if (tui) "lsp-tui" else "lsp-detached"; + var d = try process.Detached.start(gpa, exe, if (tui) "lsp-root" else name, .{}); defer d.deinit(); var term: ?process.Child = null; defer if (term) |*t| t.deinit(); - if (tty) term = try d.startTty(exe, name, &.{}); + if (tui) term = try d.startTui(exe, name, &.{}); const address = d.abs(try std.fmt.allocPrint(a, "pardes-9p-{s}.sock", .{name})); const c = try Conn.dial(gpa, address); defer c.deinit(gpa); diff --git a/test/process/flags.zig b/test/process/flags.zig index aa5b7497..78be22f6 100644 --- a/test/process/flags.zig +++ b/test/process/flags.zig @@ -169,7 +169,7 @@ fn forwarding(gpa: std.mem.Allocator, exe: [:0]const u8) !void { .{ "/virtual/pane/1/body:1:2-4", "initial\n", .{ 1, 4 }, true }, }) |row| { const before = try c.serials(a); - const r = try process.run(a, &.{ exe, "--tty", row[0] }, opts); + const r = try process.run(a, &.{ exe, "--tui", row[0] }, opts); try check(r.code == 0, "{s}: exit {d}: {s}", .{ row[0], r.code, r.said }); if (row[3]) { try check(same(before, try c.serials(a)), "{s} made a pane", .{row[0]}); @@ -213,14 +213,16 @@ fn forwarding(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // Flags of a session's own start one, never forwarded. const Launch = struct { []const u8, []const [:0]const u8, ?[]const u8 }; for ([_]Launch{ - .{ "mount", &.{ "--tty", z(a, "--mount=peer={s}", .{address}), "/n/peer/pane/1/body" }, null }, - .{ "name", &.{ "--tty", "--9p=forwarded-name" }, "forwarded-name" }, - .{ "tcp", &.{ "--tty", "--9p-tcp=tcp!127.0.0.1!0" }, null }, - .{ "load", &.{ "--tty", "-l", saved }, null }, + .{ "mount", &.{ "--tui", z(a, "--mount=peer={s}", .{address}), "/n/peer/pane/1/body" }, null }, + .{ "name", &.{ "--tui", "--9p=forwarded-name" }, "forwarded-name" }, + // --tty, the old spelling, which an upgraded session may pass. + .{ "old-flag", &.{ "--tty", "--9p=old-flag" }, "old-flag" }, + .{ "tcp", &.{ "--tui", "--9p-tcp=tcp!127.0.0.1!0" }, null }, + .{ "load", &.{ "--tui", "-l", saved }, null }, .{ "shells", &.{ "-n", "3" }, null }, - .{ "toggle", &.{ "--tty", "--tty-toggle=q" }, null }, - .{ "toggle-arg", &.{ "--tty", "--tty-toggle", "q" }, null }, - .{ "quic", &.{ "--tty", "--9p-quic=quic!127.0.0.1!0" }, null }, + .{ "toggle", &.{ "--tui", "--tty-toggle=q" }, null }, + .{ "toggle-arg", &.{ "--tui", "--tty-toggle", "q" }, null }, + .{ "quic", &.{ "--tui", "--9p-quic=quic!127.0.0.1!0" }, null }, }) |row| { if (std.mem.eql(u8, row[0], "quic") and !try process.quicIncluded(a, exe)) continue; var argv: [8][:0]const u8 = undefined; @@ -258,7 +260,7 @@ fn forwarding(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // A session that answers takes the file or says why, as acme's B does: // a pane it has not is its refusal and exit 1, never a nested editor. - const gone = try process.run(a, &.{ exe, "--tty", spaced }, .{ .root = d.root(), .env = &.{ inherited[0], .{ "PARDES_PANE", "4294967295" }, inherited[2] } }); + const gone = try process.run(a, &.{ exe, "--tui", spaced }, .{ .root = d.root(), .env = &.{ inherited[0], .{ "PARDES_PANE", "4294967295" }, inherited[2] } }); try check(gone.code == 1 and std.mem.startsWith(u8, gone.said, "pardes: "), "gone pane: exit {d}: {s}", .{ gone.code, gone.said }); try std.testing.expectEqualStrings(before, try c.read(a, "/index")); const absent = d.abs("absent.sock"); @@ -272,7 +274,7 @@ fn forwarding(gpa: std.mem.Allocator, exe: [:0]const u8) !void { .{ "not-nested", inherited[0..2], spaced }, }) |row| { const existing = try process.entries(a, d.root()); - var argv: [3][:0]const u8 = .{ exe, "--tty", undefined }; + var argv: [3][:0]const u8 = .{ exe, "--tui", undefined }; if (row[2]) |w| argv[2] = w; var child = try Child.spawn(argv[0..if (row[2] != null) 3 else 2], .{ .root = d.root(), .env = row[1], .pty = .{ .log = d.abs(try std.fmt.allocPrint(a, "{s}.pty", .{row[0]})) } }); defer child.deinit(); @@ -653,7 +655,7 @@ fn commandBody(a: std.mem.Allocator, c: *Conn, node: []const u8) ![]const u8 { fn outside(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // The terminal frontend's and a detached session's own: a window is neither. - try process.only(.tty); + try process.only(.tui); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); @@ -678,7 +680,7 @@ fn outside(gpa: std.mem.Allocator, exe: [:0]const u8) !void { } // A launch with no terminal to draw on (a pty that is no one's // controlling terminal) says so and exits 1, no error trace. - var tty = try Child.spawn(&.{ exe, "--tty", "x.txt" }, .{ .root = d.root(), .pty = .{ .log = d.abs("noctty.pty"), .ctty = false } }); + var tty = try Child.spawn(&.{ exe, "--tui", "x.txt" }, .{ .root = d.root(), .pty = .{ .log = d.abs("noctty.pty"), .ctty = false } }); defer tty.deinit(); const words = try tty.said(a); try exitsWith(&tty, 1, 10_000); @@ -699,7 +701,7 @@ fn socketFile(path: []const u8) !void { fn killedTty(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // The terminal frontend's and a detached session's own: a window is neither. - try process.only(.tty); + try process.only(.tui); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); @@ -718,7 +720,7 @@ fn killedTty(gpa: std.mem.Allocator, exe: [:0]const u8) !void { const existing = try process.entries(a, d.root()); const log = d.abs(try std.fmt.allocPrint(a, "killed-{t}.pty", .{sig})); // The daemon's, as a user's editor has: a hangup leaves the session. - var killed = try Child.spawn(&.{ exe, "--tty", "x.txt" }, .{ .root = d.root(), .env = &.{.{ "PARDES_DAEMON", "on" }}, .pty = .{ .log = log } }); + var killed = try Child.spawn(&.{ exe, "--tui", "x.txt" }, .{ .root = d.root(), .env = &.{.{ "PARDES_DAEMON", "on" }}, .pty = .{ .log = log } }); defer killed.deinit(); const deadline = process.nowMs() + 10_000; while (!has(d.get(a, std.fs.path.basename(log)) catch "", "\x1b[?1049h")) { @@ -763,7 +765,7 @@ fn daemonGone(d: *const process.Detached) void { fn signalCleansUp(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // The terminal frontend's and a detached session's own: a window is neither. - try process.only(.tty); + try process.only(.tui); // A detached session told to stop by a signal unlinks its sockets. A // hangup is a terminal's end, not a session's: the daemon keeps it. for ([_]libc.SIG{ .TERM, .INT, .HUP }) |first| { diff --git a/test/process/look_and_exec.zig b/test/process/look_and_exec.zig index 8ff01054..83836def 100644 --- a/test/process/look_and_exec.zig +++ b/test/process/look_and_exec.zig @@ -64,9 +64,9 @@ const Flow = struct { fn canary(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // shortcut: on the window, after its terminal steps, Newcol is refused - // (or a run hangs), where a fresh window takes it; tty alone until that + // (or a run hangs), where a fresh window takes it; tui alone until that // is found (docs/next-tests.md). - try process.only(.tty); + try process.only(.tui); const started = process.nowMs(); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -121,7 +121,7 @@ fn canary(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try std.testing.expectEqualStrings("from disk\n", try c.pane(a, pb, "body")); // A terminal: pty/run failing then passing. - const term = try f.madeBy(1, "Tty\n"); + const term = try f.madeBy(1, "Term\n"); { const deadline = process.nowMs() + 10_000; while (true) { diff --git a/test/process/mounts.zig b/test/process/mounts.zig index 10dc7b5a..f59a7a0f 100644 --- a/test/process/mounts.zig +++ b/test/process/mounts.zig @@ -129,7 +129,7 @@ fn quic(gpa: std.mem.Allocator, exe: [:0]const u8) !void { std.debug.print("SKIP a build without QUIC (-Dquic=true)\n", .{}); return; } - for ([_]bool{ false, true }) |tty| for ([_][:0]const u8{ "127.0.0.1", "::1" }) |host| { + for ([_]bool{ false, true }) |tui| for ([_][:0]const u8{ "127.0.0.1", "::1" }) |host| { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); @@ -137,11 +137,11 @@ fn quic(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try std.fmt.allocPrintSentinel(a, "--9p-tcp=tcp!{s}!0", .{host}, 0), try std.fmt.allocPrintSentinel(a, "--9p-quic=quic!{s}!0", .{host}, 0), }; - var d = try Detached.start(gpa, exe, if (tty) "quic-root" else "server", .{ .args = if (tty) &.{} else &args }); + var d = try Detached.start(gpa, exe, if (tui) "quic-root" else "server", .{ .args = if (tui) &.{} else &args }); defer d.deinit(); var term: ?process.Child = null; defer if (term) |*t| t.deinit(); - if (tty) term = try d.startTty(exe, "server", &args); + if (tui) term = try d.startTui(exe, "server", &args); const address = d.abs("pardes-9p-server.sock"); const unix = try Conn.dial(gpa, address); defer unix.deinit(gpa); diff --git a/test/process/repls.zig b/test/process/repls.zig index 09e25e96..a6fe07ac 100644 --- a/test/process/repls.zig +++ b/test/process/repls.zig @@ -35,7 +35,7 @@ fn pythonRepl(gpa: std.mem.Allocator, exe: [:0]const u8) !void { const c = try Conn.dial(gpa, d.socket()); defer c.deinit(gpa); const before = try c.serials(a); - try c.write("/pane/1/ctl", "Tty\n"); + try c.write("/pane/1/ctl", "Term\n"); const deadline = process.nowMs() + 10_000; var tty: u32 = 0; while (tty == 0 and process.nowMs() < deadline) : (process.nap(50)) { @@ -43,7 +43,7 @@ fn pythonRepl(gpa: std.mem.Allocator, exe: [:0]const u8) !void { tty = @max(tty, n); }; } - try check(tty != 0, "Tty made no pane", .{}); + try check(tty != 0, "Term made no pane", .{}); try check(try waitFor(a, c, tty, "$", 15_000) or try waitFor(a, c, tty, ">", 15_000), "no prompt: {s}", .{try c.pane(a, tty, "body")}); try c.write(try std.fmt.allocPrint(a, "/pane/{d}/pty/data", .{tty}), "python3 -q\r"); try check(try waitFor(a, c, tty, ">>>", 15_000), "no >>>: {s}", .{try c.pane(a, tty, "body")}); diff --git a/test/process/root_ctl.zig b/test/process/root_ctl.zig index 8ad92f7d..f4a0149b 100644 --- a/test/process/root_ctl.zig +++ b/test/process/root_ctl.zig @@ -28,7 +28,7 @@ fn exitAnswers(gpa: std.mem.Allocator, exe: [:0]const u8) !void { /// Nothing attached, no key, no click, no other request comes to move it along. fn messagesExpire(gpa: std.mem.Allocator, exe: [:0]const u8) !void { // With nothing attached: a window always is. - try process.only(.tty); + try process.only(.tui); var d = try process.Detached.start(gpa, exe, "msg", .{}); defer d.deinit(); try d.files.write("/pane/1/ctl", "Msg lingering-words\n"); @@ -118,16 +118,16 @@ fn redial(gpa: std.mem.Allocator, path: []const u8) !*Conn { } fn restore(gpa: std.mem.Allocator, exe: [:0]const u8) !void { - for ([_]bool{ false, true }) |tty| { + for ([_]bool{ false, true }) |tui| { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); - const name = if (tty) "restore tty space" else "restore detached space"; - var d = try process.Detached.start(gpa, exe, if (tty) "restore-root" else name, .{}); + const name = if (tui) "restore tui space" else "restore detached space"; + var d = try process.Detached.start(gpa, exe, if (tui) "restore-root" else name, .{}); defer d.deinit(); var term: ?process.Child = null; defer if (term) |*t| t.deinit(); - if (tty) term = try d.startTty(exe, name, &.{}); + if (tui) term = try d.startTui(exe, name, &.{}); const address = d.abs(try std.fmt.allocPrint(a, "pardes-9p-{s}.sock", .{name})); const old = try Conn.dial(gpa, address); defer old.deinit(gpa); @@ -179,7 +179,7 @@ fn restore(gpa: std.mem.Allocator, exe: [:0]const u8) !void { defer screen.deinit(); const width = try std.unicode.utf8CountCodepoints(std.mem.sliceTo(try screen.screen(), '\n')); // A detached one is 160x50; a window keeps its own size. - if (process.backend == .tty) try std.testing.expectEqual(@as(usize, if (tty) 80 else 160), width); + if (process.backend == .tui) try std.testing.expectEqual(@as(usize, if (tui) 80 else 160), width); const opened = try restored.look(a, try std.fmt.allocPrint(a, "/n/own/os{s}", .{d.abs(try std.fmt.allocPrint(a, "{s}.txt", .{name}))}), ids[1]); try std.testing.expectEqualStrings("initial\n", try restored.pane(a, opened, "body")); } diff --git a/test/process/terminals.zig b/test/process/terminals.zig index e7e93a4f..96804adf 100644 --- a/test/process/terminals.zig +++ b/test/process/terminals.zig @@ -79,9 +79,9 @@ const Other = struct { }; fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void { - // shortcut: on the window a fresh Tty's first pty/run sometimes never - // answers (4 runs of 6); tty alone until that is found (docs/next-tests.md). - try process.only(.tty); + // shortcut: on the window a fresh Term's first pty/run sometimes never + // answers (4 runs of 6); tui alone until that is found (docs/next-tests.md). + try process.only(.tui); var d = try process.Detached.start(gpa, exe, "run", .{}); defer d.deinit(); const f = &d.files; @@ -97,12 +97,12 @@ fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try c.write(f.at("/pane/{d}/name", .{peer}), "/n/nosuchpeer/d/f.txt\n"); const count = std.mem.count(u8, try c.read(a, "/index"), "\n"); try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "ls\n", "no such directory"); - try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "Tty\n", "no such directory"); + try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "Term\n", "no such directory"); try expectEqual(count, std.mem.count(u8, try c.read(a, "/index"), "\n")); try expect(!has(try c.read(a, "/log"), "exit 127")); try c.remove(f.at("/pane/{d}", .{peer})); try c.write("/exec", "Shell bash\n"); - try c.write("/exec", "Tty\n"); + try c.write("/exec", "Term\n"); var term: u32 = 0; var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n'); while (rows.next()) |r| { @@ -222,8 +222,8 @@ fn namedOnce(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var made: std.ArrayList(u32) = .empty; try made.append(a, try c.look(a, f.at("{s}/sub", .{root}), null)); const before = try serials(a, c); - try c.write("/pane/1/ctl", "Tty\n"); - if (shell(a, "command -v fish >/dev/null", .{}) == 0) try c.write("/pane/1/ctl", "Tty fish\n"); + try c.write("/pane/1/ctl", "Term\n"); + if (shell(a, "command -v fish >/dev/null", .{}) == 0) try c.write("/pane/1/ctl", "Term fish\n"); for (try serials(a, c)) |s| if (std.mem.indexOfScalar(u32, before, s) == null) try made.append(a, s); try expect(made.items.len >= 2); process.sleep(1500); // their shells start and say where they are @@ -235,14 +235,14 @@ fn namedOnce(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try expect(!has(log, f.at("\nrename {d} ", .{s}))); try expect(has(log, f.at("\nnew {d} {s}", .{ s, root }))); } - // A shell that cannot start (its interpreter is not there): Tty fails + // A shell that cannot start (its interpreter is not there): Term fails // the write with why and leaves no pane; pty/ctl exec fails with why // and keeps its terminal. try d.put("badsh", "#!/nonexistent/interp\n"); const bad = f.at("{s}/badsh", .{root}); _ = libc.chmod(try std.fmt.allocPrintSentinel(a, "{s}", .{bad}, 0), 0o755); const panes = std.mem.count(u8, try c.read(a, "/index"), "\n"); - try refusedSaying(c, "/pane/1/ctl", f.at("Tty {s}\n", .{bad}), "interpreter /nonexistent/interp not found"); + try refusedSaying(c, "/pane/1/ctl", f.at("Term {s}\n", .{bad}), "interpreter /nonexistent/interp not found"); try refusedSaying(c, "/ctl", f.at("Shell {s}\n", .{bad}), "interpreter /nonexistent/interp not found"); process.sleep(300); try expectEqual(panes, std.mem.count(u8, try c.read(a, "/index"), "\n")); @@ -275,7 +275,7 @@ fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8 const f = &d.files; try d.put("command.sh", f.at("exec /bin/sh -c '{s}'\n", .{script})); try f.write("/ctl", "Shell /bin/sh\n"); - try f.write("/exec", "Tty\n"); + try f.write("/exec", "Term\n"); const term = try f.focused(); const body = f.at("/pane/{d}/body", .{term}); const data = f.at("/pane/{d}/pty/data", .{term}); diff --git a/test/process/tree.zig b/test/process/tree.zig index ee39170b..27b51bf1 100644 --- a/test/process/tree.zig +++ b/test/process/tree.zig @@ -482,7 +482,7 @@ fn cutWrites(gpa: std.mem.Allocator, exe: [:0]const u8) !void { try expectEqual(@as(usize, 2500), k); // A detached session with no frontend is 160x50 until told; a // window's size is its own, and refuses size. - if (process.backend == .tty) { + if (process.backend == .tui) { const cols, const rows = try screenSize(f); try expect(cols == 160 and rows == 50); try c.write("/ctl", "size 132 40\n"); diff --git a/test/process_test.zig b/test/process_test.zig index a870f13a..67f28f53 100644 --- a/test/process_test.zig +++ b/test/process_test.zig @@ -21,7 +21,7 @@ const files = .{ pub fn main(init: std.process.Init) !void { const all = try init.minimal.args.toSlice(init.arena.allocator()); - // [--backend=tty|gui] [filter] + // [--backend=tui|gui] [filter] var args: [3][:0]const u8 = undefined; var n: usize = 0; for (all[1..]) |a| { diff --git a/test/record_casts.py b/test/record_casts.py index 13893517..15f46ced 100644 --- a/test/record_casts.py +++ b/test/record_casts.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Record the documentation site's terminal casts (asciicast v2). -zig build -Dplatform=tty -Doptimize=ReleaseSafe --prefix +zig build -Dplatform=tui -Doptimize=ReleaseSafe --prefix python3 -B test/record_casts.py /bin/pardes [cast ...] [--show] Each cast runs the tty pardes in a pty this script owns, sized 100x30 with @@ -770,8 +770,8 @@ def terminals(r): """A shell beside the notes: run, Ctrl-b, copy a line of output into the file; then git log paged through pardes - into a +Pager.""" r.step(None, until=lambda s: 'What ./hello prints' in s.text(), quiet=.4, hold=1.2) - start, end = word_at(r, 'Tty', 2) - r.sweep(1, start, end, show=.5, hold=.6, until=lambda s: 'Tty+sh' in s.text(), what='the shell') + start, end = word_at(r, 'Term', 2) + r.sweep(1, start, end, show=.5, hold=.6, until=lambda s: 'Term+sh' in s.text(), what='the shell') r.step(None, until=lambda s: s.text().count('$') >= 2, hold=.4) # Its own column, beside the file: Ctrl-b to normal, Alt-c, Ctrl-b back. r.step('\x02', hold=.3) @@ -909,7 +909,7 @@ def show(name, work, at=None): def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('binary', type=Path, nargs='?', help='a pardes built with -Dplatform=tty') + parser.add_argument('binary', type=Path, nargs='?', help='a pardes built with -Dplatform=tui') parser.add_argument('casts', nargs='*', help='which casts (default: all): ' + ', '.join(CASTS)) parser.add_argument('--work', type=Path, default=REPO.parent / '.scratch/casts/work', help='the session home, step logs and check pictures (default %(default)s)') diff --git a/test/record_demos.py b/test/record_demos.py index a2e48d73..4468ffb6 100644 --- a/test/record_demos.py +++ b/test/record_demos.py @@ -220,7 +220,7 @@ class Session: def terminal_rows(self): """The screen's rows below the (one) terminal's tag.""" rows = self.screen() - return rows[next(i for i, line in enumerate(rows) if 'Tty+sh' in line) + 1:] + return rows[next(i for i, line in enumerate(rows) if 'Term+sh' in line) + 1:] def wait(self, predicate, what, seconds=20): deadline = time.monotonic() + seconds @@ -594,7 +594,7 @@ def text_is_the_interface(s): def shell_setup(s): """A terminal under the file, at the project, with a short prompt.""" - s.write('/pane/1/exec', 'Tty\n') + s.write('/pane/1/exec', 'Term\n') s.wait(lambda: 2 in s.panes(), 'the terminal') s.write('/pane/2/pty/data', f"cd {PROJECT}; PS1='$ '; clear\r") s.wait(lambda: any(line.rstrip() == ' $' for line in s.screen()), 'the prompt') @@ -844,7 +844,7 @@ def theme_scene(s): subprocess.run(['git', '-C', str(PROJECT), *args], check=True, env=env, capture_output=True) main = PROJECT / 'src/main.c' main.write_text(main.read_text().replace('i <= 4', 'i <= 5')) - s.write('/pane/1/exec', 'Tty\n') + s.write('/pane/1/exec', 'Term\n') s.wait(lambda: 2 in s.panes(), 'the terminal') s.write('/pane/2/pty/data', f"cd {PROJECT}; PS1='$ '; clear; make; git diff\r") s.wait(lambda: len(s.panes()) == 3, 'the pager') diff --git a/test/replicas.zig b/test/replicas.zig index 18060763..4fcb9920 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -12,8 +12,8 @@ //! the authority steps, each replica acknowledging them over its link and //! asking for the rows it scrolls back into and does not hold. //! -//! zig build replicas -Dplatform=tty -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] [--shared] -//! zig build replicas -Dplatform=tty -- --echo [--seeds N] [--rtt 30,80,207] [--first K] +//! zig build replicas -Dplatform=tui -- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207] [--first K] [--flood MB] [--shared] +//! zig build replicas -Dplatform=tui -- --echo [--seeds N] [--rtt 30,80,207] [--first K] //! //! `--echo` types a corpus into a shell instead, with and without the //! predicted echo (src/echo.zig), and gates what it draws: below, at diff --git a/test/rollback_bench.zig b/test/rollback_bench.zig index 0f0c77a4..659a73d3 100644 --- a/test/rollback_bench.zig +++ b/test/rollback_bench.zig @@ -9,7 +9,7 @@ //! Then a fork of the big one, child gone at once, and the authority's //! copy-on-write after it. //! -//! zig build rollback-bench -Dplatform=tty -Doptimize=ReleaseFast +//! zig build rollback-bench -Dplatform=tui -Doptimize=ReleaseFast const std = @import("std"); const libc = std.c; const pardes = @import("pardes"); diff --git a/test/selfmount.py b/test/selfmount.py index 61d32523..1df17226 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -37,7 +37,7 @@ def unix_mount(ns, binary, served, env, name, fixture): env = dict(env, PARDES_DUMP=f'/tmp/{second}.dump.zon') pid, master = pty.fork() if pid == 0: - os.execve(ns, ['9ns', '--unix', served, '--', binary, '--tty', '--9p=' + second, str(fixture)], env) + os.execve(ns, ['9ns', '--unix', served, '--', binary, '--tui', '--9p=' + second, str(fixture)], env) fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0)) os.set_blocking(master, False) try: @@ -83,7 +83,7 @@ def run(binary): env['PARDES_LSP_' + language] = '' pid, master = pty.fork() if pid == 0: - os.execve(ns, ['9ns', '--mntgen', '--', binary, '--tty', '--9p=' + name, str(fixture)], env) + os.execve(ns, ['9ns', '--mntgen', '--', binary, '--tui', '--9p=' + name, str(fixture)], env) fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0)) os.set_blocking(master, False) tail = bytearray() @@ -276,7 +276,7 @@ def run(binary): other_env = dict(env, PARDES_DUMP=f'/tmp/{other}.dump.zon') other_pid, other_master = pty.fork() if other_pid == 0: - os.execve(binary, [binary, '--tty', '--9p=' + other], other_env) + os.execve(binary, [binary, '--tui', '--9p=' + other], other_env) os.set_blocking(other_master, False) deadline = time.monotonic() + 15 while not os.path.exists(other_sock) and time.monotonic() < deadline: diff --git a/test/snapshot.zig b/test/snapshot.zig index 95d07cc7..00585018 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -1132,7 +1132,7 @@ fn readProc(buf: []u8, path: [*:0]const u8) ?[]const u8 { /// What a capture is made of: grid text, cursor cell, and a compact digest of /// every cell style. Style used not to matter to `stable`, which let a -/// color-only animation look idle while the TTY frontend was deliberately +/// color-only animation look idle while the TUI frontend was deliberately /// asleep between frames; a following `snapstyle` then caught a midpoint. fn stateKey(h: *eh.Harness) ![]u8 { const text = try h.screenText(); @@ -1455,7 +1455,7 @@ fn styleRows(arena: std.mem.Allocator, h: *eh.Harness) ![]const []const u8 { var run_len: usize = 0; var run_start: u16 = 0; // A blank's ink shows nowhere, and the tty leaves whatever ink the - // terminal had there (tty.zig blankInk), so it depends on the frames + // terminal had there (tui.zig blankInk), so it depends on the frames // before: a blank is written with the ink of the cell before it. var ink_buf: [16]u8 = undefined; var ink: []const u8 = "d"; diff --git a/test/snapshots/images.snap b/test/snapshots/images.snap index caed1fa1..d5dc580d 100644 --- a/test/snapshots/images.snap +++ b/test/snapshots/images.snap @@ -1,6 +1,6 @@ # image panes: right-click a .ppm opens petscii glyph art (no kitty in the # harness). The tag starts with the renderer's plain state fields followed by -# its path and `Tty Del`; the fields are display-only, while their toggles are +# its path and `Term Del`; the fields are display-only, while their toggles are # builtins under SPC t (the old clickable tag words sat past the pane's right # edge, so clicking them only ever hit the neighbouring shell's tag). ppmdiag pic.ppm @@ -41,12 +41,12 @@ snap no-ascii # prefix is wider than this source-local column, so widen the grid for this # final assertion. (A column-border drag intentionally takes width from only # one neighbour, which cannot expose this 82-column prefix.) Then click the -# visible tail itself, at its `Tty`. This proves the image tag is an ordinary +# visible tail itself, at its `Term`. This proves the image tag is an ordinary # editor rather than accidentally typing at a clipped read-only path. resize 31 400 stable 400 5000 -press left @Tty 7 -release left @Tty 7 +press left @Term 7 +release left @Term 7 stable 400 5000 key i send Zork\x20 diff --git a/test/snapshots/look-fd-deep.snap b/test/snapshots/look-fd-deep.snap index 8df0aaaf..d9e5ac06 100644 --- a/test/snapshots/look-fd-deep.snap +++ b/test/snapshots/look-fd-deep.snap @@ -18,7 +18,7 @@ stable 700 20000 text cd a && ls && fd key enter wait 8000 c.txt -wait 8000 cwd/a Tty +wait 8000 cwd/a Term stable 700 20000 snap listed press right 6 8 diff --git a/test/snapshots/look-file-1col.snap b/test/snapshots/look-file-1col.snap index 490aaf38..1b23e054 100644 --- a/test/snapshots/look-file-1col.snap +++ b/test/snapshots/look-file-1col.snap @@ -1,5 +1,5 @@ # single narrow column (-n 1): the first document splits below its source -# shell, like Tty. A new column would require at least 200 cells of width. +# shell, like Term. A new column would require at least 200 cells of width. lines big.txt 60 start 31 100 -n 1 wait 8000 big.txt diff --git a/test/snapshots/ttyclick.snap b/test/snapshots/ttyclick.snap index 65b6f9fc..534005b9 100644 --- a/test/snapshots/ttyclick.snap +++ b/test/snapshots/ttyclick.snap @@ -18,8 +18,8 @@ snap tty-bodyclick # tag edit from tty: the box still reads `$` while the tag is typed into (the # tag's mode is its own: a clicked tag is in normal mode), and `:` hands the keyboard back — a bug # that lost the body's mode would show `•` in one snap or the other -press left @Tty 3 -release left @Tty 3 +press left @Term 3 +release left @Term 3 stable 400 5000 snap tty-tagedit key : diff --git a/test/snapshots/ttyonly.snap b/test/snapshots/ttyonly.snap index 1008e084..0c2d8738 100644 --- a/test/snapshots/ttyonly.snap +++ b/test/snapshots/ttyonly.snap @@ -1,6 +1,6 @@ -# --tty: a single fullscreen shell already in raw tty mode, prompts visible +# --tui: a single fullscreen shell already in raw tty mode, prompts visible file t.txt x -start 31 100 --tty +start 31 100 --tui wait 8000 $ stable 700 20000 text echo TTY''ONLY diff --git a/test/soak.py b/test/soak.py index e3ff18c7..99f43cc9 100644 --- a/test/soak.py +++ b/test/soak.py @@ -935,7 +935,7 @@ class Run: self.safe_tags() # Two shells beside the directory, as the user's had. for _ in range(self.shells): - self.nine_write('/pane/1/exec', b'Tty\n') + self.nine_write('/pane/1/exec', b'Term\n') time.sleep(0.5) def session_alive(self): @@ -1027,7 +1027,7 @@ class BoxRun(Run): self.session_pid = int(dict(line.split(maxsplit=1) for line in status.splitlines())['pid']) self.safe_tags() for _ in range(self.shells): - self.nine_write('/pane/1/exec', b'Tty\n') + self.nine_write('/pane/1/exec', b'Term\n') time.sleep(1) def session_alive(self): @@ -1633,7 +1633,7 @@ def local_session(run, kind): run.nine = None wait_for(f'{name}\'s 9P', run.nine_sock.exists, timeout=30) wait_for(f'{name}\'s first frame', c.ready, timeout=30) - run.nine_write('/pane/1/exec', b'Tty\n') + run.nine_write('/pane/1/exec', b'Term\n') time.sleep(1) run.instant_panes = instant_panes(run) run.nine_write(f'/pane/{run.instant_panes[1]}/body', b'seq 1 3000\n') diff --git a/test/tag_cleanup.py b/test/tag_cleanup.py index ae0a0e66..80bdb4b0 100644 --- a/test/tag_cleanup.py +++ b/test/tag_cleanup.py @@ -30,11 +30,11 @@ def run(args): pdf = next(serial for serial, tag in panes(client).items() if str(source) in tag) pdf_tag = client.read(f'/pane/{pdf}/tag').decode().strip() require(pdf_tag.startswith(str(source) + ' [1/'), 'PDF name/page prefix missing') - require(pdf_tag.endswith('] Tty Del PdfSections PdfTint Collapse'), 'PDF commands missing') + require(pdf_tag.endswith('] Term Del PdfSections PdfTint Collapse'), 'PDF commands missing') require(all(word not in pdf_tag for word in ['PdfFit', 'filtered', 'full', 'disabled']), 'PDF tag contains fit or tint-state clutter') control = new_pane(client, b'') before = set(panes(client)) - execute(client, control, 'Tty') + execute(client, control, 'Term') tty = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'terminal missing') client.write(f'/pane/{control}/exec', b'Del\n') # owned command-only scratch diff --git a/test/ui_review.py b/test/ui_review.py index a1cdcdeb..3232c519 100644 --- a/test/ui_review.py +++ b/test/ui_review.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Capture a read-only Agave review in an isolated SDL or TTY session. +"""Capture a read-only Agave review in an isolated SDL or TUI session. python3 test/ui_review.py zig-out/bin/pardes-gui /tmp/pardes-review \\ --project /path/to/agave --theme orchard @@ -36,7 +36,7 @@ def command(client, serial, text): """Execute a temporary tag command without changing source contents.""" tag = f'/pane/{serial}/tag' before = client.read(tag).rstrip(b'\n') - tail_start = before.index(b'Save Tty Del') + tail_start = before.index(b'Save Term Del') while tail_start and before[tail_start - 1:tail_start] == b' ': tail_start -= 1 client.write(tag, b' ' + text.encode()) @@ -120,10 +120,10 @@ def run(args): if grep_pane: (root / 'grep-results.txt').write_bytes(client.read(f'/pane/{grep_pane}/body')) capture(client, root, '03-grep', not args.tty) - command(client, source, 'Tty') + command(client, source, 'Term') terminal = require(wait_for(lambda: next((serial for serial in panes(client) if 'pty' in client.list(f'/pane/{serial}')), None)), - 'Tty did not create a terminal') + 'Term did not create a terminal') if terminal: client.write(f'/pane/{terminal}/pty/data', b"printf '\\033[1;36mAgave workspace\\033[0m\\n'; pwd; printf '\\033[32mRead-only UI review ready\\033[0m\\n'\r") require(wait_for(lambda: b'\nRead-only UI review ready\n' in diff --git a/test/window_opacity.py b/test/window_opacity.py index 0253e15c..2664ff8c 100644 --- a/test/window_opacity.py +++ b/test/window_opacity.py @@ -46,7 +46,7 @@ def run(args): source = require(wait_for(lambda: next((serial for serial, tag in panes(client).items() if str(source_path) in tag), None)), 'source missing') before = set(panes(client)) - command(client, source, 'Tty') + command(client, source, 'Term') terminal = require(wait_for(lambda: next((serial for serial in panes(client) if serial not in before), None)), 'terminal missing') client.write(f'/pane/{terminal}/pty/data', diff --git a/test/yazi_preview.py b/test/yazi_preview.py index 7fa02aa6..4c64b2a7 100644 --- a/test/yazi_preview.py +++ b/test/yazi_preview.py @@ -105,7 +105,7 @@ def run(args): with session('/bin/sh', root, name, socket_name=name, tty=True, launch=launch, inherited=inherited) as (client, _): scratch = new_pane(client, b'') before = panes(client) - execute(client, scratch, 'Tty') + execute(client, scratch, 'Term') term = require(wait_for(lambda: next((s for s in panes(client) if s not in before and 'pty' in client.list(f'/pane/{s}')), None)), 'no terminal') client.remove(f'/pane/{scratch}') diff --git a/tools/gen_builtins_json.zig b/tools/gen_builtins_json.zig index 71df5307..3158c8b2 100644 --- a/tools/gen_builtins_json.zig +++ b/tools/gen_builtins_json.zig @@ -1,4 +1,4 @@ -//! Writes every builtin as JSON to the path given (docs/typ/builtins-.json, +//! Writes every builtin as JSON to the path given (docs/typ/builtins-.json, //! by way of `zig build builtins-json`). const std = @import("std"); const pardes = @import("pardes"); diff --git a/tools/shared_libs_check.zig b/tools/shared_libs_check.zig index 7b3174e4..d475f631 100644 --- a/tools/shared_libs_check.zig +++ b/tools/shared_libs_check.zig @@ -1,6 +1,6 @@ //! One copy of each codec in a pardes binary (docs/shared-libs.md). //! -//! zig build shared-libs-check -Dplatform=tty|gui +//! zig build shared-libs-check -Dplatform=tui|gui //! //! Reads the linked executable's ELF symbol table and fails when a family of //! symbols the build has chosen against is in it: a second PNG, JPEG or -- cgit v1.3