From f9a3179542012ec1a700e2020ac9f616b819f972 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 21:23:22 -0300 Subject: dev: the frontends (dev/tui, dev/gui, the macOS app's Swift and resources in dev/macos), host_io, file_watch, fonts, the lsp client and Scip, Art, jump_trail, glide and vaxis_input into dev/ (the reorganisation's tree, step 2b): module `dev` (dev/root.zig) beside the core and the runtime, each naming the others; the window wired into it, sketchbook's devices imported as `sketchbook` (its `dev` would be ours); pardes.zig keeps its re-exports (host_io, file_watch, glide, fonts) so every caller reads as before; core-test and shell-test run the devices' test program too, so the same tests run (the ledger, tui and gui); nothing else changes: frames byte-identical, replicas and process-test the base's Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- build.zig | 4 +- build/core.zig | 17 +- build/gui.zig | 14 +- build/macos.zig | 18 +- build/tests.zig | 16 +- dev/Art.zig | 591 ++ dev/file_watch.zig | 963 ++++ dev/fonts.zig | 436 ++ dev/glide.zig | 466 ++ dev/gui/Trackpad.zig | 142 + dev/gui/deck.zig | 204 + dev/gui/gui.zig | 8319 ++++++++++++++++++++++++++++ dev/gui/macos_trackpad.h | 21 + dev/gui/macos_trackpad.m | 176 + dev/gui/pet.zig | 215 + dev/host_io.zig | 4007 ++++++++++++++ dev/jump_trail.zig | 87 + dev/lsp/Scip.zig | 357 ++ dev/lsp/lsp_client.zig | 3183 +++++++++++ dev/macos/Info.plist | 76 + dev/macos/Sources/AppDelegate.swift | 704 +++ dev/macos/Sources/FileWatcher.swift | 122 + dev/macos/Sources/PardesView.swift | 2728 +++++++++ dev/macos/Sources/ScenePostprocessor.swift | 321 ++ dev/macos/Sources/main.swift | 16 + dev/macos/icon.png | Bin 0 -> 1788282 bytes dev/macos/icon.swift | 194 + dev/root.zig | 34 + dev/tui/tui.zig | 3386 +++++++++++ dev/vaxis_input.zig | 147 + runtime/9p_io.zig | 44 +- runtime/macos.zig | 6 +- runtime/main.zig | 21 +- runtime/root.zig | 2 +- src/Art.zig | 591 -- src/Core.zig | 2 +- src/Effect.zig | 2 +- src/Handover.zig | 2 +- src/Kind.zig | 2 +- src/Output.zig | 2 +- src/Stream.zig | 2 +- src/builtins.zig | 2 +- src/edit_cmd.zig | 2 +- src/exec.zig | 2 +- src/file_watch.zig | 963 ---- src/fonts.zig | 436 -- src/fs.zig | 4 +- src/glide.zig | 466 -- src/gui/Trackpad.zig | 142 - src/gui/deck.zig | 204 - src/gui/gui.zig | 8319 ---------------------------- src/gui/macos_trackpad.h | 21 - src/gui/macos_trackpad.m | 176 - src/gui/pet.zig | 215 - src/host_io.zig | 4007 -------------- src/jump_trail.zig | 87 - src/look.zig | 2 +- src/lsp/Scip.zig | 357 -- src/lsp/lsp.zig | 2 +- src/lsp/lsp_client.zig | 3183 ----------- src/macos/Info.plist | 76 - src/macos/Sources/AppDelegate.swift | 704 --- src/macos/Sources/FileWatcher.swift | 122 - src/macos/Sources/PardesView.swift | 2728 --------- src/macos/Sources/ScenePostprocessor.swift | 321 -- src/macos/Sources/main.swift | 16 - src/macos/icon.png | Bin 1788282 -> 0 bytes src/macos/icon.swift | 194 - src/ninep/pty.zig | 2 +- src/pardes.zig | 24 +- src/tape.zig | 2 +- src/tui/tui.zig | 3386 ----------- src/vaxis_input.zig | 147 - test/macos_trackpad.m | 2 +- 74 files changed, 26992 insertions(+), 26962 deletions(-) create mode 100644 dev/Art.zig create mode 100644 dev/file_watch.zig create mode 100644 dev/fonts.zig create mode 100644 dev/glide.zig create mode 100644 dev/gui/Trackpad.zig create mode 100644 dev/gui/deck.zig create mode 100644 dev/gui/gui.zig create mode 100644 dev/gui/macos_trackpad.h create mode 100644 dev/gui/macos_trackpad.m create mode 100644 dev/gui/pet.zig create mode 100644 dev/host_io.zig create mode 100644 dev/jump_trail.zig create mode 100644 dev/lsp/Scip.zig create mode 100644 dev/lsp/lsp_client.zig create mode 100644 dev/macos/Info.plist create mode 100644 dev/macos/Sources/AppDelegate.swift create mode 100644 dev/macos/Sources/FileWatcher.swift create mode 100644 dev/macos/Sources/PardesView.swift create mode 100644 dev/macos/Sources/ScenePostprocessor.swift create mode 100644 dev/macos/Sources/main.swift create mode 100644 dev/macos/icon.png create mode 100644 dev/macos/icon.swift create mode 100644 dev/root.zig create mode 100644 dev/tui/tui.zig create mode 100644 dev/vaxis_input.zig delete mode 100644 src/Art.zig delete mode 100644 src/file_watch.zig delete mode 100644 src/fonts.zig delete mode 100644 src/glide.zig delete mode 100644 src/gui/Trackpad.zig delete mode 100644 src/gui/deck.zig delete mode 100644 src/gui/gui.zig delete mode 100644 src/gui/macos_trackpad.h delete mode 100644 src/gui/macos_trackpad.m delete mode 100644 src/gui/pet.zig delete mode 100644 src/host_io.zig delete mode 100644 src/jump_trail.zig delete mode 100644 src/lsp/Scip.zig delete mode 100644 src/lsp/lsp_client.zig delete mode 100644 src/macos/Info.plist delete mode 100644 src/macos/Sources/AppDelegate.swift delete mode 100644 src/macos/Sources/FileWatcher.swift delete mode 100644 src/macos/Sources/PardesView.swift delete mode 100644 src/macos/Sources/ScenePostprocessor.swift delete mode 100644 src/macos/Sources/main.swift delete mode 100644 src/macos/icon.png delete mode 100644 src/macos/icon.swift delete mode 100644 src/tui/tui.zig delete mode 100644 src/vaxis_input.zig diff --git a/build.zig b/build.zig index dbc7e3ba..fca7afe3 100644 --- a/build.zig +++ b/build.zig @@ -209,8 +209,8 @@ pub fn build(b: *std.Build) void { var sketchbook: ?*std.Build.Dependency = null; if (also_gui or platform == .gui) { const window = gui.make(b, target, optimize, macos_sdk, prebuilt_shaders, a.freetype); - // ...into the core, whose gui/gui.zig names the window. - for ([_]?core.Modules{ gui_set, if (platform == .gui) root_set else null, if (platform == .gui) static_set else null }) |m| if (m) |s| window.wire(s.core); + // ...into the devices, whose gui/gui.zig names the window. + for ([_]?core.Modules{ gui_set, if (platform == .gui) root_set else null, if (platform == .gui) static_set else null }) |m| if (m) |s| window.wire(s.dev); sketchbook = window.sketchbook; } const snake_shader_lib = addons.gpu(b, target, optimize, a.addon_mod, sketchbook); diff --git a/build/core.zig b/build/core.zig index 8749d612..56a047c0 100644 --- a/build/core.zig +++ b/build/core.zig @@ -318,18 +318,19 @@ pub const Core = struct { util: bool = false, }; -/// What `module` makes: the core and the runtime, each naming the other -/// (`core`, `runtime`), and the module a compile roots at. +/// What `module` makes: the core, the devices and the runtime, each naming +/// the others (`core`, `dev`, `runtime`), and the module a compile roots at. pub const Modules = struct { /// A product's own file (runtime/main.zig, runtime/macos.zig) naming /// both, the runtime, or the core. root: *std.Build.Module, core: *std.Build.Module, + dev: *std.Build.Module, runtime: *std.Build.Module, }; -/// A core and the runtime beside it, everything they import and link -/// named here and nowhere else. +/// A core and the devices and runtime beside it, everything they import +/// and link named here and nowhere else. pub fn module(b: *std.Build, p: Parts, c: Core) Modules { const in_runtime = std.mem.startsWith(u8, c.root, "runtime/"); const m = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(if (in_runtime) "src/pardes.zig" else c.root), .link_libc = true }); @@ -356,9 +357,10 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { for (p.ts.libs.items) |lib| m.linkLibrary(lib); // The /src tree's files that live outside the core's directory // (fs.zig embeds them under the names they had there). - if (p.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig" }) |f| + if (p.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig", "dev/host_io.zig" }) |f| m.addAnonymousImport(f, .{ .root_source_file = b.path(f) }); const runtime = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("runtime/root.zig"), .link_libc = true }); + const dev = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("dev/root.zig"), .link_libc = true }); const root = if (!in_runtime) m else if (std.mem.eql(u8, c.root, "runtime/root.zig")) runtime else b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true }); // Each options module once, so that the modules share it: a file is in // one module of a compilation. @@ -368,7 +370,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { const pardes_config = c.config.createModule(); const pardes_isolation = (if (c.isolated) p.iso_on else p.iso_off).createModule(); const builtin_addons = (if (c.builtin_addons) p.builtin_on else p.builtin_off).createModule(); - for ([_]*std.Build.Module{ m, runtime, root }) |x| { + for ([_]*std.Build.Module{ m, dev, runtime, root }) |x| { x.addImport("cloud9", p.cloud9); if (c.builtin_addons) if (p.pdf) |pdf| x.addImport("pdf_addon", pdf); if (c.builtin_addons) x.addImport("image_addon", p.image); @@ -390,9 +392,10 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { x.addImport("pardes_isolation", pardes_isolation); x.addImport("builtin_addons", builtin_addons); x.addImport("core", m); + x.addImport("dev", dev); x.addImport("runtime", runtime); } - return .{ .root = root, .core = m, .runtime = runtime }; + return .{ .root = root, .core = m, .dev = dev, .runtime = runtime }; } /// What `assemble` makes besides the parts: the shells' options, the diff --git a/build/gui.zig b/build/gui.zig index cc90bd0a..bec26c0c 100644 --- a/build/gui.zig +++ b/build/gui.zig @@ -30,7 +30,7 @@ pub const Window = struct { gm.addIncludePath(sdl.include); if (w.sketchbook) |sb| { gm.addImport("gui_c", sb.module("c")); - gm.addImport("dev", sb.module("dev")); + gm.addImport("sketchbook", sb.module("dev")); } if (sdl.trackpad) |object| { gm.addObjectFile(object); @@ -47,7 +47,7 @@ pub const Window = struct { gm.addRPath(.{ .cwd_relative = "/usr/local/lib" }); if (w.sketchbook) |sb| gm.addCSourceFile(.{ .file = sb.namedLazyPath("font.c") }); // the embedded UI font: provided as a build import since assets/ lives - // outside the src/ module root (@embedFile can't escape it) + // outside the dev/ module root (@embedFile can't escape it) gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf"), }); @@ -77,7 +77,7 @@ pub fn make(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang. \\#include "macos_trackpad.h" \\ ); - const include: []const std.Build.LazyPath = &.{ dep.path("include"), b.path("src/gui") }; + const include: []const std.Build.LazyPath = &.{ dep.path("include"), b.path("dev/gui") }; w.sketchbook = b.lazyDependency("sketchbook", .{ .target = target, .optimize = optimize, .@"c-header" = header, .@"c-include" = include, .@"prebuilt-shaders" = prebuilt_shaders }); var sdl: Window.Sdl = .{ .lib = sdl_lib, .include = dep.path("include") }; if (target.result.os.tag == .macos) { @@ -85,9 +85,9 @@ pub fn make(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang. const shim = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O2", "-target", b.fmt("{s}-apple-macos13.0", .{arch}), "-I" }); shim.addDirectoryArg(dep.path("include")); shim.addArg("-c"); - shim.addFileArg(b.path("src/gui/macos_trackpad.m")); + shim.addFileArg(b.path("dev/gui/macos_trackpad.m")); // Header changes invalidate the independently compiled adapter. - shim.addFileInput(b.path("src/gui/macos_trackpad.h")); + shim.addFileInput(b.path("dev/gui/macos_trackpad.h")); shim.addArg("-o"); sdl.trackpad = shim.addOutputFileArg("macos_trackpad.o"); } @@ -136,8 +136,8 @@ pub fn make(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang. const adapter_test = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O1", "-framework", "Cocoa", "-I" }); adapter_test.addDirectoryArg(sdl.include); adapter_test.addFileArg(b.path("test/macos_trackpad.m")); - adapter_test.addFileInput(b.path("src/gui/macos_trackpad.m")); - adapter_test.addFileInput(b.path("src/gui/macos_trackpad.h")); + adapter_test.addFileInput(b.path("dev/gui/macos_trackpad.m")); + adapter_test.addFileInput(b.path("dev/gui/macos_trackpad.h")); adapter_test.addArg("-o"); const adapter_bin = adapter_test.addOutputFileArg("macos-trackpad-test"); const run_adapter = std.Build.Step.Run.create(b, "run macos-trackpad-test"); diff --git a/build/macos.zig b/build/macos.zig index 7289e70a..b865740e 100644 --- a/build/macos.zig +++ b/build/macos.zig @@ -23,7 +23,7 @@ pub fn add(b: *std.Build, c: struct { }); c.root_mod.addImport("pardes.h", header.createModule()); // The app's watcher, which macos.zig's test reads beside its own. - c.root_mod.addAnonymousImport("macos/Sources/FileWatcher.swift", .{ .root_source_file = b.path("src/macos/Sources/FileWatcher.swift") }); + c.root_mod.addAnonymousImport("macos/Sources/FileWatcher.swift", .{ .root_source_file = b.path("dev/macos/Sources/FileWatcher.swift") }); const lib = b.addLibrary(.{ .name = "pardes", @@ -68,7 +68,7 @@ pub fn add(b: *std.Build, c: struct { "ScenePostprocessor.swift", "FileWatcher.swift", }) |src| - link.addFileArg(b.path(b.fmt("src/macos/Sources/{s}", .{src}))); + link.addFileArg(b.path(b.fmt("dev/macos/Sources/{s}", .{src}))); link.addFileArg(lib_archive); link.addArgs(&.{ "-lc++", @@ -86,17 +86,17 @@ pub fn add(b: *std.Build, c: struct { const icon_build = b.addSystemCommand(&.{ "swiftc", "-O", "-target", triple, "-o" }); const icon_bin = icon_build.addOutputFileArg("pardes-icon"); - icon_build.addFileArg(b.path("src/macos/icon.swift")); + icon_build.addFileArg(b.path("dev/macos/icon.swift")); const icon_run = std.Build.Step.Run.create(b, "pardes-icon"); icon_run.addFileArg(icon_bin); - icon_run.addFileArg(b.path("src/macos/icon.png")); + icon_run.addFileArg(b.path("dev/macos/icon.png")); const icon_dir = icon_run.addOutputDirectoryArg("Resources"); const plist = b.addSystemCommand(&.{ "plutil", "-replace", "LSMinimumSystemVersion", "-string", min_version, "-o", }); const plist_out = plist.addOutputFileArg("Info.plist"); - plist.addFileArg(b.path("src/macos/Info.plist")); + plist.addFileArg(b.path("dev/macos/Info.plist")); const version_plist = b.addSystemCommand(&.{ "plutil", "-replace", "CFBundleShortVersionString", "-string", display_version, "-o", @@ -149,10 +149,10 @@ pub fn add(b: *std.Build, c: struct { e2e.addArg("-o"); const e2e_bin = e2e.addOutputFileArg("pardes-macos-e2e"); for ([_][]const u8{ - "src/macos/Sources/PardesView.swift", - "src/macos/Sources/ScenePostprocessor.swift", - "src/macos/Sources/FileWatcher.swift", - "src/macos/Sources/AppDelegate.swift", + "dev/macos/Sources/PardesView.swift", + "dev/macos/Sources/ScenePostprocessor.swift", + "dev/macos/Sources/FileWatcher.swift", + "dev/macos/Sources/AppDelegate.swift", "test/macos_e2e.swift", }) |source| e2e.addFileArg(b.path(source)); e2e.addFileArg(lib_archive); diff --git a/build/tests.zig b/build/tests.zig index 2d43d743..d351684d 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -9,9 +9,9 @@ const program = tools.program; /// addon-test (and the addons it loads), kitty-test, the 9P roots. pub fn add(b: *std.Build, c: struct { addon_mod: *std.Build.Module, - /// The core without a terminal and the runtime beside it: core-test. + /// The core without a terminal and the devices and runtime beside it: core-test. core_lean: core.Modules, - /// The shell's root, core and runtime: shell-test. + /// The shell's root, core, devices and runtime: shell-test. root_set: core.Modules, core_module: *std.Build.Module, /// core_module's configuration, for the test roots that run on its imports. @@ -63,9 +63,9 @@ pub fn add(b: *std.Build, c: struct { // The perf and fs bench programs' own tests: they compile no editor. _ = units.add(b, units.root(b, "test/perf.zig", true, &.{.{ .name = "perf_options", .module = c.tools.perf_options.createModule() }}), null); _ = units.add(b, units.root(b, "test/fs_bench.zig", null, &.{}), null); - const core_test_step = b.step("core-test", "run core tests without native shell tests, on the core without a terminal (a test that needs one skips), and the runtime's beside it"); + const core_test_step = b.step("core-test", "run core tests without native shell tests, on the core without a terminal (a test that needs one skips), and the devices' and the runtime's beside it"); const core_match = testMatch(b, c.unit_profile, c.test_filters, core_test_step); - for ([_]*std.Build.Module{ c.core_lean.core, c.core_lean.runtime }) |m| { + for ([_]*std.Build.Module{ c.core_lean.core, c.core_lean.dev, c.core_lean.runtime }) |m| { const core_test = b.addTest(.{ .root_module = m, .filters = c.test_filters }); const run_core_test = b.addRunArtifact(core_test); run_core_test.has_side_effects = true; @@ -211,18 +211,18 @@ pub fn add(b: *std.Build, c: struct { const protocol_step = b.step("9p-test", "run freestanding 9P protocol tests"); protocol_step.dependOn(&units.add(b, protocol_tests, null).step); if (testMatch(b, c.unit_profile, c.test_filters, protocol_step)) |check| check.addArtifactArg(protocol_tests); - _ = units.add(b, units.root(b, "src/fonts.zig", true, cloud9), null); + _ = units.add(b, units.root(b, "dev/fonts.zig", true, cloud9), null); _ = units.add(b, units.root(b, "src/c_heap.zig", false, cloud9), null); // Its lookup goes wrong only where the optimizer folds it. _ = units.add(b, b.addTest(.{ .root_module = b.createModule(.{ .target = c.target, .optimize = .safe, .root_source_file = b.path("src/c_heap.zig"), .link_libc = false, .imports = cloud9 }), .filters = c.test_filters }), null); - _ = units.add(b, units.root(b, "test/deck/replay.zig", null, &.{.{ .name = "deck", .module = b.createModule(.{ .target = c.target, .optimize = c.optimize, .root_source_file = b.path("src/gui/deck.zig") }) }}), null); + _ = units.add(b, units.root(b, "test/deck/replay.zig", null, &.{.{ .name = "deck", .module = b.createModule(.{ .target = c.target, .optimize = c.optimize, .root_source_file = b.path("dev/gui/deck.zig") }) }}), null); if (c.platform == .tui or c.platform == .gui) { // The native shell's tests alone, without the perf gate's // ReleaseFast build: what a -Dtest-filter iteration wants. - const shell_test_step = b.step("shell-test", "run the native shell's unit tests (runtime/main.zig's, and its core's and runtime's)"); - for ([_]*std.Build.Module{ c.root_set.root, c.root_set.core, c.root_set.runtime }) |m| + const shell_test_step = b.step("shell-test", "run the native shell's unit tests (runtime/main.zig's, and its core's, devices' and runtime's)"); + for ([_]*std.Build.Module{ c.root_set.root, c.root_set.core, c.root_set.dev, c.root_set.runtime }) |m| shell_test_step.dependOn(&units.add(b, b.addTest(.{ .root_module = m, .filters = c.test_filters }), null).step); const profile_test = b.addExecutable(.{ .name = "pardes-unit-profile-test", diff --git a/dev/Art.zig b/dev/Art.zig new file mode 100644 index 00000000..9ab0d0f1 --- /dev/null +++ b/dev/Art.zig @@ -0,0 +1,591 @@ +//! Glyph art: a picture drawn in a frame's cells with block, line and +//! letter glyphs in sixteen colours (the matcher is adapted from +//! caioluders/petsciinator). It is the frontends' (tui.zig always where the +//! terminal shows no pixels, gui.zig where a pane asks): the core hands a +//! picture as a `Placement` and never draws it, so its grid, `/screen`, is +//! the same on every client. One of these a frontend keeps the art of the +//! pictures it shows, while it shows them. +const std = @import("std"); +const colors = @import("core").colors; +const pardes = @import("core"); + +const Art = @This(); +const Surface = pardes.Surface; +const Placement = pardes.Placement; +const Raster = pardes.Raster; +const RectPx = pardes.RectPx; + +grids: std.AutoHashMapUnmanaged(Key, Kept) = .empty, + +/// What a grid was made from: the picture, the part of it, the cells, and +/// how (fitted when the placement leaves its place to the frontend). +const Key = struct { key: u64, src: RectPx, cols: u16, rows: u16, fitted: bool, palette: Placement.Art.Palette, ascii: bool }; +const Kept = struct { grid: Grid, used: bool = true }; + +pub fn deinit(art: *Art, gpa: std.mem.Allocator) void { + var it = art.grids.valueIterator(); + while (it.next()) |kept| gpa.free(kept.grid.cells); + art.grids.deinit(gpa); +} + +/// `s` as this frontend draws it: every placement it shows as glyph art +/// (each one where it shows no `pixels`, else those whose pane asks for +/// art) painted into a copy of the frame made in `arena`; `s` itself when +/// there is none. `cell_h` is a cell's height in the frontend's pixels: a +/// sliver of a row (under half of it) has no art. +pub fn frame(art: *Art, gpa: std.mem.Allocator, arena: std.mem.Allocator, s: *const Surface, pixels: bool, cell_h: u32) !*const Surface { + var it = art.grids.valueIterator(); + while (it.next()) |kept| kept.used = false; + defer art.prune(gpa); + var out: ?*Surface = null; + for (s.placements.items) |place| { + if (pixels and !place.art.glyph) continue; + const grid = art.gridOf(gpa, place, cell_h) orelse continue; + const drawn = out orelse copy: { + const copy = try arena.create(Surface); + copy.* = s.*; + copy.cells = try arena.dupe(pardes.Cell, s.cells); + out = copy; + break :copy copy; + }; + // Fitted, the art is centred in its cells; else it fills them. + const offx = if (place.at == null) (place.dst.w - grid.cols) / 2 else 0; + const offy = if (place.at == null) (place.dst.h - grid.rows) / 2 else 0; + for (0..grid.rows) |cy| for (0..grid.cols) |cx| { + const cell = &grid.cells[cy * grid.cols + cx]; + const sx = place.dst.x + offx + cx; + const sy = place.dst.y + offy + cy; + if (sx >= drawn.cols or sy >= drawn.rows) continue; + drawn.set(@intCast(sx), @intCast(sy), cell.glyph[0..cell.glyph_len], switch (place.art.palette) { + .commodore => .{ .fg = .{ .rgb = commodore[cell.fg] }, .bg = .{ .rgb = commodore[cell.bg] } }, + .terminal => .{ .fg = .{ .index = cell.fg }, .bg = .{ .index = cell.bg } }, + }); + }; + } + return out orelse s; +} + +/// The placement's art, made the first frame it is drawn. +fn gridOf(art: *Art, gpa: std.mem.Allocator, place: Placement, cell_h: u32) ?Grid { + if (place.dst.w == 0 or place.dst.h == 0) return null; + if (place.at) |at| if (at.h * 2 < @as(u32, place.dst.h) * cell_h) return null; + const key: Key = .{ .key = place.key, .src = place.src, .cols = place.dst.w, .rows = place.dst.h, .fitted = place.at == null, .palette = place.art.palette, .ascii = place.art.ascii }; + if (art.grids.getPtr(key)) |hit| { + hit.used = true; + return hit.grid; + } + const colours = switch (place.art.palette) { + .commodore => commodore, + .terminal => colors.xterm[0..16].*, + }; + const grid = (if (place.at == null) + fitted(gpa, place.raster, place.src, place.dst.w, place.dst.h, colours, place.art.ascii) + else + renderRect(gpa, place.raster, place.src, place.dst.w, place.dst.h, colours, place.art.ascii)) catch return null; + if (grid.cells.len == 0) { + gpa.free(grid.cells); + return null; + } + art.grids.put(gpa, key, .{ .grid = grid }) catch { + gpa.free(grid.cells); + return null; + }; + return grid; +} + +/// Drop what this frame did not draw. +fn prune(art: *Art, gpa: std.mem.Allocator) void { + while (true) { + var it = art.grids.iterator(); + const stale = while (it.next()) |entry| { + if (!entry.value_ptr.used) break entry.key_ptr.*; + } else break; + gpa.free(art.grids.get(stale).?.grid.cells); + _ = art.grids.remove(stale); + } +} + +pub const commodore = [16][3]u8{ + .{ 0x00, 0x00, 0x00 }, // 0 black + .{ 0xff, 0xff, 0xff }, // 1 white + .{ 0x68, 0x37, 0x2b }, // 2 red + .{ 0x70, 0xa4, 0xb2 }, // 3 cyan + .{ 0x6f, 0x3d, 0x86 }, // 4 purple + .{ 0x58, 0x8d, 0x43 }, // 5 green + .{ 0x35, 0x28, 0x79 }, // 6 blue + .{ 0xb8, 0xc7, 0x6f }, // 7 yellow + .{ 0x6f, 0x4f, 0x25 }, // 8 orange + .{ 0x43, 0x39, 0x00 }, // 9 brown + .{ 0x9a, 0x67, 0x59 }, // 10 light red + .{ 0x44, 0x44, 0x44 }, // 11 dark grey + .{ 0x6c, 0x6c, 0x6c }, // 12 grey + .{ 0x9a, 0xd2, 0x84 }, // 13 light green + .{ 0x6c, 0x5e, 0xb5 }, // 14 light blue + .{ 0x95, 0x95, 0x95 }, // 15 light grey +}; + +const Colours = [16][3]u8; + +pub const Cell = struct { + glyph: [4]u8 = .{ ' ', 0, 0, 0 }, + glyph_len: u3 = 1, + fg: u4 = 1, + bg: u4 = 0, +}; + +pub const Grid = struct { cells: []Cell, cols: usize, rows: usize }; + +fn dist2(a: [3]u8, b: [3]u8) u32 { + const dr = @as(i32, a[0]) - b[0]; + const dg = @as(i32, a[1]) - b[1]; + const db = @as(i32, a[2]) - b[2]; + return @intCast(dr * dr + dg * dg + db * db); +} + +fn nearest(px: [3]u8, pal: Colours) u4 { + var best: u4 = 0; + var bestd: u32 = std.math.maxInt(u32); + for (pal, 0..) |c, i| { + const d = dist2(px, c); + if (d < bestd) { + bestd = d; + best = @intCast(i); + } + } + return best; +} + +// ---- glyph set: each is a codepoint + an 8x8 ink bitmap (bit y*8+x set = fg) ---- +const Glyph = struct { cp: u21, bits: u64 }; + +fn sextantCp(p: u6) u21 { + return switch (p) { + 0 => ' ', + 21 => 0x258C, // left half ▌ + 42 => 0x2590, // right half ▐ + 63 => 0x2588, // full block █ + else => blk: { + var off: u21 = @as(u21, p) - 1; + if (p > 21) off -= 1; + if (p > 42) off -= 1; + break :blk 0x1FB00 + off; // Symbols for Legacy Computing sextants + }, + }; +} + +// the 8x8 ink bitmap for a sextant pattern (2 cols x 3 rows of subcells). +fn sextantBits(p: u6) u64 { + var bits: u64 = 0; + var y: usize = 0; + while (y < 8) : (y += 1) { + const band = (y * 3) / 8; // 0,0,0,1,1,1,2,2 + var x: usize = 0; + while (x < 8) : (x += 1) { + const col: usize = if (x < 4) 0 else 1; + const sub: u6 = @intCast(band * 2 + col); + if ((p >> sub) & 1 != 0) bits |= @as(u64, 1) << @intCast(y * 8 + x); + } + } + return bits; +} + +// pack 8 row-bytes (bit x set, x=0 leftmost) into the 8x8 bitmap. +fn glyphMask(r: [8]u8) u64 { + var b: u64 = 0; + for (r, 0..) |row, y| b |= @as(u64, row) << @intCast(y * 8); + return b; +} + +// the horizontal half blocks and the ten 2x2 quadrants — sextants are 2x3, so they +// can't express an exact 4-row half or a quarter; these fill that gap. +const block_glyphs = [_]Glyph{ + .{ .cp = 0x2580, .bits = glyphMask(.{ 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0 }) }, // ▀ top half + .{ .cp = 0x2584, .bits = glyphMask(.{ 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff }) }, // ▄ bottom half + .{ .cp = 0x2598, .bits = glyphMask(.{ 0x0f, 0x0f, 0x0f, 0x0f, 0, 0, 0, 0 }) }, // ▘ TL + .{ .cp = 0x259d, .bits = glyphMask(.{ 0xf0, 0xf0, 0xf0, 0xf0, 0, 0, 0, 0 }) }, // ▝ TR + .{ .cp = 0x2596, .bits = glyphMask(.{ 0, 0, 0, 0, 0x0f, 0x0f, 0x0f, 0x0f }) }, // ▖ BL + .{ .cp = 0x2597, .bits = glyphMask(.{ 0, 0, 0, 0, 0xf0, 0xf0, 0xf0, 0xf0 }) }, // ▗ BR + .{ .cp = 0x259a, .bits = glyphMask(.{ 0x0f, 0x0f, 0x0f, 0x0f, 0xf0, 0xf0, 0xf0, 0xf0 }) }, // ▚ TL+BR + .{ .cp = 0x259e, .bits = glyphMask(.{ 0xf0, 0xf0, 0xf0, 0xf0, 0x0f, 0x0f, 0x0f, 0x0f }) }, // ▞ TR+BL + .{ .cp = 0x259b, .bits = glyphMask(.{ 0xff, 0xff, 0xff, 0xff, 0x0f, 0x0f, 0x0f, 0x0f }) }, // ▛ ¬BR + .{ .cp = 0x259c, .bits = glyphMask(.{ 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0 }) }, // ▜ ¬BL + .{ .cp = 0x2599, .bits = glyphMask(.{ 0x0f, 0x0f, 0x0f, 0x0f, 0xff, 0xff, 0xff, 0xff }) }, // ▙ ¬TR + .{ .cp = 0x259f, .bits = glyphMask(.{ 0xf0, 0xf0, 0xf0, 0xf0, 0xff, 0xff, 0xff, 0xff }) }, // ▟ ¬TL +}; + +// line/diagonal glyphs add the characteristic PETSCII "drawn" look on edges. +const line_glyphs = [_]Glyph{ + .{ .cp = 0x2500, .bits = glyphMask(.{ 0, 0, 0, 0xff, 0xff, 0, 0, 0 }) }, // ─ + .{ .cp = 0x2502, .bits = glyphMask(.{ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18 }) }, // │ + .{ .cp = 0x253c, .bits = glyphMask(.{ 0x18, 0x18, 0x18, 0xff, 0xff, 0x18, 0x18, 0x18 }) }, // ┼ + .{ .cp = 0x2572, .bits = glyphMask(.{ 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }) }, // ╲ + .{ .cp = 0x2571, .bits = glyphMask(.{ 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }) }, // ╱ + .{ .cp = 0x2573, .bits = glyphMask(.{ 0x81, 0x42, 0x24, 0x18, 0x18, 0x24, 0x42, 0x81 }) }, // ╳ +}; + +const ascii_glyphs = [_]Glyph{ + .{ .cp = 0x21, .bits = 0x00180018183c3c18 }, // ! + .{ .cp = 0x22, .bits = 0x0000000000246666 }, // " + .{ .cp = 0x23, .bits = 0x0036367f367f3636 }, // # + .{ .cp = 0x24, .bits = 0x00183e603c067c18 }, // $ + .{ .cp = 0x25, .bits = 0x0063660c18336300 }, // % + .{ .cp = 0x26, .bits = 0x006e333b6e1c361c }, // & + .{ .cp = 0x27, .bits = 0x00000000000c1818 }, // ' + .{ .cp = 0x28, .bits = 0x0030180c0c0c1830 }, // ( + .{ .cp = 0x29, .bits = 0x000c18303030180c }, // ) + .{ .cp = 0x2a, .bits = 0x0000663cff3c6600 }, // * + .{ .cp = 0x2b, .bits = 0x000018187e181800 }, // + + .{ .cp = 0x2c, .bits = 0x0c18180000000000 }, // , + .{ .cp = 0x2d, .bits = 0x000000007e000000 }, // - + .{ .cp = 0x2e, .bits = 0x0018180000000000 }, // . + .{ .cp = 0x2f, .bits = 0x000103060c183060 }, // / + .{ .cp = 0x30, .bits = 0x001c36636b63361c }, // 0 + .{ .cp = 0x31, .bits = 0x007e181818181c18 }, // 1 + .{ .cp = 0x32, .bits = 0x007f660c3860633e }, // 2 + .{ .cp = 0x33, .bits = 0x003e63603c60633e }, // 3 + .{ .cp = 0x34, .bits = 0x0078307f33363c38 }, // 4 + .{ .cp = 0x35, .bits = 0x003e63603f03037f }, // 5 + .{ .cp = 0x36, .bits = 0x003e63633f03061c }, // 6 + .{ .cp = 0x37, .bits = 0x000c0c0c1830637f }, // 7 + .{ .cp = 0x38, .bits = 0x003e63633e63633e }, // 8 + .{ .cp = 0x39, .bits = 0x001e30607e63633e }, // 9 + .{ .cp = 0x3a, .bits = 0x0018180000181800 }, // : + .{ .cp = 0x3b, .bits = 0x0c18180000181800 }, // ; + .{ .cp = 0x3c, .bits = 0x006030180c183060 }, // < + .{ .cp = 0x3d, .bits = 0x00007e00007e0000 }, // = + .{ .cp = 0x3e, .bits = 0x00060c1830180c06 }, // > + .{ .cp = 0x3f, .bits = 0x001800181830633e }, // ? + .{ .cp = 0x40, .bits = 0x001e037b7b7b633e }, // @ + .{ .cp = 0x41, .bits = 0x006363637f63361c }, // A + .{ .cp = 0x42, .bits = 0x003f66663e66663f }, // B + .{ .cp = 0x43, .bits = 0x003c66030303663c }, // C + .{ .cp = 0x44, .bits = 0x001f36666666361f }, // D + .{ .cp = 0x45, .bits = 0x007f46161e16467f }, // E + .{ .cp = 0x46, .bits = 0x000f06161e16467f }, // F + .{ .cp = 0x47, .bits = 0x005c66730303663c }, // G + .{ .cp = 0x48, .bits = 0x006363637f636363 }, // H + .{ .cp = 0x49, .bits = 0x003c18181818183c }, // I + .{ .cp = 0x4a, .bits = 0x001e333330303078 }, // J + .{ .cp = 0x4b, .bits = 0x006766361e366667 }, // K + .{ .cp = 0x4c, .bits = 0x007f66460606060f }, // L + .{ .cp = 0x4d, .bits = 0x0063636b7f7f7763 }, // M + .{ .cp = 0x4e, .bits = 0x006363737b6f6763 }, // N + .{ .cp = 0x4f, .bits = 0x003e63636363633e }, // O + .{ .cp = 0x50, .bits = 0x000f06063e66663f }, // P + .{ .cp = 0x51, .bits = 0x703e73636363633e }, // Q + .{ .cp = 0x52, .bits = 0x006766363e66663f }, // R + .{ .cp = 0x53, .bits = 0x003c6630180c663c }, // S + .{ .cp = 0x54, .bits = 0x003c1818185a7e7e }, // T + .{ .cp = 0x55, .bits = 0x003e636363636363 }, // U + .{ .cp = 0x56, .bits = 0x001c366363636363 }, // V + .{ .cp = 0x57, .bits = 0x00367f6b6b636363 }, // W + .{ .cp = 0x58, .bits = 0x006363361c366363 }, // X + .{ .cp = 0x59, .bits = 0x003c18183c666666 }, // Y + .{ .cp = 0x5a, .bits = 0x007f664c1831637f }, // Z + .{ .cp = 0x5b, .bits = 0x003c0c0c0c0c0c3c }, // [ + .{ .cp = 0x5c, .bits = 0x00406030180c0603 }, // \\ + .{ .cp = 0x5d, .bits = 0x003c30303030303c }, // ] + .{ .cp = 0x5e, .bits = 0x0000000063361c08 }, // ^ + .{ .cp = 0x5f, .bits = 0xff00000000000000 }, // _ + .{ .cp = 0x60, .bits = 0x000000000030180c }, // ` + .{ .cp = 0x61, .bits = 0x006e333e301e0000 }, // a + .{ .cp = 0x62, .bits = 0x003b6666663e0607 }, // b + .{ .cp = 0x63, .bits = 0x003e6303633e0000 }, // c + .{ .cp = 0x64, .bits = 0x006e3333333e3038 }, // d + .{ .cp = 0x65, .bits = 0x003e037f633e0000 }, // e + .{ .cp = 0x66, .bits = 0x000f06061f06663c }, // f + .{ .cp = 0x67, .bits = 0x1f303e33336e0000 }, // g + .{ .cp = 0x68, .bits = 0x006766666e360607 }, // h + .{ .cp = 0x69, .bits = 0x003c1818181c0018 }, // i + .{ .cp = 0x6a, .bits = 0x3c66666060600060 }, // j + .{ .cp = 0x6b, .bits = 0x0067361e36660607 }, // k + .{ .cp = 0x6c, .bits = 0x003c18181818181c }, // l + .{ .cp = 0x6d, .bits = 0x006b6b6b7f370000 }, // m + .{ .cp = 0x6e, .bits = 0x00666666663b0000 }, // n + .{ .cp = 0x6f, .bits = 0x003e6363633e0000 }, // o + .{ .cp = 0x70, .bits = 0x0f063e66663b0000 }, // p + .{ .cp = 0x71, .bits = 0x78303e33336e0000 }, // q + .{ .cp = 0x72, .bits = 0x000f06066e3b0000 }, // r + .{ .cp = 0x73, .bits = 0x003f603e037e0000 }, // s + .{ .cp = 0x74, .bits = 0x00386c0c0c3f0c0c }, // t + .{ .cp = 0x75, .bits = 0x006e333333330000 }, // u + .{ .cp = 0x76, .bits = 0x001c366363630000 }, // v + .{ .cp = 0x77, .bits = 0x00367f6b6b630000 }, // w + .{ .cp = 0x78, .bits = 0x0063361c36630000 }, // x + .{ .cp = 0x79, .bits = 0x3f607e6363630000 }, // y + .{ .cp = 0x7a, .bits = 0x007e4c18327e0000 }, // z + .{ .cp = 0x7b, .bits = 0x007018180e181870 }, // { + .{ .cp = 0x7c, .bits = 0x0018181818181818 }, // | + .{ .cp = 0x7d, .bits = 0x000e18187018180e }, // } + .{ .cp = 0x7e, .bits = 0x0000000000003b6e }, // ~ +}; + +// the block glyph table (sextants + half/quadrant blocks + line glyphs), built at +// comptime, and the same set extended with the ASCII glyphs. `render(ascii=…)` picks. +const glyphs = blk: { + @setEvalBranchQuota(100000); + var list: [64 + block_glyphs.len + line_glyphs.len]Glyph = undefined; + var p: usize = 0; + while (p < 64) : (p += 1) list[p] = .{ .cp = sextantCp(@intCast(p)), .bits = sextantBits(@intCast(p)) }; + for (block_glyphs, 0..) |bg, i| list[64 + i] = bg; + for (line_glyphs, 0..) |lg, i| list[64 + block_glyphs.len + i] = lg; + break :blk list; +}; +const glyphs_ascii = glyphs ++ ascii_glyphs; + +fn matchCell(cell: *const [64][3]u8, pal: Colours, gset: []const Glyph) Cell { + var counts = @as([16]u16, @splat(0)); + for (cell) |px| counts[nearest(px, pal)] += 1; + var cand: [4]u4 = undefined; + var ncand: usize = 0; + var used = @as([16]bool, @splat(false)); + while (ncand < 4) : (ncand += 1) { + var best: ?usize = null; + for (counts, 0..) |c, i| { + if (used[i] or c == 0) continue; + if (best == null or c > counts[best.?]) best = i; + } + if (best) |bi| { + cand[ncand] = @intCast(bi); + used[bi] = true; + } else break; + } + if (ncand == 0) return .{}; // can't happen (64 pixels), but keep it total + if (ncand == 1) return encode(' ', cand[0], cand[0]); // solid color + + var best_cost: i64 = std.math.maxInt(i64); + var best = encode(' ', cand[0], cand[0]); + var fi: usize = 0; + while (fi < ncand) : (fi += 1) { + var bi: usize = 0; + while (bi < ncand) : (bi += 1) { + if (fi == bi) continue; + const fg = cand[fi]; + const bg = cand[bi]; + var dfg: [64]u32 = undefined; + var dbg: [64]u32 = undefined; + var base: i64 = 0; + for (cell, 0..) |px, p| { + dfg[p] = dist2(px, pal[fg]); + dbg[p] = dist2(px, pal[bg]); + base += dbg[p]; + } + for (gset) |g| { + var delta: i64 = 0; + var bits = g.bits; + while (bits != 0) : (bits &= bits - 1) { + const p: usize = @ctz(bits); + delta += @as(i64, dfg[p]) - @as(i64, dbg[p]); + } + const cost = base + delta; + if (cost < best_cost) { + best_cost = cost; + best = encode(g.cp, fg, bg); + } + } + } + } + return best; +} + +fn encode(cp: u21, fg: u4, bg: u4) Cell { + var c = Cell{ .fg = fg, .bg = bg }; + const n = std.unicode.utf8Encode(cp, &c.glyph) catch 1; + c.glyph_len = @intCast(n); + return c; +} + +/// `src` of `raster` fitted into `max_cols` x `max_rows` cells, its shape +/// kept: cells are about twice as tall as wide, so a row spans two widths. +fn fitted(gpa: std.mem.Allocator, raster: Raster, src: RectPx, max_cols: usize, max_rows: usize, pal: Colours, ascii: bool) !Grid { + if (src.w == 0 or src.h == 0 or max_cols == 0 or max_rows == 0) return .{ .cells = try gpa.alloc(Cell, 0), .cols = 0, .rows = 0 }; + var cols = max_cols; + var rows = (max_cols * src.h) / (2 * src.w); + if (rows > max_rows) { + rows = max_rows; + cols = (max_rows * 2 * src.w) / src.h; + } + cols = std.math.clamp(cols, 1, max_cols); + rows = std.math.clamp(rows, 1, max_rows); + return renderRect(gpa, raster, src, cols, rows, pal, ascii); +} + +/// The pixels of `src` laid over exactly `cols` x `rows` cells, whatever +/// their shape: a terminal's image fragment is already the size its cells +/// are. +fn renderRect(gpa: std.mem.Allocator, raster: Raster, src: RectPx, cols: usize, rows: usize, pal: Colours, ascii: bool) !Grid { + const iw: usize = raster.w; + const ih: usize = raster.h; + const rgba = raster.bytes(); + const x0: usize = @min(src.x, iw); + const y0: usize = @min(src.y, ih); + const sw: usize = @min(src.w, iw - x0); + const sh: usize = @min(src.h, ih - y0); + if (sw == 0 or sh == 0 or cols == 0 or rows == 0) return .{ .cells = try gpa.alloc(Cell, 0), .cols = 0, .rows = 0 }; + const gset: []const Glyph = if (ascii) &glyphs_ascii else &glyphs; + const cells = try gpa.alloc(Cell, cols * rows); + var cy: usize = 0; + while (cy < rows) : (cy += 1) { + const ry0 = y0 + cy * sh / rows; + const ry1 = @max(ry0 + 1, y0 + (cy + 1) * sh / rows); + var cx: usize = 0; + while (cx < cols) : (cx += 1) { + const rx0 = x0 + cx * sw / cols; + const rx1 = @max(rx0 + 1, x0 + (cx + 1) * sw / cols); + var cell: [64][3]u8 = undefined; + var sy: usize = 0; + while (sy < 8) : (sy += 1) { + const py0 = ry0 + sy * (ry1 - ry0) / 8; + const py1 = @max(py0 + 1, ry0 + (sy + 1) * (ry1 - ry0) / 8); + var sx: usize = 0; + while (sx < 8) : (sx += 1) { + const px0 = rx0 + sx * (rx1 - rx0) / 8; + const px1 = @max(px0 + 1, rx0 + (sx + 1) * (rx1 - rx0) / 8); + var rs: usize = 0; + var gs: usize = 0; + var bs: usize = 0; + var n: usize = 0; + var yy = py0; + while (yy < py1 and yy < ih) : (yy += 1) { + var xx = px0; + while (xx < px1 and xx < iw) : (xx += 1) { + const i = yy * raster.stride + xx * 4; + rs += rgba[i]; + gs += rgba[i + 1]; + bs += rgba[i + 2]; + n += 1; + } + } + if (n == 0) n = 1; + cell[sy * 8 + sx] = .{ @intCast(rs / n), @intCast(gs / n), @intCast(bs / n) }; + } + } + cells[cy * cols + cx] = matchCell(&cell, pal, gset); + } + } + return .{ .cells = cells, .cols = cols, .rows = rows }; +} + +test "sextant codepoints: blocks + endpoints" { + try std.testing.expectEqual(@as(u21, ' '), sextantCp(0)); + try std.testing.expectEqual(@as(u21, 0x2588), sextantCp(63)); + try std.testing.expectEqual(@as(u21, 0x258C), sextantCp(21)); + try std.testing.expectEqual(@as(u21, 0x2590), sextantCp(42)); + try std.testing.expectEqual(@as(u21, 0x1FB00), sextantCp(1)); // first sextant + try std.testing.expectEqual(@as(u21, 0x1FB3B), sextantCp(62)); // last sextant +} + +test "matchCell: solid color -> space on that bg" { + var cell: [64][3]u8 = undefined; + for (&cell) |*p| p.* = commodore[5]; // all green + const m = matchCell(&cell, commodore, &glyphs); + try std.testing.expectEqual(@as(u4, 5), m.bg); + try std.testing.expectEqual(@as(u8, ' '), m.glyph[0]); +} + +test "matchCell: clean top/bottom split picks the two colors" { + var cell: [64][3]u8 = undefined; + for (0..64) |p| cell[p] = if (p < 32) commodore[1] else commodore[6]; // white over blue + const m = matchCell(&cell, commodore, &glyphs); + // both palette colors must be chosen (in some fg/bg order) + const a = @as(u4, @min(m.fg, m.bg)); + const b = @as(u4, @max(m.fg, m.bg)); + try std.testing.expectEqual(@as(u4, 1), a); + try std.testing.expectEqual(@as(u4, 6), b); + // a clean top/bottom split must resolve to a real block glyph (the top-4-rows + // half block ▀), never a blank cell. + const cp = std.unicode.utf8Decode(m.glyph[0..m.glyph_len]) catch 0; + try std.testing.expectEqual(@as(u21, 0x2580), cp); +} + +test "ascii option only enables the ascii glyphs" { + // the ascii glyph codepoints must be reachable exactly when ascii is on. + var seen_block = false; + var seen_ascii = false; + for (glyphs) |g| if (g.cp == '#') { + seen_block = true; + }; + for (glyphs_ascii) |g| if (g.cp == '#') { + seen_ascii = true; + }; + try std.testing.expect(!seen_block); // '#' is an ascii-only glyph + try std.testing.expect(seen_ascii); + try std.testing.expectEqual(glyphs.len + ascii_glyphs.len, glyphs_ascii.len); +} + +test "ascii glyph is chosen when a cell has its exact shape" { + // a cell shaped exactly like the font 'S' (ink=white on black) must match 'S' + // with ascii on (cost 0), and fall back to some block glyph with ascii off. + const s_bits: u64 = 0x003c6630180c663c; + var cell: [64][3]u8 = undefined; + for (0..64) |p| cell[p] = if ((s_bits >> @intCast(p)) & 1 != 0) commodore[1] else commodore[0]; + const on = matchCell(&cell, commodore, &glyphs_ascii); + try std.testing.expectEqual(@as(u21, 'S'), std.unicode.utf8Decode(on.glyph[0..on.glyph_len]) catch 0); + const off = matchCell(&cell, commodore, &glyphs); + try std.testing.expect((std.unicode.utf8Decode(off.glyph[0..off.glyph_len]) catch 0) != 'S'); +} + +test "a tiny image fitted into cells makes a grid within bounds" { + const a = std.testing.allocator; + // 2x2 checker, RGBA + var img = @as([2 * 2 * 4]u8, @splat(0)); + img[0] = 255; + img[1] = 255; + img[2] = 255; + img[3] = 255; // (0,0) white + img[(3) * 4 + 0] = 255; + img[(3) * 4 + 1] = 255; + img[(3) * 4 + 2] = 255; + img[(3) * 4 + 3] = 255; // (1,1) white + const g = try fitted(a, .of(&img, 2, 2), .{ .w = 2, .h = 2 }, 10, 10, commodore, true); + defer a.free(g.cells); + try std.testing.expect(g.cols >= 1 and g.cols <= 10); + try std.testing.expect(g.rows >= 1 and g.rows <= 10); + try std.testing.expectEqual(g.cols * g.rows, g.cells.len); +} + +test "a frontend draws a placement as glyph art where it shows no pixels, or where its pane asks, and else leaves the frame be" { + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var art: Art = .{}; + defer art.deinit(gpa); + // 8x8 pixels, white over blue, over a 20x6 cell body at (2, 1). + var px: [8 * 8 * 4]u8 = undefined; + for (0..64) |i| px[i * 4 ..][0..4].* = if (i < 32) .{ 255, 255, 255, 255 } else .{ 0x35, 0x28, 0x79, 255 }; + var cells: [30 * 8]pardes.Cell = @splat(.{}); + var s: Surface = .{ .cols = 30, .rows = 8, .cells = &cells }; + defer s.placements.deinit(gpa); + try s.placements.append(gpa, .{ .pane = 0, .raster = .of(&px, 8, 8), .src = .{ .w = 8, .h = 8 }, .dst = .{ .x = 2, .y = 1, .w = 20, .h = 6 }, .key = Placement.keyOf(1, 0, 0) }); + + try std.testing.expectEqual(@as(*const Surface, &s), try art.frame(gpa, arena.allocator(), &s, true, 16)); + const drawn = try art.frame(gpa, arena.allocator(), &s, false, 16); + try std.testing.expect(drawn != &s); + try std.testing.expect(s.at(2, 1).default); + // Fitted at its shape (a square is half as many rows as columns) and + // centred: 12x6 cells from column 6. + try std.testing.expect(@constCast(drawn).at(5, 1).default); + try std.testing.expectEqual(pardes.Color{ .rgb = commodore[1] }, @constCast(drawn).at(6, 1).style.bg); + try std.testing.expect(!@constCast(drawn).at(17, 6).default); + try std.testing.expect(@constCast(drawn).at(18, 6).default); + try std.testing.expectEqual(@as(u32, 1), art.grids.count()); + + // The pane asks for art in the terminal's sixteen: indices, not rgb. + s.placements.items[0].art = .{ .glyph = true, .palette = .terminal }; + const asked = try art.frame(gpa, arena.allocator(), &s, true, 16); + try std.testing.expect(@constCast(asked).at(6, 1).style.bg == .index); + // What a frame did not draw is let go. + try std.testing.expectEqual(@as(u32, 1), art.grids.count()); + s.placements.clearRetainingCapacity(); + try std.testing.expectEqual(@as(*const Surface, &s), try art.frame(gpa, arena.allocator(), &s, false, 16)); + try std.testing.expectEqual(@as(u32, 0), art.grids.count()); + + // Placed exactly (a terminal's image row), it fills its cells, but not + // a sliver of a row. + try s.placements.append(gpa, .{ .pane = 0, .raster = .of(&px, 8, 8), .src = .{ .w = 8, .h = 4 }, .dst = .{ .x = 0, .y = 7, .w = 4, .h = 1 }, .at = .{ .w = 40, .h = 16 }, .key = Placement.keyOf(1, 2, 0) }); + const row = try art.frame(gpa, arena.allocator(), &s, false, 16); + for (0..4) |x| try std.testing.expect(!@constCast(row).at(@intCast(x), 7).default); + try std.testing.expect(@constCast(row).at(4, 7).default); + s.placements.items[0].at.?.h = 7; + try std.testing.expectEqual(@as(*const Surface, &s), try art.frame(gpa, arena.allocator(), &s, false, 16)); +} diff --git a/dev/file_watch.zig b/dev/file_watch.zig new file mode 100644 index 00000000..b2205173 --- /dev/null +++ b/dev/file_watch.zig @@ -0,0 +1,963 @@ +//! Native file-watch state and the mark/reconcile transaction shared by the +//! TTY and SDL hosts. Their event loops still own blocking waits, wake +//! coalescing, and retry scheduling; this file owns the identical synchronous +//! operation each wake performs. Text buffers already own the bytes whose hash +//! is their generation. A kind's pane (a PDF) uses metadata which changes for +//! in-place and rename-over saves, reading its file only when it changed. +//! +//! Two kernels, one transaction: inotify on linux (and FreeBSD 15's, the +//! same events), kqueue on macos. `init`, `wait`, `stop`, `drain`, `markDir` +//! and `unmarkDir` are the whole of that difference, and nothing above them +//! knows which one it is on. +const std = @import("std"); +const builtin = @import("builtin"); +/// libc: inotify and kqueue, which std.Io does not have. +const libc = std.c; +const linux = std.os.linux; +const pardes = @import("core"); +const colors = @import("core").colors; +const filesystem = @import("core").filesystem; +const message = pardes.Messages.Message; + +pub const Identity = struct { + inode: std.Io.File.INode, + size: u64, + mtime_ns: i96, + ctime_ns: i96, + + pub fn eql(a: Identity, b: Identity) bool { + return std.meta.eql(a, b); + } +}; + +/// The last disk generation accepted by a native shell. Text panes already +/// need their bytes, so their exact content hash is cheapest. A kind's pane +/// uses metadata, its file read only once that moved (a PDF can be large). +pub const Generation = union(enum) { + text: u64, + kind: ?Identity, +}; + +/// Whether a kind's file is still the bytes its pane opened from. +fn sameBytes(core: *pardes.Pardes, pane: *const pardes.Pane, path: []const u8) bool { + const k = pane.addon orelse return false; + if (k.opened == 0) return false; + const bytes = filesystem.read(core, path) catch return false; + defer core.gpa.free(bytes); + return std.hash.Wyhash.hash(0, bytes) == k.opened; +} + +fn kindPath(pane: *const pardes.Pane) ?[]const u8 { + const k = pane.addon orelse return null; + return if (k.path.len > 0) k.path else null; +} + +/// One native directory mark, plus what macos needs beside it. +/// +/// `wd` is an inotify wd on linux and an open EVTONLY directory descriptor on +/// macos. Either way it marks the CONTAINING directory, because editor-style +/// rename-over saves replace the file inode. +/// +/// `file_wd` and `kq` exist only on macos, and only because a kqueue directory +/// filter reports changes to the DIRECTORY — entries added, removed, renamed — +/// and never a write to a file already inside it. inotify's CLOSE_WRITE covers +/// that from the directory mark; kqueue has no equivalent, so an in-place save +/// needs a second filter on the file itself. `kq` is the queue both filters +/// live on, kept here so `reloadPane` can re-arm the file filter after a +/// rename-over gave the pathname a new inode, without every caller between it +/// and a host having to carry the descriptor. +/// +/// `generation` is the reconciled disk snapshot; Restore establishes this +/// baseline without replacing its saved buffer. Serial rejects reused slots. +pub const Watch = struct { + wd: c_int, + file_wd: c_int = -1, + kq: c_int = -1, + serial: u32, + generation: Generation, + /// The path last read while watched (its hash): its going away later is + /// a deletion to say, where a path never there (a pane renamed to a new + /// name) is not. + existed: ?u64 = null, +}; + +/// The final slot is the one non-pane watched payload: the active ThemeFile. +/// Sharing the table also shares directory descriptors correctly when a user +/// happens to open that .zon as an ordinary document. +pub const theme_slot = pardes.MAX_PANES; +pub const Table = [theme_slot + 1]?Watch; + +/// Whether this OS has a watcher at all. Off it every entry point below +/// returns the inert answer: `watchPane` installs nothing, so `watches` stays +/// empty and `reloadPane` returns false for every slot. The core then keeps its +/// own record of what was asked and simply never gets a `file_changed`, which +/// is what a host with no watcher has always done here. +pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd or builtin.os.tag == .macos; + +/// The wake filter's `ident` on macos. `ident` is a directory descriptor for +/// every other filter on this queue, and no descriptor is `maxInt(usize)`, so +/// nothing can collide with it. +const wake_ident: usize = std.math.maxInt(usize); + +/// Create the descriptor a host waits on, and the ONE place the difference +/// between the two kernels is spelled. +/// +/// linux: an inotify instance; a mark is a wd added to it. +/// macos: a kqueue; a mark is an EVFILT_VNODE filter whose `ident` is an open +/// directory descriptor, plus the one EVFILT_USER filter registered here that +/// `stop` triggers to end a parked `wait`. +/// +/// `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` (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 +/// queue. +/// +/// -1 when there is no watcher to make, which every entry point below reads as +/// "mark nothing". +pub fn init(polled: bool) c_int { + switch (builtin.os.tag) { + .linux => return libc.inotify_init1(if (polled) + linux.IN.CLOEXEC | linux.IN.NONBLOCK + else + linux.IN.CLOEXEC), + // FreeBSD's IN_CLOEXEC and IN_NONBLOCK are its O_ flags. + .freebsd => return libc.inotify_init1(if (polled) 0x00100000 | 0x4 else 0x00100000), + .macos => { + const kq = libc.kqueue(); + if (kq < 0) return -1; + const changes = [_]libc.Kevent{.{ + .ident = wake_ident, + .filter = libc.EVFILT.USER, + .flags = libc.EV.ADD | libc.EV.CLEAR, + .fflags = 0, + .data = 0, + .udata = 0, + }}; + var events: [1]libc.Kevent = undefined; + if (libc.kevent(kq, &changes, 1, &events, 0, null) < 0) { + _ = libc.close(kq); + return -1; + } + return kq; + }, + else => return -1, + } +} + +/// Park until a marked directory changes. False ends the watcher: `stop` was +/// called, or the queue died. +/// +/// 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 +/// (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 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; + if (fd < 0) return false; + const none = [_]libc.Kevent{}; + var events: [8]libc.Kevent = undefined; + while (true) { + const n = libc.kevent(fd, &none, 0, &events, events.len, null); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return false; + } + if (n == 0) continue; + for (events[0..@intCast(n)]) |event| { + if (event.filter == libc.EVFILT.USER) return false; + } + return true; + } +} + +/// Wake a host parked in `wait` so it returns BEFORE the descriptor it is +/// parked on is closed. A no-op on linux, where cancelling the future reading +/// that descriptor is what ends the watcher. +pub fn stop(fd: c_int) void { + if (comptime builtin.os.tag != .macos) return; + if (fd < 0) return; + const changes = [_]libc.Kevent{.{ + .ident = wake_ident, + .filter = libc.EVFILT.USER, + .flags = 0, + .fflags = libc.NOTE.TRIGGER, + .data = 0, + .udata = 0, + }}; + var events: [1]libc.Kevent = undefined; + _ = libc.kevent(fd, &changes, 1, &events, 0, null); +} + +/// Consume every pending edge without blocking, for a host that found the +/// descriptor ready in its own `poll(2)` rather than parking a thread on it. +/// True when at least one of them was a directory change. +/// +/// DRAINED TO EMPTY on both kernels, and for the same reason: the descriptor is +/// level-triggered, so a queue left partly full makes the next `poll` return +/// ready immediately, and each of those rounds is a whole pump. +pub fn drain(fd: c_int) bool { + if (fd < 0) return false; + switch (builtin.os.tag) { + .linux, .freebsd => { + var buf: [4096]u8 = undefined; + var seen = false; + while (libc.read(fd, &buf, buf.len) > 0) seen = true; + return seen; + }, + .macos => { + const none = [_]libc.Kevent{}; + const now: libc.timespec = .{ .sec = 0, .nsec = 0 }; + var events: [16]libc.Kevent = undefined; + var seen = false; + while (true) { + const n = libc.kevent(fd, &none, 0, &events, events.len, &now); + if (n <= 0) return seen; + for (events[0..@intCast(n)]) |event| { + if (event.filter != libc.EVFILT.USER) seen = true; + } + if (n < events.len) return seen; + } + }, + else => return false, + } +} + +/// Install the kernel mark on `dir_z` and return its handle, or -1. +/// +/// The handle is an inotify wd on linux and an open directory descriptor on +/// macos, and BOTH have to answer "the same directory twice is the same +/// handle": `watchPane`'s sharing loop compares handles to decide when the last +/// user of a mark is gone, and `Watch` keeps no path to compare instead. +/// inotify does that deduplication itself. On macos it is done here, by device +/// and inode, because each EVFILT_VNODE filter needs a descriptor of its own. +fn markDir(fd: c_int, dir_z: [:0]const u8, watches: *const Table) c_int { + switch (builtin.os.tag) { + .linux, .freebsd => { + // CLOSE_WRITE coalesces one writer's writes; MOVED_TO and CREATE + // cover rename-over and delete-then-recreate saves; DELETE and + // MOVED_FROM a file going away, said at once (File.deleted), not + // when something else next changes in the directory. + const mask = linux.IN.CLOSE_WRITE | linux.IN.MOVED_TO | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_FROM | linux.IN.ONLYDIR; + return libc.inotify_add_watch(fd, dir_z, mask); + }, + .macos => { + // EVTONLY is the point of the descriptor: it marks the directory + // without counting as a reference that would keep an unmounting + // volume busy. DIRECTORY is inotify's ONLYDIR. + const dir_fd = libc.open(dir_z, .{ + .ACCMODE = .RDONLY, + .EVTONLY = true, + .CLOEXEC = true, + .DIRECTORY = true, + }, @as(libc.mode_t, 0)); + if (dir_fd < 0) return -1; + var want: libc.Stat = undefined; + if (libc.fstat(dir_fd, &want) != 0) { + _ = libc.close(dir_fd); + return -1; + } + for (watches) |other| { + const candidate = other orelse continue; + var have: libc.Stat = undefined; + if (libc.fstat(candidate.wd, &have) != 0) continue; + if (have.dev != want.dev or have.ino != want.ino) continue; + _ = libc.close(dir_fd); + return candidate.wd; + } + // What a DIRECTORY filter reports is its entries changing, which + // is a rename-over or a delete-then-recreate — MOVED_TO and CREATE + // above. It does NOT report a write to a file already inside it, + // which is what CLOSE_WRITE covers there; `markFile` is that half. + // RENAME and DELETE here are the marked directory itself going + // away. + // + // EV_CLEAR is not optional: without it the filter stays triggered + // once it has fired and every `wait` returns immediately forever. + const changes = [_]libc.Kevent{.{ + .ident = @intCast(dir_fd), + .filter = libc.EVFILT.VNODE, + .flags = libc.EV.ADD | libc.EV.CLEAR, + .fflags = libc.NOTE.WRITE | libc.NOTE.RENAME | libc.NOTE.DELETE, + .data = 0, + .udata = 0, + }}; + var events: [1]libc.Kevent = undefined; + if (libc.kevent(fd, &changes, 1, &events, 0, null) < 0) { + _ = libc.close(dir_fd); + return -1; + } + return dir_fd; + }, + else => return -1, + } +} + +/// The other half of a macos mark: the filter on the watched FILE, which is the +/// only thing that reports an in-place save. -1 when there is no file there yet +/// — a path that does not exist is still worth marking the directory for, and +/// the create arrives on that mark. +/// +/// Not deduplicated, unlike the directory: two panes on the same file are two +/// slots that each want their own wake, and a file filter has exactly one user. +fn markFile(kq: c_int, path_z: [:0]const u8) c_int { + if (comptime builtin.os.tag != .macos) return -1; + const file_fd = libc.open(path_z, .{ + .ACCMODE = .RDONLY, + .EVTONLY = true, + .CLOEXEC = true, + }, @as(libc.mode_t, 0)); + if (file_fd < 0) return -1; + // EXTEND and ATTRIB beside WRITE because an append and a truncate-in-place + // are both saves, and DELETE/RENAME because losing this inode is how a + // rename-over reaches the pane whose file it replaced. + const changes = [_]libc.Kevent{.{ + .ident = @intCast(file_fd), + .filter = libc.EVFILT.VNODE, + .flags = libc.EV.ADD | libc.EV.CLEAR, + .fflags = libc.NOTE.WRITE | libc.NOTE.EXTEND | libc.NOTE.ATTRIB | + libc.NOTE.RENAME | libc.NOTE.DELETE | libc.NOTE.REVOKE, + .data = 0, + .udata = 0, + }}; + var events: [1]libc.Kevent = undefined; + if (libc.kevent(kq, &changes, 1, &events, 0, null) < 0) { + _ = libc.close(file_fd); + return -1; + } + return file_fd; +} + +/// Re-point a live mark's file filter at whatever the pathname is NOW. Called +/// from `reloadPane`, because a rename-over leaves the old filter on an inode +/// that no longer answers to this name and a later in-place save would then +/// wake nobody. A no-op off macos, where the directory mark covers both cases +/// by itself and there is no second filter to move. +fn remarkFile(live: *Watch, path: ?[]const u8) void { + if (comptime builtin.os.tag != .macos) return; + if (live.kq < 0) return; + const watched = filesystem.localPath(path orelse return) orelse return; + var path_buf: [4096:0]u8 = undefined; + if (watched.len >= path_buf.len) return; + @memcpy(path_buf[0..watched.len], watched); + path_buf[watched.len] = 0; + // Mark first, compare second. There is no `stat` in std.c on this target — + // only `fstat` — and opening the path is what tells us both whether it is + // there and which inode it is now. + const fresh = markFile(live.kq, path_buf[0..watched.len :0]); + if (fresh < 0) return; // nothing at that name now; keep whatever we had + if (live.file_wd >= 0) { + var have: libc.Stat = undefined; + var want: libc.Stat = undefined; + // Same inode as the filter already on it? Then that one still reports + // this file and the registration just made is a duplicate to drop. + if (libc.fstat(live.file_wd, &have) == 0 and libc.fstat(fresh, &want) == 0 and + have.dev == want.dev and have.ino == want.ino) + { + _ = libc.close(fresh); + return; + } + _ = libc.close(live.file_wd); + } + live.file_wd = fresh; +} + +/// Drop one slot's marks. The DIRECTORY mark goes only when its last slot is +/// gone — several panes share it — while the file filter has exactly one user +/// and always goes. On macos a filter dies with the descriptor it was +/// registered against, so the close IS the removal. +fn unmark(fd: c_int, old: Watch, drop_dir: bool) void { + if (comptime builtin.os.tag == .macos) { + if (old.file_wd >= 0) _ = libc.close(old.file_wd); + } + if (!drop_dir) return; + switch (builtin.os.tag) { + .linux, .freebsd => _ = libc.inotify_rm_watch(fd, old.wd), + .macos => _ = libc.close(old.wd), + else => {}, + } +} + +/// Mark or unmark the pathname in `slot`: a pane's id, `theme_slot` or a +/// shader's. Panes in the same directory share an inotify descriptor, so +/// removing one pane drops the kernel mark only after its last user +/// disappears. +pub fn watchPane( + fd: c_int, + watches: *Table, + slot: usize, + path: ?[]const u8, + serial: u32, + generation: Generation, +) void { + if (comptime !supported) return; + if (fd < 0) return; + if (watches[slot]) |old| { + var shared = false; + for (watches, 0..) |other, i| { + const candidate = other orelse continue; + if (i != slot and candidate.wd == old.wd) shared = true; + } + watches[slot] = null; + unmark(fd, old, !shared); + } + const declared_path = path orelse return; + const watched_path = filesystem.localPath(declared_path) orelse return; + // The path may lie in a mount this editor serves, and marking it is a + // stat and a lookup out there: the turn goes out with them. + pardes.turn.yield(); + defer pardes.turn.back(); + const stat = @import("core").filesystem.statPath(std.Io.Threaded.global_single_threaded.io(), watched_path, .{}) catch null; + const dir = if (stat != null and stat.?.kind == .directory) watched_path else std.Io.Dir.path.dirname(watched_path) orelse "."; + var dir_buf: [4096:0]u8 = undefined; + if (dir.len >= dir_buf.len) return; + @memcpy(dir_buf[0..dir.len], dir); + dir_buf[dir.len] = 0; + const wd = markDir(fd, dir_buf[0..dir.len :0], watches); + if (wd < 0) return; + watches[slot] = .{ .wd = wd, .kq = fd, .serial = serial, .generation = generation }; + // The file half, which only macos has and only for a path that exists yet. + if (comptime builtin.os.tag == .macos) { + if (watches[slot]) |*live| remarkFile(live, declared_path); + } +} + +/// Every pane's mark dropped (a Restore's old core, a test's end). +pub fn unwatchAll(fd: c_int, watches: *Table) void { + for (0..pardes.MAX_PANES) |id| watchPane(fd, watches, @intCast(id), null, 0, .{ .text = 0 }); +} + +/// Reconcile one marked pane. A true result requests an immediate second pass: +/// a kind's pathname changed between the stat before its pane reopened and +/// the stat after, so committing either identity would lose a generation. +pub fn reloadPane( + core: *pardes.Pardes, + io: std.Io, + watches: *Table, + id: usize, + announce: bool, +) bool { + const watched = watches[id] orelse return false; + const pane = core.panes[id] orelse return false; + if (pane.serial != watched.serial) return false; + + // Re-point the macos file filter at whatever this pathname is now, BEFORE + // deciding anything: a rename-over left the old filter on a dead inode, and + // the next in-place save would otherwise wake nobody. A no-op elsewhere, + // and a no-op here too when the inode has not moved. + if (comptime builtin.os.tag == .macos) { + if (watches[id]) |*live| remarkFile(live, if (pane.file) |f| f.path else kindPath(pane)); + } + + if (pane.file) |file| { + const bytes = filesystem.read(core, file.path) catch |err| { + // Gone from under the pane: said once, the text kept. + if (err == error.FileNotFound and watched.existed == std.hash.Wyhash.hash(0, file.path)) pardes.panes.File.deleted(core, @intCast(id)); + return false; + }; + if (watches[id]) |*live| live.existed = std.hash.Wyhash.hash(0, file.path); + defer core.gpa.free(bytes); + const hash = std.hash.Wyhash.hash(0, bytes); + switch (watched.generation) { + .text => |accepted| if (accepted == hash) return false, + .kind => {}, + } + // The pane holds the disk's text already (a Zerox twin saved, its + // other twin watching the same file): nothing reloaded, nothing said. + if (std.mem.eql(u8, file.content, bytes)) { + if (watches[id]) |*live| if (live.serial == watched.serial) { + live.generation = .{ .text = hash }; + }; + return false; + } + if (!core.reloadWatchedFile(@intCast(id), bytes)) return false; + const current = core.panes[id] orelse return false; + if (current.serial != watched.serial) return false; + const current_file = current.file orelse return false; + if (!std.mem.eql(u8, current_file.content, bytes)) return false; + if (watches[id]) |*live| { + if (live.serial == watched.serial) + live.generation = .{ .text = hash }; + } + if (announce) { + var msg_buf: [256]u8 = undefined; + core.setMessage(id, message.stamp(&msg_buf, "reloaded", current_file.path)); + } + return false; + } + + const path = kindPath(pane) orelse return false; + const before = identify(io, path) catch return false; + switch (watched.generation) { + .kind => |accepted| if (accepted) |identity| { + if (identity.eql(before)) return false; + } else if (sameBytes(core, pane, path)) { + // Armed over the bytes the pane opened: nothing to reload + // (opening it again doubled every PDF's open). Changed between + // the open and the arm, it reloads. + if (watches[id]) |*live| if (live.serial == watched.serial) { + live.generation = .{ .kind = before }; + }; + return false; + }, + .text => {}, + } + // Its kind reads the file again (Kind.fileChanged): on the tape, no bytes. + if (!core.reloadWatchedFile(@intCast(id), &.{})) return false; + const current = core.panes[id] orelse return false; + if (current.serial != watched.serial) return false; + const current_path = kindPath(current) orelse return false; + const after = identify(io, current_path) catch return true; + if (!before.eql(after)) return true; + if (watches[id]) |*live| { + if (live.serial == watched.serial) + live.generation = .{ .kind = after }; + } + if (announce) { + var msg_buf: [256]u8 = undefined; + core.setMessage(id, message.stamp(&msg_buf, "reloaded", current_path)); + } + return false; +} + +/// Install the directory mark before reconciling the open bytes/path. This +/// closes the drain-time race without requiring another filesystem event. +pub fn applyEffect( + core: *pardes.Pardes, + io: std.Io, + fd: c_int, + watches: *Table, + id: u8, + on: bool, + mode: pardes.WatchMode, +) bool { + var path: ?[]const u8 = null; + var serial: u32 = 0; + var generation: Generation = .{ .text = 0 }; + if (on) if (core.panes[id]) |pane| { + serial = pane.serial; + if (pane.file) |file| { + path = file.path; + generation = .{ .text = std.hash.Wyhash.hash(0, file.content) }; + } else if (kindPath(pane)) |kind_path| { + path = kind_path; + generation = .{ .kind = null }; + } + }; + watchPane(fd, watches, id, path, serial, generation); + if (on and mode == .baseline_disk) if (watches[id]) |*watched| { + const pane = core.panes[id] orelse return false; + const file = pane.file orelse return reloadPane(core, io, watches, id, false); + const bytes = filesystem.read(core, file.path) catch return false; + defer core.gpa.free(bytes); + watched.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }; + watched.existed = std.hash.Wyhash.hash(0, file.path); + return false; + }; + // A text armed over its open's bytes, read just now (its content that + // read's very buffer, unedited): the file still what it was before that + // read (the same inode, size and times) needs no reading again. + if (on) if (watches[id]) |*watched| if (core.panes[id]) |pane| if (pane.file) |file| if (filesystem.localPath(file.path)) |native| { + const at = std.hash.Wyhash.hash(0, native); + for (filesystem.last_reads) |r| if (r.path == at and r.bytes == file.content.ptr and r.len == file.content.len and file.revision == 0) { + const now = identify(io, file.path) catch break; + if (!now.eql(r.file)) break; + watched.existed = std.hash.Wyhash.hash(0, file.path); + return false; + }; + }; + return on and watches[id] != null and reloadPane(core, io, watches, id, false); +} + +/// Reconcile every mark after a coalesced directory wake. +pub fn reloadChanged( + core: *pardes.Pardes, + io: std.Io, + gpa: std.mem.Allocator, + watches: *Table, +) bool { + var retry = false; + for (watches[0..pardes.MAX_PANES], 0..) |slot, id| { + if (slot != null) retry = reloadPane(core, io, watches, id, true) or retry; + } + if (watches[theme_slot] != null) + retry = reloadTheme(core, gpa, watches, true) or retry; + return retry; +} + +/// Stop the old theme watch, synchronously load the requested snapshot, then +/// install its parent-directory mark and reconcile once to close the read -> +/// watch race. Returns true only when that reconciliation wants another pass. +pub fn applyThemeEffect( + core: *pardes.Pardes, + gpa: std.mem.Allocator, + fd: c_int, + watches: *Table, + generation: u32, + on: bool, +) bool { + watchPane(fd, watches, theme_slot, null, 0, .{ .text = 0 }); + if (!on) return false; + const request = colors.themeFileRequest(core, generation) orelse return false; + // What fails here is the ThemeFile write's failure too, which waits on + // this (the one-failure rule): late, as a Save's. + const pane = request.pane; + const bytes = filesystem.readFile(gpa, request.path) catch |err| { + colors.failThemeFile(core, generation, err); + core.noteLateFailure(pane); + return false; + }; + defer gpa.free(bytes); + if (!colors.loadThemeFile(core, generation, bytes)) { + core.noteLateFailure(pane); + return false; + } + const hash = std.hash.Wyhash.hash(0, bytes); + watchPane(fd, watches, theme_slot, request.path, generation, .{ .text = hash }); + if (watches[theme_slot] == null) return false; + return reloadTheme(core, gpa, watches, false); +} + +/// Re-read the one active theme file after a coalesced directory edge. The +/// generation advances only after a valid parse, so a malformed save never +/// replaces the last good colors or blesses bad bytes as the new baseline. +pub fn reloadTheme( + core: *pardes.Pardes, + gpa: std.mem.Allocator, + watches: *Table, + announce: bool, +) bool { + const watched = watches[theme_slot] orelse return false; + const request = colors.themeFileRequest(core, watched.serial) orelse return false; + // Same re-arm as reloadPane's, for the same reason: a .zon saved by rename + // moves the inode the file filter is on. + if (comptime builtin.os.tag == .macos) { + if (watches[theme_slot]) |*entry| remarkFile(entry, request.path); + } + const bytes = filesystem.readFile(gpa, request.path) catch |err| { + core.invalidate(); + colors.failThemeFile(core, watched.serial, err); + return false; + }; + defer gpa.free(bytes); + const hash = std.hash.Wyhash.hash(0, bytes); + switch (watched.generation) { + .text => |accepted| if (accepted == hash) return false, + .kind => unreachable, + } + if (!colors.loadThemeFile(core, watched.serial, bytes)) return false; + core.invalidate(); + const live = if (watches[theme_slot]) |*entry| entry else return false; + if (live.serial != watched.serial) return false; + live.generation = .{ .text = hash }; + if (announce) { + var msg_buf: [256]u8 = undefined; + core.setMessage(request.pane, message.stamp(&msg_buf, "reloaded theme", request.path)); + } + return false; +} + +pub fn identify(io: std.Io, path: []const u8) !Identity { + const native = filesystem.localPath(path) orelse return error.NonLocalPath; + pardes.turn.yield(); + defer pardes.turn.back(); + const stat = try @import("core").filesystem.statPath(io, native, .{}); + if (stat.kind != .file) return error.NotFile; + return .{ + .inode = stat.inode, + .size = stat.size, + .mtime_ns = stat.mtime.nanoseconds, + .ctime_ns = stat.ctime.nanoseconds, + }; +} + +test "a restored file is watched again: one clean takes what its file became since the dump, one unsaved keeps its text" { + if (comptime !supported or !filesystem.platform_has_fs) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + for ([_]bool{ false, true }) |dirty| { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "dumped\n" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); + const source = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer source.deinit(); + const id: u8 = @intCast(source.freeSlot().?); + const opened = try pardes.panes.File.open(source, id, path, 0); + if (dirty) _ = pardes.ctlfs.pane.spliceBody(source, opened, 0, 0, "unsaved ").?; + try pardes.dump.dumpState(source); + // Changed on disk between the dump and its load. + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "changed since\n" }); + const core = try pardes.dump.initFromDump(gpa, .{ .tty_only = true }, source.dump_out.?); + defer core.deinit(); + const pane = core.panes[id].?; + const fd = init(true); + if (fd < 0) return error.NoWatcher; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer watchPane(fd, &watches, id, null, pane.serial, .{ .text = 0 }); + var armed = false; + while (core.nextEffect()) |effect| switch (effect) { + .watch => |watch| if (watch.pane == id and watch.on) { + _ = applyEffect(core, io, fd, &watches, id, watch.on, watch.mode); + armed = true; + }, + else => {}, + }; + try std.testing.expect(armed and watches[id] != null); + if (dirty) { + try std.testing.expectEqualStrings("unsaved dumped\n", pane.file.?.content); + try std.testing.expect(pane.file.?.disk_newer != null); + } else try std.testing.expectEqualStrings("changed since\n", pane.file.?.content); + } +} + +test "a Zerox twin's save wakes its other twin's watch, which says nothing: their text is the file's already" { + if (comptime !supported or !filesystem.platform_has_fs) return; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "twinned", .data = "before\n" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/twinned", .{tmp.sub_path}); + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("before\n"); + core.gpa.free(pane.file.?.path); + pane.file.?.path = try core.gpa.dupe(u8, path); + try std.testing.expect(core.executeBuiltinLine(0, "Zerox")); + const twin: u8 = for (core.panes, 0..) |slot, id| { + if (id != 0) if (slot) |other| if (other.file != null) break @intCast(id); + } else return error.NoTwin; + const fd = init(true); + if (fd < 0) return error.NoWatcher; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer watchPane(fd, &watches, twin, null, core.panes[twin].?.serial, .{ .text = 0 }); + watchPane(fd, &watches, twin, path, core.panes[twin].?.serial, .{ .text = std.hash.Wyhash.hash(0, "before\n") }); + // Edited in the first and saved: the file is the twins' text now. + pardes.panes.File.setContent(core, &pane.file.?, try core.gpa.dupe(u8, "after\n")); + try tmp.dir.writeFile(io, .{ .sub_path = "twinned", .data = "after\n" }); + _ = reloadPane(core, io, &watches, twin, true); + const other = core.panes[twin].?; + try std.testing.expect(std.mem.indexOf(u8, other.msg[0..other.msg_len], "reloaded") == null); + try std.testing.expectEqualStrings("after\n", other.file.?.content); +} + +test "ordinary file watches still reconcile changes between open and watch" { + if (comptime !supported or !filesystem.platform_has_fs) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "opened\n" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id: u8 = @intCast(core.freeSlot().?); + const pane = try pardes.panes.File.open(core, id, path, 0); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "changed before watch\n" }); + const fd = init(true); + if (fd < 0) return error.NoWatcher; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer watchPane(fd, &watches, id, null, pane.serial, .{ .text = 0 }); + var armed = false; + while (core.nextEffect()) |effect| switch (effect) { + .watch => |watch| if (watch.pane == id and watch.on) { + try std.testing.expectEqual(.reconcile, watch.mode); + try std.testing.expect(!applyEffect(core, io, fd, &watches, id, watch.on, watch.mode)); + armed = true; + }, + else => {}, + }; + try std.testing.expect(armed and watches[id] != null); + try std.testing.expectEqualStrings("changed before watch\n", pane.file.?.content); + try pardes.panes.File.undoStep(core, pane, true); + try std.testing.expectEqualStrings("opened\n", pane.file.?.content); +} + +test "a kind's pane whose file changed between its open and its watch opens again from it" { + if (comptime !supported or !filesystem.platform_has_fs) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "pic.ppm", .data = "opened\n" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/pic.ppm", .{tmp.sub_path}); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const id: u8 = @intCast(core.freeSlot().?); + _ = try pardes.Kind.open(core, id, pardes.Kind.test_kind.of(core), path, "opened\n"); + while (core.nextEffect()) |_| {} + const fd = init(true); + if (fd < 0) return error.NoWatcher; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer unwatchAll(fd, &watches); + // The file as it opened: armed, nothing opened again. + try std.testing.expect(!applyEffect(core, io, fd, &watches, id, true, .reconcile)); + try std.testing.expectEqual(std.hash.Wyhash.hash(0, "opened\n"), core.panes[id].?.addon.?.opened); + // Changed before the watch arms: opened again from it. + try std.testing.expect(!applyEffect(core, io, fd, &watches, id, false, .reconcile)); + try tmp.dir.writeFile(io, .{ .sub_path = "pic.ppm", .data = "changed before watch\n" }); + try std.testing.expect(!applyEffect(core, io, fd, &watches, id, true, .reconcile)); + try std.testing.expectEqual(std.hash.Wyhash.hash(0, "changed before watch\n"), core.panes[id].?.addon.?.opened); +} + +test "explicit OS directory watches refresh prefix-preserving listings" { + if (comptime !supported or !filesystem.platform_has_fs) return; + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "first", .data = "first\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; + var path_buf: [4102]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/n/os{s}", .{directory}); + const pane_id = core.freeSlot().?; + const pane = try pardes.panes.File.open(core, pane_id, path, 0); + const fd = init(true); + if (fd < 0) return error.NoWatcher; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer watchPane(fd, &watches, @intCast(pane_id), null, pane.serial, .{ .text = 0 }); + _ = applyEffect(core, std.testing.io, fd, &watches, @intCast(pane_id), true, .reconcile); + try std.testing.expect(watches[pane_id] != null); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "second", .data = "second\n" }); + _ = reloadChanged(core, std.testing.io, gpa, &watches); + try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "/second\n") != null); + var rows = std.mem.tokenizeScalar(u8, pane.file.?.content, '\n'); + while (rows.next()) |row| { + try std.testing.expect(std.mem.startsWith(u8, row, path)); + const bytes = try filesystem.read(core, row); + defer gpa.free(bytes); + try std.testing.expect(std.mem.endsWith(u8, bytes, "\n")); + } +} + +test "file identity changes for in-place and rename-over writes" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "a" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); + const before = try identify(io, path); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "longer" }); + const after = try identify(io, path); + try std.testing.expect(!before.eql(after)); + + // The dominant editor save shape keeps size/content arbitrary but swaps + // the inode. Keep this replacement the same length to prove identity does + // not rely on size changing. + try tmp.dir.writeFile(io, .{ .sub_path = "replacement", .data = "swap!!" }); + try tmp.dir.rename("replacement", tmp.dir, "watched", io); + const replaced = try identify(io, path); + try std.testing.expect(after.inode != replaced.inode); + try std.testing.expect(!after.eql(replaced)); +} + +test "theme watch reloads valid ZON and keeps the last theme across a bad save" { + if (comptime !supported) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const base_len = try tmp.dir.realPath(io, &base_buf); + const path = try std.Io.Dir.path.join(gpa, &.{ base_buf[0..base_len], "mine.zon" }); + defer gpa.free(path); + + var first = pardes.themes[0]; + first.name = "watched"; + first.bg = .{ 1, 2, 3 }; + var first_zon: std.Io.Writer.Allocating = .init(gpa); + defer first_zon.deinit(); + try std.zon.stringify.serialize(first, .{ .whitespace = true }, &first_zon.writer); + try tmp.dir.writeFile(io, .{ .sub_path = "mine.zon", .data = first_zon.written() }); + + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + colors.requestThemeFile(core, 0, path); + const request = while (core.nextEffect()) |effect| switch (effect) { + .theme_file => |theme_file| break theme_file, + else => {}, + } else return error.MissingThemeFileEffect; + + const fd = init(true); + if (fd < 0) return error.WatchInitFailed; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer _ = applyThemeEffect(core, gpa, fd, &watches, 0, false); + try std.testing.expect(!applyThemeEffect( + core, + gpa, + fd, + &watches, + request.generation, + true, + )); + try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), core.theme().bg); + try std.testing.expect(watches[theme_slot] != null); + + var second = first; + second.bg = .{ 9, 8, 7 }; + var second_zon: std.Io.Writer.Allocating = .init(gpa); + defer second_zon.deinit(); + try std.zon.stringify.serialize(second, .{ .whitespace = true }, &second_zon.writer); + try tmp.dir.writeFile(io, .{ .sub_path = "mine.zon", .data = second_zon.written() }); + try std.testing.expect(!reloadTheme(core, gpa, &watches, false)); + try std.testing.expectEqual(@as(?[3]u8, .{ 9, 8, 7 }), core.theme().bg); + + try tmp.dir.writeFile(io, .{ .sub_path = "mine.zon", .data = ".{ .name = " }); + try std.testing.expect(!reloadTheme(core, gpa, &watches, false)); + try std.testing.expectEqual(@as(?[3]u8, .{ 9, 8, 7 }), core.theme().bg); +} + +test "a watched file deleted wakes the watch at once, and its pane says so" { + if (comptime !supported or !filesystem.platform_has_fs or builtin.os.tag != .linux) return; + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "here\n" }); + var path_buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id: u8 = @intCast(core.freeSlot().?); + const pane = try pardes.panes.File.open(core, id, path, 0); + const fd = init(true); + if (fd < 0) return error.NoWatcher; + defer _ = libc.close(fd); + var watches: Table = @splat(null); + defer watchPane(fd, &watches, id, null, pane.serial, .{ .text = 0 }); + while (core.nextEffect()) |effect| switch (effect) { + .watch => |watch| if (watch.pane == id and watch.on) { + _ = applyEffect(core, io, fd, &watches, id, watch.on, watch.mode); + }, + else => {}, + }; + _ = drain(fd); + try tmp.dir.deleteFile(io, "watched"); + var pfd = [_]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }}; + try std.testing.expect(libc.poll(&pfd, 1, 1000) > 0); + _ = reloadChanged(core, io, gpa, &watches); + try std.testing.expect(pane.file.?.disk_gone); +} diff --git a/dev/fonts.zig b/dev/fonts.zig new file mode 100644 index 00000000..540e3a60 --- /dev/null +++ b/dev/fonts.zig @@ -0,0 +1,436 @@ +//! The fonts installed on the machine: the list the picker shows (Output.zig), +//! the path a `Font ` resolves to (exec.zig), and the fallback faces a +//! window loads after its own (gui.zig, macos.zig). It is the whole seam, +//! because the core has no font and the shells have no builtin dispatch. +//! +//! It lives at src/ rather than under gui/ because two shells draw their own +//! text. It is compiled only behind `pardes.font_picker` (gui or macos), so +//! the tui binary never opens a font directory, and the browser has none to +//! open. +//! +//! No fontconfig and no CoreText. Enumerating fonts is a walk over a handful +//! of well-known directories, and the one thing the picker must know about +//! each face — whether every glyph has the same advance — is three small sfnt +//! reads. That avoids initializing a FreeType face for every file in the +//! directory, and it keeps the answer identical on both platforms: the shells +//! disagree about how to RASTERIZE a file, never about which files there are. +const std = @import("std"); +const builtin = @import("builtin"); +/// libc: the tests' scratch fonts, written raw into /tmp. +const libc = std.c; + +/// Where each platform keeps fonts. The `home` list is relative to $HOME (a +/// machine with no $HOME simply has neither). ponytail: the unix set is the +/// freedesktop list minus /usr/share/X11/fonts, whose legacy bitmap formats +/// are outside this TTF/OTF picker; XDG_DATA_DIRS is the general answer if +/// another font root becomes common. +/// +/// macOS keeps a third of its faces — Menlo and Courier among them — inside +/// `Supplemental`, which is an ordinary directory the walk would reach anyway; +/// it is named because the depth cap is the only thing that would stop it. +const system_dirs = switch (builtin.os.tag) { + .macos => [_][]const u8{ "/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts" }, + else => [_][]const u8{ "/usr/share/fonts", "/usr/local/share/fonts" }, +}; +const home_dirs = switch (builtin.os.tag) { + .macos => [_][]const u8{"Library/Fonts"}, + else => [_][]const u8{ ".local/share/fonts", ".fonts" }, +}; + +/// The same safety rails look.find has, for the same reason: this walk runs +/// INSIDE the keystroke that asked for it, so it must end whatever it is +/// pointed at. A font tree is shallow and wide (one directory per family), so +/// the depth cap is lower than find's. +/// +/// `max_fonts` is a MEMORY bound and nothing else (the work is bounded by +/// `max_steps`), and it is sized past any real machine: a desktop with the +/// Noto and Nerd Font sets has nearly a thousand monospace faces, and the list +/// is sorted AFTER the cut, so a cut list reads as complete with faces missing +/// out of its middle. +const max_fonts = 4096; +const max_steps = 20_000; +const max_depth = 8; + +pub const Font = struct { name: []const u8, path: []const u8 }; + +/// Optional fallback faces, in preference order after the always-available +/// embedded Adwaita Mono face. Keep text faces before symbol faces so ordinary +/// letters retain terminal-like metrics; DejaVu Sans is the final broad, +/// proportional safety net. +pub const fallback_names = [_][]const u8{ + "NotoSansMono-Regular", + "DejaVuSansMono", + "SymbolsNerdFont-Regular", + "NotoSansSymbols2-Regular", + "NotoSansSymbols-Regular", + "DejaVuSans", +}; + +/// Every monospace font installed, `{name, path}`, arena-owned and sorted by +/// name — or, when `want_name` is given, just the one that answers to it. +pub fn list(arena: std.mem.Allocator, want_name: ?[]const u8) []const Font { + if (want_name) |name| { + const wanted = [1][]const u8{name}; + return scan(arena, &wanted, true); + } + return scan(arena, null, true); +} + +/// The session's config's absolute font path belongs to the session's machine. +/// Resolve the same face by name on this machine, retaining the filename as a fallback. +pub fn fromSession(arena: std.mem.Allocator, path: []const u8, name: []const u8) ?Font { + if (name.len > 0) { + const matches = list(arena, name); + if (matches.len > 0) return matches[0]; + } + const base = std.Io.Dir.path.basename(path); + const stem = base[0 .. base.len - std.Io.Dir.path.extension(base).len]; + if (stem.len == 0 or std.mem.eql(u8, stem, name)) return null; + const matches = list(arena, stem); + return if (matches.len > 0) matches[0] else null; +} + +/// Installed members of `fallback_names`, returned in preference order. This +/// is runtime discovery only: no local font path or exploration result enters +/// the build, and a machine with none simply uses embedded Adwaita Mono. +pub fn fallbacks(arena: std.mem.Allocator) []const Font { + return scan(arena, &fallback_names, false); +} + +/// One bounded directory walk for the picker, one named font, or the fallback +/// chain. User-facing lists always require a fixed-pitch face, including an +/// exact `Font ` request. The fallback chain opts out deliberately so a +/// broad symbol face may fill glyphs the primary grid face does not contain. +fn scan( + arena: std.mem.Allocator, + wanted: ?[]const []const u8, + require_monospaced: bool, +) []const Font { + // From the arena, not the stack: 4096 faces of {name, path} is 128 KiB. An + // allocator that cannot spare it answers with the embedded face, like + // every other failure in here. + const found = arena.alloc(Font, max_fonts) catch return &.{}; + var found_len: usize = 0; + // The blocking single-threaded Io: the walk is synchronous, inside the + // keystroke, as look.find's is. + const io = std.Io.Threaded.global_single_threaded.io(); + const home: []const u8 = if (libc.getenv("HOME")) |h| std.mem.span(h) else ""; + var root_buf: [512]u8 = undefined; + var path_buf: [4096]u8 = undefined; + roots: for (0..system_dirs.len + home_dirs.len) |i| { + const root: []const u8 = if (i < system_dirs.len) + system_dirs[i] + else if (home.len == 0) + continue + else + std.fmt.bufPrint(&root_buf, "{s}/{s}", .{ std.mem.trimEnd(u8, home, "/"), home_dirs[i - system_dirs.len] }) catch continue; + var dir = std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }) catch continue; + defer dir.close(io); + // walkSelectively, not walk: descending is opt-in, which is the only + // way to express the depth cap at all (look.find, same reason) + var w = dir.walkSelectively(arena) catch continue; + defer w.deinit(); + var steps: usize = 0; + while (steps < max_steps and found_len < found.len) { + steps += 1; // an unreadable dir burns a step too, so it cannot spin + const e = (w.next(io) catch continue) orelse break; + if (e.kind == .directory) { + if (e.depth() < max_depth) w.enter(io, e) catch {}; + continue; + } + const ext = std.Io.Dir.path.extension(e.basename); + // .ttc is a collection: several cuts of one family in a single + // file, which is how macOS ships Menlo, Courier and a third of + // everything else. The probe below reads face 0 out of one, and + // the shell loading it takes the same face — see tableOffset. + if (!std.ascii.eqlIgnoreCase(ext, ".ttf") and + !std.ascii.eqlIgnoreCase(ext, ".otf") and + !std.ascii.eqlIgnoreCase(ext, ".ttc")) continue; + const name = e.basename[0 .. e.basename.len - ext.len]; + if (wanted) |names| { + var matches = false; + for (names) |candidate| { + if (std.mem.eql(u8, candidate, name)) { + matches = true; + break; + } + } + if (!matches) continue; + for (found[0..found_len]) |prior| { + if (std.mem.eql(u8, prior.name, name)) { + matches = false; + break; + } + } + if (!matches) continue; + } + // e.path points into the walker's own buffer and dies at the next + // next(), so the path is spelled out here and copied below + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ root, e.path }, 0) catch continue; + if (require_monospaced and !monospaced(io, path)) continue; + found[found_len] = .{ + .name = arena.dupe(u8, name) catch break, + .path = arena.dupe(u8, path) catch break, + }; + found_len += 1; + if (wanted) |names| { + if (names.len == 1) return arena.dupe(Font, found[0..found_len]) catch &.{}; + if (found_len == names.len) break :roots; + } + } + } + if (wanted) |names| { + std.mem.sort(Font, found[0..found_len], names, struct { + fn rank(order: []const []const u8, name: []const u8) usize { + for (order, 0..) |candidate, i| + if (std.mem.eql(u8, candidate, name)) return i; + return order.len; + } + fn lt(order: []const []const u8, a: Font, b: Font) bool { + return rank(order, a.name) < rank(order, b.name); + } + }.lt); + } else { + // readdir order is undefined; sort so the picker is the same list twice + // running and n/N walks a font's own variants in a row + std.mem.sort(Font, found[0..found_len], {}, struct { + fn lt(_: void, a: Font, b: Font) bool { + return std.mem.lessThan(u8, a.name, b.name); + } + }.lt); + } + return arena.dupe(Font, found[0..found_len]) catch &.{}; +} + +/// Is every glyph in this font the same width? The grid is one advance for +/// every column, chosen once from 'M', so a proportional font in it has every +/// row a different length and the mouse pointing at the wrong character: the +/// picker lists only the faces that can be worn. +/// +/// Three reads and no allocation, which is why the walk can afford it per file: +/// the sfnt header and table directory, then `hhea`'s numberOfHMetrics, then +/// the start of `hmtx` — one {advance, lsb} pair per glyph. A font whose first +/// advances all agree is monospace. Zeros are skipped: .notdef and the +/// combining marks legitimately advance nothing, in any font. +/// +/// ponytail: the first 64 metrics, not all of them, so this is one 256-byte +/// read whatever the font's size. Those cover .notdef and the whole of basic +/// latin — the range a terminal is actually worn in — which also (deliberately) +/// keeps the CJK mono faces whose *later* glyphs are double-width, exactly the +/// fonts fontconfig calls "dual-width" and refuses. +fn monospaced(io: std.Io, path: []const u8) bool { + const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return false; + defer file.close(io); + // 12-byte header + one 16-byte record per table; 256 records is far more + // than any real font carries + var head: [12 + 16 * 256]u8 = undefined; + const n = file.readPositionalAll(io, &head, 0) catch return false; + if (n < 12) return false; + const hhea = tableOffset(head[0..n], "hhea") orelse return false; + const hmtx = tableOffset(head[0..n], "hmtx") orelse return false; + var hh: [36]u8 = undefined; + if ((file.readPositionalAll(io, &hh, hhea) catch return false) != hh.len) return false; + const metrics = std.mem.readInt(u16, hh[34..36], .big); + const k: usize = @min(@as(usize, metrics), 64); + if (k == 0) return false; + var mx: [64 * 4]u8 = undefined; + if ((file.readPositionalAll(io, mx[0 .. k * 4], hmtx) catch return false) != k * 4) return false; + var ref: u16 = 0; + for (0..k) |i| { + const adv = std.mem.readInt(u16, mx[i * 4 ..][0..2], .big); + if (adv == 0) continue; + if (ref == 0) ref = adv else if (adv != ref) return false; + } + return ref != 0; +} + +/// Where `tag`'s table starts, read out of an sfnt table directory. Called +/// twice per font, which is the only reason it is not inline up there. +fn tableOffset(head: []const u8, tag: *const [4]u8) ?u32 { + const dir = head[sfntBase(head) orelse return null ..]; + if (dir.len < 12) return null; + // 0x00010000 TrueType outlines, "OTTO" CFF ones, "true" the old Apple + // spelling. Anything else — a WOFF, a lie about its extension — is not an + // sfnt face this picker can inspect. + const ver = std.mem.readInt(u32, dir[0..4], .big); + if (ver != 0x00010000 and ver != 0x4F54544F and ver != 0x74727565) return null; + const num = std.mem.readInt(u16, dir[4..6], .big); + var i: usize = 0; + while (i < num and 12 + (i + 1) * 16 <= dir.len) : (i += 1) { + const rec = dir[12 + i * 16 ..][0..16]; + // Table offsets in a collection are from the start of the FILE, not + // from the directory that named them, so this needs no adjusting. + if (std.mem.eql(u8, rec[0..4], tag)) return std.mem.readInt(u32, rec[8..12], .big); + } + return null; +} + +/// Where the sfnt table directory begins. Zero for an ordinary font file; for +/// a `ttcf` collection, the offset of face 0 — the cut the file is named +/// after, and the one a shell asked for this path will load. A collection +/// whose first face lies past what was read has no answer here rather than a +/// guessed one. +fn sfntBase(head: []const u8) ?usize { + if (head.len < 12) return null; + if (!std.mem.eql(u8, head[0..4], "ttcf")) return 0; + if (head.len < 16) return null; + if (std.mem.readInt(u32, head[8..12], .big) == 0) return null; // numFonts + const base = std.mem.readInt(u32, head[12..16], .big); + return if (base + 12 <= head.len) base else null; +} + +/// A scratch font path only this process writes. Not a fixed name: `zig build +/// unit-test` compiles this module into two test binaries and runs them +/// CONCURRENTLY, so a shared path in /tmp is one test truncating the file +/// another is halfway through reading. +fn scratchFont(buf: *[64:0]u8, ext: []const u8) [:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "/tmp/pardes-fonts-test-{d}{s}", .{ + @as(u32, @intCast(libc.getpid())), ext, + // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 + }, 0) catch unreachable; +} + +/// Write `bytes` where `monospaced` can read them back. +fn writeScratch(path: [:0]const u8, bytes: []const u8) !void { + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(c_uint, 0o600)); + try std.testing.expect(fd >= 0); + defer _ = libc.close(fd); + try std.testing.expectEqual(@as(isize, @intCast(bytes.len)), libc.write(fd, bytes.ptr, bytes.len)); +} + +test "fallback discovery is unique and preserves candidate priority" { + for (fallback_names, 0..) |name, i| { + try std.testing.expect(name.len != 0); + for (fallback_names[0..i]) |prior| + try std.testing.expect(!std.mem.eql(u8, prior, name)); + } + + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const installed = fallbacks(arena_state.allocator()); + var previous: ?usize = null; + for (installed) |font| { + const rank = for (fallback_names, 0..) |name, i| { + if (std.mem.eql(u8, name, font.name)) break i; + } else return error.UnknownFallback; + if (previous) |p| try std.testing.expect(rank > p); + previous = rank; + } +} + +test "the picker lists every monospace face rather than the first max_fonts" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const installed = list(arena_state.allocator(), null); + // A canary, and only meaningful on a machine that HAS fonts: reaching the + // cap is the silent cut max_fonts is sized against. + try std.testing.expect(installed.len < max_fonts); + // ...and what it does return is sorted. + for (installed, 0..) |font, i| { + try std.testing.expect(font.name.len != 0); + if (i > 0) try std.testing.expect(!std.mem.lessThan(u8, font.name, installed[i - 1].name)); + } +} + +test "monospaced reads the advances out of a real sfnt layout" { + // A whole font in 92 bytes: the header, a two-record table directory, and + // an hhea + hmtx that between them say "three glyphs, all 600 units wide". + // Everything a real .ttf has that this does not (glyf, cmap, name) is + // exactly what the probe never reads, which is the property under test. + var f: [92]u8 = @splat(0); + std.mem.writeInt(u32, f[0..4], 0x00010000, .big); // sfnt version + std.mem.writeInt(u16, f[4..6], 2, .big); // numTables + @memcpy(f[12..16], "hhea"); + std.mem.writeInt(u32, f[20..24], 44, .big); // hhea at 44, 36 bytes long + @memcpy(f[28..32], "hmtx"); + std.mem.writeInt(u32, f[36..40], 80, .big); // hmtx right after it + std.mem.writeInt(u16, f[44 + 34 ..][0..2], 3, .big); // numberOfHMetrics + for (0..3) |i| std.mem.writeInt(u16, f[80 + i * 4 ..][0..2], 600, .big); + + var path_buf: [64:0]u8 = undefined; + const path = scratchFont(&path_buf, ".ttf"); + defer _ = libc.unlink(path); + try writeScratch(path, &f); + try std.testing.expect(monospaced(std.testing.io, path)); + + // ...and one glyph a different width makes it proportional + std.mem.writeInt(u16, f[80 + 4 ..][0..2], 1200, .big); + try writeScratch(path, &f); + try std.testing.expect(!monospaced(std.testing.io, path)); +} + +test "a ttc collection is read through its first face" { + // The same 92-byte font as above, moved 20 bytes down the file behind a + // `ttcf` header naming two faces. Table offsets stay absolute, which an + // "add the base" would silently break. + const base = 20; + var f: [base + 92]u8 = @splat(0); + @memcpy(f[0..4], "ttcf"); + std.mem.writeInt(u16, f[4..6], 1, .big); // majorVersion + std.mem.writeInt(u32, f[8..12], 2, .big); // numFonts + std.mem.writeInt(u32, f[12..16], base, .big); // face 0 lives here + std.mem.writeInt(u32, f[16..20], base, .big); // face 1, same tables + + const sfnt = f[base..]; + std.mem.writeInt(u32, sfnt[0..4], 0x00010000, .big); + std.mem.writeInt(u16, sfnt[4..6], 2, .big); + @memcpy(sfnt[12..16], "hhea"); + std.mem.writeInt(u32, sfnt[20..24], base + 44, .big); + @memcpy(sfnt[28..32], "hmtx"); + std.mem.writeInt(u32, sfnt[36..40], base + 80, .big); + std.mem.writeInt(u16, sfnt[44 + 34 ..][0..2], 3, .big); + for (0..3) |i| std.mem.writeInt(u16, sfnt[80 + i * 4 ..][0..2], 600, .big); + + var path_buf: [64:0]u8 = undefined; + const path = scratchFont(&path_buf, ".ttc"); + defer _ = libc.unlink(path); + try writeScratch(path, &f); + try std.testing.expect(monospaced(std.testing.io, path)); + + // A collection claiming no faces has no first one to read. + std.mem.writeInt(u32, f[8..12], 0, .big); + try writeScratch(path, &f); + try std.testing.expect(!monospaced(std.testing.io, path)); +} + +test "the walk finds this machine's monospace faces" { + // Not a fixture: the directory list is the entire platform-specific part + // of this file, and a wrong one produces an empty picker rather than an + // error. Every OS pardes draws its own text on ships a monospace face, so + // finding NONE means the walk is looking somewhere that does not exist. + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const found = list(arena_state.allocator(), null); + try std.testing.expect(found.len > 0); + for (found) |font| { + try std.testing.expect(font.name.len > 0); + try std.testing.expect(font.path[0] == '/'); + // The name is the stem, so the file it came from is always longer. + try std.testing.expect(std.Io.Dir.path.basename(font.path).len > font.name.len); + } + + // macOS ships Menlo, and ships it inside a .ttc. It is the one face this + // machine can be held to by name, and naming it here is what keeps the + // collection branch honest end to end: drop .ttc from the walk, or read a + // collection's directory at offset 0, and this is what notices. + if (comptime builtin.os.tag == .macos) { + const menlo = for (found) |font| { + if (std.mem.eql(u8, font.name, "Menlo")) break font; + } else return error.MenloMissing; + try std.testing.expect(std.mem.endsWith(u8, menlo.path, ".ttc")); + } +} + +test "the session's font config resolves the installed face despite another machine's path" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const alloc = arena.allocator(); + const installed = list(alloc, null); + if (installed.len == 0) return error.SkipZigTest; + const face = installed[0]; + const foreign = try std.fmt.allocPrint(alloc, "/other-machine/fonts/{s}", .{std.Io.Dir.path.basename(face.path)}); + const by_name = fromSession(alloc, foreign, face.name) orelse return error.MissingLocalFace; + try std.testing.expectEqualStrings(face.path, by_name.path); + const by_file = fromSession(alloc, foreign, "") orelse return error.MissingLocalFace; + try std.testing.expectEqualStrings(face.path, by_file.path); +} diff --git a/dev/glide.zig b/dev/glide.zig new file mode 100644 index 00000000..711acb22 --- /dev/null +++ b/dev/glide.zig @@ -0,0 +1,466 @@ +//! The view's glide (G6, anim 3, 9, 12): a frontend's own picture of a +//! scroll, on its own clock, from the frames it draws alone. Whatever +//! scrolls a text (a wheel's lines, Ctrl-d, a page, G, n, a Look) scrolls +//! the core at once, so every key and click acts on where the text is; the +//! frontend sees a body's first line move between two frames (Region.line) +//! and its picture follows there, critically damped (text never passes its +//! mark), every distance on the same law. The GUI draws it at the pixel; +//! the tty at whole rows (tui.zig's glideRows). Nothing here reaches back +//! into the core. + +const std = @import("std"); +const pardes = @import("core"); +const config = @import("core").config; + +/// How far the rows moved is measured on the frame against the last drawn, +/// a line wrapped over several rows or a terminal's output included, and +/// the rows that left are kept to draw in the gap. A move past what the two +/// frames share (a page and more, G) has no rows between them to show: the +/// picture comes from the last frame's body as if it lay just past the new +/// one, one body away, so a jump of any length reads as one body's slide. +/// +/// The picture's motion is one system with its own state, integrated in +/// one place every frame (`Follow.advance`), and every scroll, whatever +/// made it, is an input into it (`Follow.kick`): it moves the target by the +/// rows the core moved and leaves the motion as it is. Inputs coming as a +/// stream (each like the last, at a steady spacing: a held key, a spun +/// wheel) feed it at the stream's own rate; an input into a resting view, +/// or against the way it moves, starts the spring from the speed it has; a +/// jump mid-glide adds its rows with the speed kept. +pub const Glide = struct { + /// The picture's lag behind the core's rows and its motion (rows). + follow: Follow = .{}, + now_ns: u64 = 0, + pane: usize = 0, + rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, + body_y: u16 = 0, + body_h: u16 = 0, + /// The way the last scroll went, and the body's rows before it. + dir: i8 = 0, + before: []pardes.Cell = &.{}, + /// The rows past the body's top (`above`) and bottom (`below`), nearest + /// first, `bw` cells each: what the gap shows while the picture lags. + above: []pardes.Cell = &.{}, + below: []pardes.Cell = &.{}, + nabove: u16 = 0, + nbelow: u16 = 0, + /// The core's lines a scroll moved, not yet measured; and what the + /// glide in flight has moved, in lines and in the picture's rows. A + /// wrapped line is several rows, and the thumb counts lines. + pending_lines: f32 = 0, + lines_moved: f32 = 0, + rows_moved: f32 = 0, + /// The caret's row as the last frame drew it, and whether the move + /// measured carried it with its line (a wheel's) or left it on its row + /// (a page, a held key's): the tty draws a carried caret with the rows. + caret_row: ?u16 = null, + caret_rides: bool = false, + /// Each body as the last frame showed it, by its pane: its serial, + /// first line, text and place, so a view that moved since is found + /// whatever moved it. + seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), + /// Each body's rows held at its top while it scrolls (a source's + /// sticky context rows, TreeContext), its frontend's to say: they do + /// not move, so a move is measured, and the rows that left are kept, + /// below them. + held: [pardes.MAX_PANES]u16 = @splat(0), + /// The last frame's cells, which a move is measured against. + last: []pardes.Cell = &.{}, + last_cols: u16 = 0, + last_rows: u16 = 0, + + /// The rows kept past each edge, in bodies, so a jump made while one + /// glides carries on from where it is: as far as the picture may lag. + pub const reach = Follow.reach; + + pub fn moving(glide: *const Glide) bool { + return glide.follow.moving(); + } + + pub fn stop(glide: *Glide) void { + glide.follow = .{ .at_ns = glide.follow.at_ns }; + glide.nabove = 0; + glide.nbelow = 0; + glide.pending_lines = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; + } + + /// The glide's lag in the core's lines: its rows, scaled by the lines + /// they carried. + pub fn lagLines(glide: *const Glide) f32 { + if (glide.rows_moved == 0) return glide.follow.offset; + return glide.follow.offset * glide.lines_moved / glide.rows_moved; + } + + pub fn deinit(glide: *Glide, gpa: std.mem.Allocator) void { + gpa.free(glide.before); + gpa.free(glide.above); + gpa.free(glide.below); + gpa.free(glide.last); + } + + pub fn bw(glide: *const Glide) u16 { + return glide.rect.w -| config.GUTTER; + } + + /// The rules at this body's size: a tenth of a pixel is 5e-3 rows. + pub fn pace(glide: *const Glide) Follow.Pace { + return Follow.pace(@floatFromInt(glide.body_h), 5e-3); + } + + /// The frame about to be drawn, at `now_ns` on the frontend's clock: + /// the glide moves on to now, and a body whose first line moved since + /// the last frame (the same text in the same place) is measured against + /// that frame and kicks it. A terminal's view glides only under the + /// wheel (`wheeled`: its output scrolls it at every line, and that is no + /// glide); not one the frontend moves by the pixel (`direct`). One glide + /// at a time: the focused body's, else the one that moved most. + pub fn frame(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface, now_ns: u64, wheeled: ?usize, direct: ?usize) void { + glide.now_ns = now_ns; + defer glide.remember(gpa, surface); + if (glide.follow.moving()) { + glide.follow.advance(now_ns, glide.pace()); + if (glide.follow.offset == 0) { + glide.nabove = 0; + glide.nbelow = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; + } + } + var pick: ?pardes.Region = null; + var delta: i64 = 0; + var shown: [pardes.MAX_PANES]bool = @splat(false); + for (surface.regionList()) |region| { + if (region.kind != .body or region.owner >= glide.seen.len) continue; + const id: usize = region.owner; + shown[id] = true; + const was = glide.seen[id]; + glide.seen[id] = .{ .serial = region.serial, .line = region.line, .doc = region.doc, .rect = region.rect }; + if (was.serial != region.serial or was.doc != region.doc or was.line == region.line) continue; + // The last frame drew this body where it is now: a pane that + // moved or was resized in the same step has no picture to glide + // from. + if (!std.meta.eql(was.rect, region.rect)) continue; + if (region.doc == 0 and wheeled != id) continue; + if (direct == id) continue; + const moved = @as(i64, region.line) - was.line; + if (pick) |best| if (best.active or (!region.active and @abs(moved) <= @abs(delta))) continue; + pick = region; + delta = moved; + } + for (&glide.seen, shown) |*seen, here| if (!here) { + seen.* = .{}; + }; + const body = pick orelse return; + const r = body.rect; + const rect: pardes.Rect = .{ .x = r.x -| config.GUTTER, .y = r.y, .w = r.w + config.GUTTER, .h = r.h }; + // A new pane or place: what was kept belongs to another picture. + if (glide.pane != body.owner or !std.meta.eql(glide.rect, rect)) glide.stop(); + glide.pane = body.owner; + glide.rect = rect; + glide.body_y = r.y; + glide.body_h = r.h; + const w = r.w; + if (w == 0 or r.h == 0 or glide.last_cols != surface.cols or glide.last_rows != surface.rows or + r.x + w > surface.cols or r.y + r.h > surface.rows) return glide.stop(); + // The body as the last frame drew it, which the move is measured from. + const n = @as(usize, w) * r.h; + if (glide.before.len < n) glide.before = gpa.realloc(glide.before, n) catch &.{}; + if (glide.before.len < n) return glide.stop(); + for (0..r.h) |row| @memcpy(glide.before[row * w ..][0..w], glide.last[(@as(usize, r.y) + row) * glide.last_cols + r.x ..][0..w]); + glide.dir = @intCast(std.math.sign(delta)); + glide.pending_lines += @floatFromInt(@abs(delta)); + glide.measure(gpa, surface); + } + + /// This frame's cells and caret, for the next frame's measure. + fn remember(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + if (glide.last.len != surface.cells.len) { + gpa.free(glide.last); + glide.last = gpa.alloc(pardes.Cell, surface.cells.len) catch &.{}; + } + if (glide.last.len != surface.cells.len) { + glide.last_cols = 0; + return; + } + @memcpy(glide.last, surface.cells); + glide.last_cols = surface.cols; + glide.last_rows = surface.rows; + glide.caret_row = if (surface.cursor) |c| c.y else null; + } + + /// Finds how far the pane's body rows moved, `dir` rows at a time, by + /// the rows of `surface` against `before`; keeps the rows that left. + fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + const w = glide.bw(); + const x0 = glide.rect.x + config.GUTTER; + if (w == 0 or glide.body_h == 0 or x0 + w > surface.cols or glide.body_y + glide.body_h > surface.rows or glide.before.len < @as(usize, w) * glide.body_h) return glide.stop(); + // The rows under the held ones (`held`) are what scrolls: `before` + // and the frame are compared, and kept, from there. + const top = @min(glide.held[glide.pane], glide.body_h -| 1); + const h = glide.body_h - top; + const now = struct { + fn row(s: *const pardes.Surface, x: u16, y: u16, n: u16) []const pardes.Cell { + return s.cells[@as(usize, y) * s.cols + x ..][0..n]; + } + }; + // The least shift under which the rows agree, but for a few: the + // cursor's line and its number's weight move with the scroll. The + // lines the core moved are tried first: unwrapped, they are the + // rows, and one pass over the body settles it (the search over + // every shift was 6 ms of the first frame of a page in Debug). + const agrees = struct { + fn at(gl: *const Glide, surf: *const pardes.Surface, x: u16, width: u16, height: u16, kk: u16) bool { + if (kk == 0 or kk + 3 > height) return false; + const allowed = @max(2, (height - kk) / 8); + var misses: usize = 0; + for (0..height - kk) |r| { + const rr: u16 = @intCast(r); + const held = @min(gl.held[gl.pane], gl.body_h -| 1); + const old_row = gl.before[@as(usize, held + if (gl.dir > 0) rr + kk else rr) * width ..][0..width]; + const new_row = now.row(surf, x, gl.body_y + held + if (gl.dir > 0) rr else rr + kk, width); + if (!sameRow(old_row, new_row)) { + misses += 1; + if (misses > allowed) return false; + } + } + return true; + } + }; + const guess: u16 = @intFromFloat(@min(glide.pending_lines, @as(f32, @floatFromInt(h)))); + // A body's lines or more: every row moved off, none in common. + var shift: u16 = if (guess >= h) 0 else if (agrees.at(glide, surface, x0, w, h, guess)) guess else found: for (1..h) |k| { + if (agrees.at(glide, surface, x0, w, h, @intCast(k))) break :found @intCast(k); + } else 0; + // Rows that disagree under every shift though the core moved a few + // lines: their colours changed as they moved (a paint arriving as a + // spin stops). Unwrapped, the rows moved are the lines: glide those + // (it landed from wherever it was, a snap at a spin's end). + if (shift == 0 and guess > 0 and guess < h) shift = guess; + // None in common: a body's move from the last frame's body, if the + // lines moved are that many (rows that merely changed, a small + // scroll the rows cannot show, land at once). + if (shift == 0 and glide.pending_lines + 3 < @as(f32, @floatFromInt(h))) return glide.stop(); + const far = shift == 0; + if (far) shift = h; + glide.caret_rides = !far and if (glide.caret_row) |old| if (surface.cursor) |c| + @as(i32, c.y) == @as(i32, old) - @as(i32, shift) * glide.dir + else + false else false; + glide.rows_moved += @floatFromInt(shift); + glide.lines_moved += glide.pending_lines; + glide.pending_lines = 0; + // The rows that left: past the top going down, the bottom going up. + if (!glide.ensure(gpa)) return glide.stop(); + const keep = if (glide.dir > 0) &glide.above else &glide.below; + const count = if (glide.dir > 0) &glide.nabove else &glide.nbelow; + const kept = @min(count.*, h * reach - shift); + std.mem.copyBackwards(pardes.Cell, keep.*[@as(usize, shift) * w ..][0 .. @as(usize, kept) * w], keep.*[0 .. @as(usize, kept) * w]); + for (0..shift) |i| { + const src_row: usize = top + if (glide.dir > 0) shift - 1 - i else h - shift + i; + @memcpy(keep.*[i * w ..][0..w], glide.before[src_row * w ..][0..w]); + } + count.* = kept + shift; + // What came into view is no longer past the other edge. + const other = if (glide.dir > 0) &glide.below else &glide.above; + const other_n = if (glide.dir > 0) &glide.nbelow else &glide.nabove; + // ...and after a jump, the rows past it are another place's. + const dropped = if (far) other_n.* else @min(other_n.*, shift); + std.mem.copyForwards(pardes.Cell, other.*[0 .. @as(usize, other_n.* - dropped) * w], other.*[@as(usize, dropped) * w ..][0 .. @as(usize, other_n.* - dropped) * w]); + other_n.* -= dropped; + // An input: the core's rows moved by as many (down positive). + glide.follow.kick(@as(f32, @floatFromInt(shift)) * @as(f32, @floatFromInt(glide.dir)), glide.now_ns, glide.pace()); + } + + pub fn ensure(glide: *Glide, gpa: std.mem.Allocator) bool { + const n = @as(usize, glide.bw()) * glide.body_h * reach; + inline for (.{ &glide.above, &glide.below }) |buffer| if (buffer.len < n) { + const grown = gpa.realloc(buffer.*, n) catch return false; + buffer.* = grown; + }; + return true; + } +}; + +pub fn sameRow(a: []const pardes.Cell, b: []const pardes.Cell) bool { + for (a, b) |x, y| { + if (x.default != y.default) return false; + if (x.default) continue; + if (!std.mem.eql(u8, x.grapheme(), y.grapheme()) or !std.meta.eql(x.style, y.style)) return false; + } + return true; +} + +/// A frame's length at 60 Hz, what a tick of the follow is clamped to. +const frame_ns: u64 = 16 * std.time.ns_per_ms; + +/// A view that follows its input (anim 9, 11): the picture's offset from +/// the core's position now (rows of text; negative, the picture still +/// shows what is above), its speed (rows a second), when it was last +/// integrated, and what has been feeding it. +pub const Follow = struct { + offset: f32 = 0, + speed: f32 = 0, + at_ns: u64 = 0, + /// The last inputs (down positive), their spacing, the last's time, and + /// how many came as one stream. + feed: struct { amount: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{}, + + /// How far the picture may lag, in bodies (a flick past that jumps); + /// how fast it may move, in bodies a second, so moving text stays + /// readable. + pub const reach = 2; + pub const bodies_per_s: f32 = 15; + /// Inputs this close, each the way the last went, are one stream. + pub const stream_ns = 150 * std.time.ns_per_ms; + /// The spring's natural frequency, rad/s: an arrival lands inside + /// 220 ms. + pub const omega: f32 = 51; + + /// What a view's size makes of the rules: the speed cap, the lag cap, + /// and the offset under which it is at rest (a tenth of a pixel, in + /// rows). + pub const Pace = struct { cap: f32, limit: f32, rest: f32 }; + + pub fn pace(body: f32, rest: f32) Pace { + return .{ .cap = body * bodies_per_s, .limit = body * reach, .rest = rest }; + } + + pub fn moving(follow: *const Follow) bool { + return follow.offset != 0 or follow.speed != 0; + } + + /// An input: the core moved `amount` (down positive). The picture now + /// lags by as much more, its speed as it was. + pub fn kick(follow: *Follow, amount: f32, now_ns: u64, p: Pace) void { + follow.advance(now_ns, p); + follow.offset = std.math.clamp(follow.offset - amount, -p.limit, p.limit); + const f = &follow.feed; + const like = f.count > 0 and (amount > 0) == (f.amount > 0) and now_ns -| f.last_ns < stream_ns; + if (like) { + const gap = now_ns -| f.last_ns; + f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2; + f.amount = (f.amount + amount) / 2; + f.count +|= 1; + } else f.* = .{ .amount = amount, .count = 1 }; + f.last_ns = now_ns; + } + + /// The system moved on to `now_ns`. Fed by a stream, at the stream's + /// rate (an input's amount over their spacing), held a lag `lead` + /// behind so a late input never finds it stopped and the stream's end + /// never runs it past its mark; else on the spring, critically damped, + /// from the speed it has. Never faster than `p.cap`. + pub fn advance(follow: *Follow, now_ns: u64, p: Pace) void { + const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| follow.at_ns, 2 * frame_ns))) / std.time.ns_per_s); + follow.at_ns = now_ns; + if (follow.offset == 0 and follow.speed == 0) return; + const toward: f32 = if (follow.offset < 0) 1 else -1; + const f = follow.feed; + if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) { + const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s); + const rate = @abs(f.amount) / gap; + const lead = @max(@abs(f.amount), rate / omega); + // ponytail: a gentle pull to the lead (a tenth an input), so the + // per-frame step varies by a tenth; a stream's own jitter beyond + // that shows. An estimate of the input clock if it ever matters. + // A slow stream's lag runs out before its next input: never + // faster than the spring's own pace from there (omega a unit of + // lag a second), so it eases onto the mark, not into it at speed. + const v = std.math.clamp(rate + 0.1 / gap * (@abs(follow.offset) - lead), 0, @min(p.cap, omega * @abs(follow.offset))); + const step = @min(v * dt, @abs(follow.offset)); + follow.offset += toward * step; + follow.speed = if (follow.offset == 0) 0 else toward * v; + return; + } + const x = follow.offset; + // Coming to rest from a stream: never faster than the spring's own + // pace from here (omega a unit of lag a second), so it eases in and + // does not pass its mark. + if (follow.speed * x < 0 and @abs(follow.speed) > omega * @abs(x)) follow.speed = std.math.sign(follow.speed) * omega * @abs(x); + const lead_v = follow.speed + omega * x; + const decay = @exp(-omega * dt); + var next = (x + lead_v * dt) * decay; + var speed = (follow.speed - omega * dt * lead_v) * decay; + if (@abs(next - x) > p.cap * dt) { + next = x + std.math.sign(next - x) * p.cap * dt; + speed = std.math.sign(next - x) * p.cap; + } + follow.offset = next; + follow.speed = speed; + if (@abs(next) < p.rest and @abs(speed) < 10 * p.rest) follow.* = .{ .at_ns = now_ns }; + } +}; + +test "a follow comes to rest without a snap: past its fastest frame each step is shorter, the last under a tenth of a pixel" { + // A flick's spin (a stream of notches, then nothing), one page, and + // notches slow enough that each lag runs out before the next (its + // stream must ease onto each mark, never pass it). + const p = Follow.pace(600, 0.1); + for ([_]struct { n: u16, gap_ms: u64 }{ .{ .n = 12, .gap_ms = 16 }, .{ .n = 1, .gap_ms = 16 }, .{ .n = 6, .gap_ms = 144 } }) |run| { + var f: Follow = .{}; + var now: u64 = std.time.ns_per_s; + for (0..run.n) |_| { + f.kick(if (run.n == 1) 600 else 25, now, p); + var waited: u64 = 0; + while (waited < run.gap_ms) : (waited += 8) { + now += 8 * std.time.ns_per_ms; + const was = f.offset; + f.advance(now, p); + // Toward its mark only, and onto it from under a pixel. + try std.testing.expect(f.offset <= 0 and f.offset >= was); + if (f.offset == 0) try std.testing.expect(-was <= 3 * p.rest); + } + } + var last: f32 = std.math.inf(f32); + var before = f.offset; + var frames: usize = 0; + var fastest: f32 = 0; + while (f.moving()) : (frames += 1) { + now += frame_ns; + f.advance(now, p); + const step = @abs(f.offset - before); + try std.testing.expect(@abs(f.offset) <= @abs(before)); + if (f.offset == 0) try std.testing.expect(step <= 3 * p.rest); + fastest = @max(fastest, step); + if (step < fastest) try std.testing.expect(step <= last); + last = step; + before = f.offset; + try std.testing.expect(frames < 120); + } + try std.testing.expect(last <= 0.1); + } +} + +test "a body scrolling under held rows (sticky context) is measured, and keeps the rows that left, below them" { + const gpa = std.testing.allocator; + // A body 10 rows high whose first 3 hold still (a source's context + // rows) while the lines under them scroll one. + var cells: [2][24 * 12]pardes.Cell = undefined; + var frames: [2]pardes.Surface = undefined; + for (&frames, &cells, [_]u16{ 10, 11 }) |*s, *c, first| { + @memset(c, .{}); + s.* = .{ .cols = 24, .rows = 12, .cells = c }; + s.addRegion(.{ .kind = .body, .owner = 0, .serial = 1, .rect = .{ .x = config.GUTTER, .y = 1, .w = 24 - config.GUTTER, .h = 10 }, .active = true, .line = first, .doc = 7 }); + for (0..3) |k| { + var buf: [8]u8 = undefined; + _ = s.print(config.GUTTER, @intCast(1 + k), 20, std.fmt.bufPrint(&buf, "ctx {d}", .{k}) catch unreachable, .{}); + } + for (3..10) |k| { + var buf: [8]u8 = undefined; + _ = s.print(config.GUTTER, @intCast(1 + k), 20, std.fmt.bufPrint(&buf, "L{d}", .{first + k - 3}) catch unreachable, .{}); + } + } + var glide: Glide = .{}; + defer glide.deinit(gpa); + glide.held[0] = 3; + glide.frame(gpa, &frames[0], std.time.ns_per_s, null, null); + glide.frame(gpa, &frames[1], std.time.ns_per_s + 16 * std.time.ns_per_ms, null, null); + // A row down, and the row that left is the first under the held ones, + // L10, not a held row. + try std.testing.expect(glide.follow.offset < -0.9); + try std.testing.expectEqual(@as(u16, 1), glide.nabove); + const w = glide.bw(); + try std.testing.expect(sameRow(glide.above[0..w], frames[0].cells[@as(usize, 1 + 3) * 24 + config.GUTTER ..][0..w])); +} diff --git a/dev/gui/Trackpad.zig b/dev/gui/Trackpad.zig new file mode 100644 index 00000000..ef28d211 --- /dev/null +++ b/dev/gui/Trackpad.zig @@ -0,0 +1,142 @@ +//! Mac trackpad policy, after AppKit decoding. Buttons use SDL's 1/2/3. +const std = @import("std"); +const Trackpad = @This(); + +fingers: usize = 0, +stream: ?u8 = null, +button: ?u8 = null, +forced: bool = false, +rotation: f32 = 0, +rotation_total: f32 = 0, +gesture: enum { none, pinch, rotate } = .none, +pinch_base: f32 = 0, +pinch_total: f32 = 1, + +pub fn countFingers(t: *Trackpad, count: usize) void { + if (count < 2 or t.fingers < 2) { + t.gesture = .none; + t.rotation_total = 0; + t.pinch_base = 0; + t.pinch_total = 1; + } + t.fingers = count; +} + +pub fn press(t: *Trackpad, stream: u8) u8 { + if (t.fingers == 0 or stream > 3) return stream; + t.stream = stream; + t.button = if (t.fingers >= 2) 2 else stream; + t.forced = false; + return t.button.?; +} + +pub fn release(t: *Trackpad, stream: u8) ?u8 { + if (t.stream != stream) return stream; + defer { + t.stream = null; + t.button = null; + t.forced = false; + } + return if (t.forced) null else t.button; +} + +/// The caller releases this button before issuing one Look click. The +/// physical release afterwards is swallowed, so it cannot become a chord. +pub fn force(t: *Trackpad, stage: f32) ?u8 { + if (stage < 2 or t.forced or t.button == null or t.button == 3) return null; + t.forced = true; + return t.button; +} + +pub fn rotate(t: *Trackpad, degrees: f32, phase: u32) i32 { + if (phase == 1 or phase == 3) { + t.rotation = 0; + t.rotation_total = 0; + } + if (phase == 3 or !std.math.isFinite(degrees)) return 0; + if (t.gesture == .pinch) return 0; + t.rotation_total += std.math.clamp(degrees, -640, 640); + if (@abs(t.rotation_total) >= 3) t.gesture = .rotate; + const next = t.rotation + std.math.clamp(degrees, -640, 640); + const ticks: i32 = @intFromFloat(@trunc(next / 10)); + t.rotation = next - @as(f32, @floatFromInt(ticks)) * 10; + return ticks; +} + +/// Ignore small magnification noise, especially while twisting. Once a +/// deliberate pinch wins, half the logarithmic gain makes fine zoom easier. +pub fn magnify(t: *Trackpad, size: f32, scale: f32, phase: u32) ?f32 { + if (phase == 1 or t.pinch_base == 0) { + t.pinch_base = size; + t.pinch_total = 1; + } + if (phase == 3) { + t.pinch_base = 0; + if (t.gesture == .pinch) t.gesture = .none; + return null; + } + if (t.gesture == .rotate or !std.math.isFinite(scale) or scale <= 0) return null; + t.pinch_total = std.math.clamp(t.pinch_total * scale, 0.01, 100); + if (t.gesture == .none) { + if (t.pinch_total > 1 / @as(f32, 1.1) and t.pinch_total < 1.1) return null; + t.gesture = .pinch; + } + return std.math.clamp(t.pinch_base * @sqrt(t.pinch_total), 8, 72); +} + +pub fn pinch(size: f32, scale: f32) f32 { + if (!std.math.isFinite(scale) or scale <= 0) return size; + return std.math.clamp(size * scale, 8, 72); +} + +test "Mac trackpad multi-finger buttons stay latched after the fingers lift" { + var t: Trackpad = .{}; + try std.testing.expectEqual(@as(u8, 3), t.press(3)); // real mouse + try std.testing.expectEqual(@as(?u8, 3), t.release(3)); + for ([_]usize{ 2, 3 }) |n| { + t.fingers = n; + try std.testing.expectEqual(@as(u8, 2), t.press(3)); + t.fingers = 0; + try std.testing.expectEqual(@as(?u8, 2), t.release(3)); + } +} + +test "Mac trackpad force click upgrades Exec once without a paste chord or stray release" { + var t: Trackpad = .{ .fingers = 2 }; + try std.testing.expectEqual(@as(u8, 2), t.press(3)); + try std.testing.expect(t.force(1) == null); + try std.testing.expectEqual(@as(?u8, 2), t.force(2)); + try std.testing.expect(t.force(2) == null); + try std.testing.expect(t.release(3) == null); + t.fingers = 1; + try std.testing.expectEqual(@as(u8, 1), t.press(1)); + try std.testing.expectEqual(@as(?u8, 1), t.release(1)); +} + +test "Mac trackpad rotate and pinch reject invalid input and reset cancelled gestures" { + var t: Trackpad = .{}; + try std.testing.expectEqual(@as(i32, 0), t.rotate(7, 1)); + try std.testing.expectEqual(@as(i32, 1), t.rotate(5, 0)); + try std.testing.expectEqual(@as(i32, -1), t.rotate(-12, 0)); + try std.testing.expectEqual(@as(i32, 0), t.rotate(9, 3)); + try std.testing.expectEqual(@as(f32, 0), t.rotation); + try std.testing.expectEqual(@as(f32, 18), pinch(18, 1)); + try std.testing.expectEqual(@as(f32, 36), pinch(18, 2)); + try std.testing.expectEqual(@as(f32, 72), pinch(18, 100)); + try std.testing.expectEqual(@as(f32, 18), pinch(18, std.math.nan(f32))); +} + +test "trackpad pinch ignores twist noise and uses gentler deliberate zoom" { + var t: Trackpad = .{}; + t.countFingers(2); + try std.testing.expect(t.magnify(18, 1, 1) == null); + for (0..5) |_| try std.testing.expect(t.magnify(18, 1.01, 0) == null); + _ = t.rotate(7, 1); + try std.testing.expect(t.magnify(18, 1.3, 0) == null); + t.countFingers(0); + t.countFingers(2); + const zoom = t.magnify(18, 1.2, 1) orelse return error.PinchNotRecognized; + try std.testing.expect(zoom > 18 and zoom < 20.5); + try std.testing.expectEqual(@as(i32, 0), t.rotate(30, 1)); + try std.testing.expect(t.magnify(zoom, 1, 3) == null); +} diff --git a/dev/gui/deck.zig b/dev/gui/deck.zig new file mode 100644 index 00000000..1859bae8 --- /dev/null +++ b/dev/gui/deck.zig @@ -0,0 +1,204 @@ +//! Steam Deck controls -> editor input, as a pure state machine: gui.zig +//! feeds SDL gamepad events in and applies the returned actions (cursor +//! moves, synthetic clicks, wheel ticks, keys, rumble), so the whole +//! mapping replays off-device from deckcap recordings (test/deck/). +//! +//! Layout: right pad moves the pointer (relative, laptop-touchpad-style) and +//! a firm press on it = select (button 1); left pad scrolls and a firm press +//! = look (button 3); R2 = select, L2 = execute (button 2), L1 = look, dpad +//! down/up = n/N, A = Enter, Y = Tab, the back paddles (L4/R4/L5/R5) toggle +//! the terminal (Ctrl-b); execute, look and pad-clicks request a brief rumble +//! ack. (The GUI mirrors this on the sticks: right stick = pointer, left +//! stick = scroll.) + +const std = @import("std"); + +// SDL_GamepadButton / SDL_GamepadAxis / touchpad indices (SDL3), verified +// against real deck recordings (test/deck/*.zon) and the pinned SDL's +// hidapi deck driver (touchpad 0 = left pad, 1 = right pad). +pub const BTN_A = 0; // SOUTH +pub const BTN_Y = 3; // NORTH +pub const BTN_L1 = 9; // LEFT_SHOULDER +pub const BTN_DPAD_UP = 11; +pub const BTN_DPAD_DOWN = 12; +// rear grip paddles (from a deckcap deckmap capture): the two-digit indices +pub const BTN_R4 = 16; +pub const BTN_L4 = 17; +pub const BTN_R5 = 18; +pub const BTN_L5 = 19; +pub const AXIS_L2 = 4; // LEFT_TRIGGER, analog 0..32767 +pub const AXIS_R2 = 5; // RIGHT_TRIGGER +pub const PAD_LEFT = 0; +pub const PAD_RIGHT = 1; + +/// feel knobs: a full-pad finger sweep covers this many screen pixels +/// (the deck's screen is 1280x800) / this many wheel ticks +pub const POINTER_SCALE: f32 = 600.0; +pub const SCROLL_SCALE: f32 = 24.0; +/// the pinned SDL 3.4.4 deck driver skips upstream's pad-Y negation, so +/// touch y arrives 0 = pad bottom; flip this when the sdl dep is bumped +pub const PAD_Y_SIGN: f32 = -1.0; +// analog triggers click at 30% and release at 20%: the gap keeps a value +// hovering near one threshold from chattering press/release pairs +pub const TRIG_PRESS: i16 = 9830; +pub const TRIG_RELEASE: i16 = 6553; +// a firm pad press (pressure 0..1) counts as a click, with the same release +// hysteresis. Real light-touch drags read ~0.03 in captures, so this is well +// clear of them; tune on-device against a real click capture. +pub const PAD_CLICK_PRESS: f32 = 0.10; +pub const PAD_CLICK_RELEASE: f32 = 0.06; + +pub const Input = union(enum) { + button: struct { idx: u8, down: bool }, + axis: struct { idx: u8, value: i16 }, + touch: struct { pad: u8, phase: enum { down, motion, up }, x: f32, y: f32, pressure: f32 }, +}; + +pub const Click = enum { select, execute, look }; // mouse buttons 1/2/3 +pub const Keytap = enum { n, cap_n, enter, tab, tty_toggle }; + +pub const Action = union(enum) { + move: struct { dx: f32, dy: f32 }, // pointer delta in screen pixels + click: struct { which: Click, down: bool }, + wheel: i32, // whole ticks, positive = wheel_down + key: Keytap, + rumble, +}; + +pub const Deck = struct { + rpad_on: bool = false, + rpad_x: f32 = 0, + rpad_y: f32 = 0, + lpad_on: bool = false, + lpad_y: f32 = 0, + scroll: f32 = 0, // fractional wheel ticks carried between motions + l2_held: bool = false, + r2_held: bool = false, + look_held: bool = false, + rpad_click: bool = false, // firm-press click state, per pad (hysteresis) + lpad_click: bool = false, + + pub fn feed(d: *Deck, in: Input, out: *[3]Action) usize { + var n: usize = 0; + switch (in) { + .button => |b| switch (b.idx) { + BTN_A => if (b.down) { + out[0] = .{ .key = .enter }; + n = 1; + }, + BTN_Y => if (b.down) { + out[0] = .{ .key = .tab }; + n = 1; + }, + BTN_DPAD_UP => if (b.down) { + out[0] = .{ .key = .cap_n }; + n = 1; + }, + BTN_DPAD_DOWN => if (b.down) { + out[0] = .{ .key = .n }; + n = 1; + }, + // any back paddle toggles the terminal (Ctrl-b), applied in gui.zig + BTN_L4, BTN_R4, BTN_L5, BTN_R5 => if (b.down) { + out[0] = .{ .key = .tty_toggle }; + n = 1; + }, + BTN_L1 => { + d.look_held = b.down; + out[0] = .{ .click = .{ .which = .look, .down = b.down } }; + n = 1; + if (b.down) { + out[1] = .rumble; + n = 2; + } + }, + else => {}, + }, + .axis => |a| { + if (a.idx != AXIS_L2 and a.idx != AXIS_R2) return 0; + const held = if (a.idx == AXIS_L2) &d.l2_held else &d.r2_held; + const which: Click = if (a.idx == AXIS_L2) .execute else .select; + if (!held.* and a.value >= TRIG_PRESS) { + held.* = true; + out[0] = .{ .click = .{ .which = which, .down = true } }; + n = 1; + if (which == .execute) { + out[1] = .rumble; + n = 2; + } + } else if (held.* and a.value <= TRIG_RELEASE) { + held.* = false; + out[0] = .{ .click = .{ .which = which, .down = false } }; + n = 1; + } + }, + .touch => |t| { + switch (t.pad) { + PAD_RIGHT => switch (t.phase) { + // a fresh touch only re-anchors — deltas start from the + // landing point, so the pointer never jumps to it + .down => { + d.rpad_on = true; + d.rpad_x = t.x; + d.rpad_y = t.y; + }, + .motion => if (d.rpad_on) { + out[n] = .{ .move = .{ + .dx = (t.x - d.rpad_x) * POINTER_SCALE, + .dy = (t.y - d.rpad_y) * PAD_Y_SIGN * POINTER_SCALE, + } }; + n += 1; + d.rpad_x = t.x; + d.rpad_y = t.y; + }, + .up => d.rpad_on = false, + }, + PAD_LEFT => switch (t.phase) { + .down => { + d.lpad_on = true; + d.lpad_y = t.y; + }, + .motion => if (d.lpad_on) { + d.scroll += (t.y - d.lpad_y) * PAD_Y_SIGN * SCROLL_SCALE; + d.lpad_y = t.y; + const ticks: i32 = @intFromFloat(d.scroll); + if (ticks != 0) { + d.scroll -= @floatFromInt(ticks); + out[n] = .{ .wheel = ticks }; + n += 1; + } + }, + .up => d.lpad_on = false, + }, + else => {}, + } + // a firm press on either pad is a click: right pad -> select + // (left button), left pad -> look (right button). The press + // rumbles as click feedback, mirroring the stock driver (SDL + // exposes no per-pad haptic, so it's a short whole-pad buzz). + if (t.pad == PAD_RIGHT or t.pad == PAD_LEFT) { + const which: Click = if (t.pad == PAD_RIGHT) .select else .look; + const held = if (t.pad == PAD_RIGHT) &d.rpad_click else &d.lpad_click; + if (t.phase == .up) { + if (held.*) { + held.* = false; + out[n] = .{ .click = .{ .which = which, .down = false } }; + n += 1; + } + } else if (!held.* and t.pressure >= PAD_CLICK_PRESS) { + held.* = true; + out[n] = .{ .click = .{ .which = which, .down = true } }; + n += 1; + out[n] = .rumble; + n += 1; + } else if (held.* and t.pressure <= PAD_CLICK_RELEASE) { + held.* = false; + out[n] = .{ .click = .{ .which = which, .down = false } }; + n += 1; + } + } + }, + } + return n; + } +}; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig new file mode 100644 index 00000000..595e867d --- /dev/null +++ b/dev/gui/gui.zig @@ -0,0 +1,8319 @@ +const dev = @import("sketchbook"); // sketchbook's devices +const SketchGpu = dev.Executor; +const Cells = dev.Cells; +const Atlas = dev.Atlas; +const Present = dev.Present; +const GpuScene = dev.scene; +const filesystem = @import("core").filesystem; +const std = @import("std"); +const builtin = @import("builtin"); +const posix = std.posix; +/// libc: pipes and fcntl for the window's wakes, and a test harness's capture files written from the render thread. +const libc = std.c; +const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser +const pardes = @import("core"); +const vaxis_input = @import("../vaxis_input.zig"); +const dump = @import("core").dump; +const config = @import("core").config; +const look = @import("core").look; +const message = pardes.Messages.Message; +const file_watch = @import("../file_watch.zig"); +const deck = @import("deck.zig"); +const pet = @import("pet.zig"); +const Trackpad = @import("Trackpad.zig"); +const JumpTrail = @import("../jump_trail.zig"); +const Art = @import("../Art.zig"); +const fonts = @import("../fonts.zig"); // the fallback faces +const selection_pipe = @import("core").selection_pipe; +const c_heap = @import("c_heap"); + +const ninep_io = @import("runtime").ninep_io; + +const daemon = @import("runtime").daemon; +const upgrade = @import("runtime").upgrade; +const replica = @import("core").replica; +const tracy = @import("core").tracy; + +pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig + +const host_io = @import("../host_io.zig"); +const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); + +const log = std.log.scoped(.gui); + +const font_ttf = @embedFile("AdwaitaMono-Regular.ttf"); + +const bg_default = [3]u8{ 18, 18, 18 }; +const fg_default = [3]u8{ 204, 204, 204 }; + +const p9_arrow_clr = [32]u8{ + 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, + 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, + 0x80, 0x02, 0x80, 0x01, 0x80, 0x02, 0x8C, 0x04, + 0x92, 0x08, 0x91, 0x10, 0xA0, 0xA0, 0xC0, 0x40, +}; +const p9_arrow_set = [32]u8{ + 0x00, 0x00, 0x7F, 0xFE, 0x7F, 0xFC, 0x7F, 0xF0, + 0x7F, 0xE0, 0x7F, 0xE0, 0x7F, 0xF0, 0x7F, 0xF8, + 0x7F, 0xFC, 0x7F, 0xFE, 0x7F, 0xFC, 0x73, 0xF8, + 0x61, 0xF0, 0x60, 0xE0, 0x40, 0x40, 0x00, 0x00, +}; +/// acme's boxcursor (acme.c:956), while a grip carries a pane or column. +const p9_box_clr = [32]u8{ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, + 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, +}; +const p9_box_set = [32]u8{ + 0x00, 0x00, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, + 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, + 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, + 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x00, 0x00, +}; +const p9_box_mask = blk: { + var m: [32]u8 = undefined; + for (&m, p9_box_set, p9_box_clr) |*b, s, cl| b.* = s | cl; + break :blk m; +}; +const p9_arrow_mask = blk: { + var m: [32]u8 = undefined; + for (&m, p9_arrow_set, p9_arrow_clr) |*b, s, cl| b.* = s | cl; + break :blk m; +}; + +const atlas_w = Atlas.atlas_w; +const atlas_h = Atlas.atlas_h; +const Slot = Atlas.Slot; +const GlyphKey = Atlas.Key; +const ruleArms = Atlas.ruleArms; + +const GlyphDecoration = packed struct(u5) { + bold: bool = false, + underline: @FieldType(pardes.CellStyle, "ul") = .off, + strikethrough: bool = false, + + fn fromCell(cell: *const pardes.Cell) GlyphDecoration { + if (cell.default or cell.style.invisible) return .{}; + return .{ .bold = cell.style.bold, .underline = cell.style.ul, .strikethrough = cell.style.strikethrough }; + } + + fn drawsBlank(decoration: GlyphDecoration) bool { + return decoration.underline != .off or decoration.strikethrough; + } +}; + +// The atlas's Key holds a GlyphDecoration and a FontRole as its own +// Decoration and Role (@bitCast, @enumFromInt): the same bits, so the same +// slots. +comptime { + std.debug.assert(@bitSizeOf(GlyphDecoration) == @bitSizeOf(Atlas.Decoration)); + for (.{ .{ @FieldType(pardes.CellStyle, "ul"), Atlas.Underline }, .{ pardes.FontRole, Atlas.Role } }) |pair| { + const ours = @typeInfo(pair[0]).@"enum"; + const its = @typeInfo(pair[1]).@"enum"; + std.debug.assert(ours.tag_type == its.tag_type and ours.field_names.len == its.field_names.len); + for (ours.field_names, its.field_names, ours.field_values, its.field_values) |a, b, x, y| std.debug.assert(std.mem.eql(u8, a, b) and x == y); + } +} + +const TaglineRaster = struct { + px: f32, + width: u32, + baseline: i32, + height: u32, +}; + +fn taglineRaster(atlas: *const Atlas, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster { + const px = body_px * @as(f32, @floatFromInt(percent)) / 100.0; + var own_w: c_int = 1; + var own_h: c_int = 1; + var own_ascent: c_int = 1; + atlas.cellMetrics(px, &own_w, &own_h, &own_ascent); + const fixed_w: c_int = @intCast(body_cell_w); + const fixed_h: c_int = @intCast(body_cell_h); + const band_h = std.math.clamp(own_h, 1, fixed_h); + return .{ + .px = px, + .width = @intCast(std.math.clamp(own_w, 1, fixed_w)), + .baseline = std.math.clamp(own_ascent, 1, band_h), + .height = @intCast(band_h), + }; +} +/// What FreeType and HarfBuzz allocate from, through ui_malloc and friends: +/// the shared C heap, exported under the names font.c and HarfBuzz's +/// hb_malloc_impl expect. runNative points it at the gui's gpa once +/// HarfBuzz's process-wide objects exist (ui_font_prime), so a Debug build's +/// leak report is about fonts; a test that counts what fonts leak points it +/// at std.testing.allocator the same way. Only the render thread calls into +/// fonts, and every allocator it is pointed at is thread-safe anyway. +var font_allocator: std.mem.Allocator = std.heap.smp_allocator; +const font_heap = c_heap.Heap(&font_allocator); +comptime { + @export(&font_heap.malloc, .{ .name = "ui_malloc" }); + @export(&font_heap.calloc, .{ .name = "ui_calloc" }); + @export(&font_heap.realloc, .{ .name = "ui_realloc" }); + @export(&font_heap.free, .{ .name = "ui_free" }); +} + +/// What SDL allocates from, on its own threads as well as the render thread: +/// the gui's gpa, through the shared C heap, which is thread-safe in every +/// build. runNative hands everything back and calls SDL_Quit on the way out. +var sdl_allocator: std.mem.Allocator = undefined; +const sdl_heap = c_heap.Heap(&sdl_allocator); + +const max_fallback_fonts = 1 + fonts.fallback_names.len; +comptime { + std.debug.assert(max_fallback_fonts <= Atlas.max_fallbacks); +} + +const max_touch_points: usize = 16; +const touch_scroll_tick: f32 = 0.02; + +// The triangle overlay holds only the pet, a jump's trail and the cursor's +// glide quad: the chrome is decor. +const max_overlay_vertices: usize = pet.max_vertices + 5 * 6 + 6; + +const font_px_step: f32 = 2.0; +const font_px_min: f32 = 8.0; +const font_px_max: f32 = 72.0; + +const CellInstance = Cells.CellInstance; +const OverlayVertex = Cells.OverlayVertex; +const ImageInstance = Cells.ImageInstance; +const opaque_bg_bit = Cells.opaque_bg_bit; + +const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 }; + +const PreparedImage = struct { + premultiplied: bool = false, + place: pardes.Placement, + texture: *c.SDL_GPUTexture, +}; + +fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) bool { + core.update(resizeOf(core.view(), cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false); + return true; +} + +/// The resize a window of `cols` by `rows` cells of these sizes is to the +/// live view, or null when it is that already. +fn resizeOf(v: *const pardes.Pardes.View, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) ?pardes.Event { + const metrics: pardes.RowMetrics = .{ .body_w = @intCast(cell_w), .body_h = @intCast(cell_h), .tagline_w = @intCast(tag_w), .tagline_h = @intCast(tag_h) }; + const same_metrics = std.meta.eql(metrics, v.row_metrics); + const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16))); + const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16))); + if (cols == v.screen_w and rows == v.screen_h and + cell_px_w == v.cell_pixels.w and cell_px_h == v.cell_pixels.h and same_metrics) return null; + return .{ .resize = .{ + .cols = cols, + .rows = rows, + .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h }, + .row_metrics = metrics, + } }; +} + +const TouchPoint = struct { + active: bool = false, + id: u64 = 0, + x: f32 = 0, + y: f32 = 0, +}; + +const TouchNormPoint = struct { x: f32 = 0, y: f32 = 0 }; + +const Finger = struct { kind: enum { down, motion, up, cancel }, id: u64, x: f32, y: f32 }; + +const Touch = struct { + points: [max_touch_points]TouchPoint = @splat(.{}), + scroll: struct { + active: bool = false, + ids: [2]u64 = .{ 0, 0 }, + accum_y: f32 = 0, + scrolled: bool = false, + last_center: TouchNormPoint = .{}, + } = .{}, + + fn findSlot(t: *const Touch, id: u64) ?usize { + for (&t.points, 0..) |*tp, i| if (tp.active and tp.id == id) return i; + return null; + } + + fn updatePoint(t: *Touch, f: Finger) void { + switch (f.kind) { + .up, .cancel => if (t.findSlot(f.id)) |i| { + t.points[i].active = false; + }, + .down, .motion => { + const idx = t.findSlot(f.id) orelse blk: { + for (&t.points, 0..) |*tp, i| if (!tp.active) break :blk i; + break :blk @as(usize, @intCast(f.id % max_touch_points)); + }; + const tp = &t.points[idx]; + if (!tp.active or tp.id != f.id) tp.* = .{ .active = true, .id = f.id }; + tp.x = f.x; + tp.y = f.y; + }, + } + } + + fn pairCenter(t: *const Touch, ids: [2]u64) ?TouchNormPoint { + var sum: TouchNormPoint = .{}; + for (ids) |id| { + const i = t.findSlot(id) orelse return null; + sum.x += t.points[i].x; + sum.y += t.points[i].y; + } + return .{ .x = sum.x * 0.5, .y = sum.y * 0.5 }; + } + + fn syncPair(t: *Touch) void { + var ids: [2]u64 = .{ 0, 0 }; + var count: usize = 0; + for (&t.points) |*tp| { + if (!tp.active) continue; + if (count >= 2) { + t.scroll = .{}; + return; + } + ids[count] = tp.id; + count += 1; + } + if (count != 2) { + t.scroll = .{}; + return; + } + if (ids[0] > ids[1]) std.mem.swap(u64, &ids[0], &ids[1]); + if (t.scroll.active and t.scroll.ids[0] == ids[0] and t.scroll.ids[1] == ids[1]) return; + t.scroll = .{ .active = true, .ids = ids, .last_center = t.pairCenter(ids) orelse .{} }; + } + + fn finishPair(t: *Touch, f: Finger) ?TouchNormPoint { + if (!t.scroll.active or (t.scroll.ids[0] != f.id and t.scroll.ids[1] != f.id)) return null; + const tap = f.kind == .up and !t.scroll.scrolled; + var center: ?TouchNormPoint = null; + if (tap) { + var sum: TouchNormPoint = .{}; + var ok = true; + for (t.scroll.ids) |id| { + if (id == f.id) { + sum.x += f.x; + sum.y += f.y; + } else if (t.findSlot(id)) |i| { + sum.x += t.points[i].x; + sum.y += t.points[i].y; + } else ok = false; + } + center = if (ok) .{ .x = sum.x * 0.5, .y = sum.y * 0.5 } else t.scroll.last_center; + } + t.scroll = .{}; + return center; + } + + fn noteMotion(t: *Touch, f: Finger) ?struct { center: TouchNormPoint, ticks: i32 } { + if (!t.scroll.active or (t.scroll.ids[0] != f.id and t.scroll.ids[1] != f.id)) return null; + const center = t.pairCenter(t.scroll.ids) orelse t.scroll.last_center; + const delta_y = center.y - t.scroll.last_center.y; + t.scroll.last_center = center; + t.scroll.accum_y += delta_y; + const ticks = takeScrollTicks(&t.scroll.accum_y); + if (ticks == 0) return null; + t.scroll.scrolled = true; + return .{ .center = center, .ticks = ticks }; + } +}; + +fn takeScrollTicks(accum: *f32) i32 { + var ticks: i32 = 0; + while (accum.* >= touch_scroll_tick) : (ticks += 1) accum.* -= touch_scroll_tick; + while (accum.* <= -touch_scroll_tick) : (ticks -= 1) accum.* += touch_scroll_tick; + return ticks; +} + +fn handleFinger(t: *Touch, in: *Input, f: Finger, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { + std.debug.assert(cell_w > 0 and cell_h > 0); + switch (f.kind) { + .down => { + t.updatePoint(f); + t.syncPair(); + }, + .motion => { + const had_pair = t.scroll.active; + t.updatePoint(f); + t.syncPair(); + if (!had_pair) return; + const res = t.noteMotion(f) orelse return; + emitTouchScroll(in, res.center, res.ticks, win_w, win_h, cell_w, cell_h, tagline_w); + }, + .up, .cancel => { + const tap_center = t.finishPair(f); + t.updatePoint(f); + t.syncPair(); + if (tap_center) |center| emitTouchClick(in, center, .middle, win_w, win_h, cell_w, cell_h, tagline_w); + }, + } +} + +fn emitTouchScroll(in: *Input, center: TouchNormPoint, ticks: i32, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { + const cell = gridCellAtDimensions(in.core, center.x * win_w, center.y * win_h, cell_w, cell_h, tagline_w); + const button: pardes.Mouse.Button = if (ticks > 0) .wheel_up else .wheel_down; + var remaining: u32 = @abs(ticks); + while (remaining > 0) : (remaining -= 1) + in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); +} + +fn emitTouchClick(in: *Input, point: TouchNormPoint, button: pardes.Mouse.Button, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { + const cell = gridCellAtDimensions(in.core, point.x * win_w, point.y * win_h, cell_w, cell_h, tagline_w); + in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); + in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); +} + +const Pty = struct { + fd: c_int, + pid: libc.pid_t, + serial: u32, + /// Its reader, blocked in an Io read: `closePty` cancels it. + reader: ?std.Io.Future(void) = null, + /// 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 = .{}, +}; + +const Queue = host_io.Inbox; + +/// Wakes a blocking SDL_WaitEventTimeout from another thread: a push to +/// the queue, a link's message. +fn sdlWake(_: ?*anyopaque) void { + var sev = std.mem.zeroes(c.SDL_Event); + sev.type = c.SDL_EVENT_USER; + _ = c.SDL_PushEvent(&sev); +} +const PipeTasks = selection_pipe.Tasks; +const output_capacity = Queue.output_capacity; + +fn stopPipe() ![2]c_int { + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + errdefer for (fds) |fd| { + _ = libc.close(fd); + }; + for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed; + return fds; +} + +fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { + while (true) { + var fds = [_]libc.pollfd{ + .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, + .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, + }; + if (libc.poll(&fds, fds.len, -1) < 0) { + if (libc.errno(-1) == .INTR) continue; + return; + } + if (fds[0].revents != 0) return; + if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return; + if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed); + } +} + +const Gui = struct { + addon_gpu: ?SketchGpu = null, + addon_hash: [pardes.MAX_PANES]u64 = @splat(0), + addon_serial: [pardes.MAX_PANES]u32 = @splat(0), + addon_failed: [pardes.MAX_PANES]u64 = @splat(0), + window: *c.SDL_Window, + /// The device, the window's claim or soft presenter, the frame's target + /// and the capture's read back (runNative owns it). + present: *Present, + /// The pipelines, the atlas's texture, the pictures' textures and the + /// buffers the frame is drawn from, on present's device (runNative owns + /// it). + cells: *Cells, + overlay_vertices: []OverlayVertex, + prepared_images: std.ArrayListUnmanaged(PreparedImage) = .empty, + /// The glyph art of the placements whose panes ask for it (Petscii + /// on), and the frame copy it is drawn into. + art: Art = .{}, + art_arena: ?std.heap.ArenaAllocator = null, + /// renderFrame's cover of the grid (coverFrame). + cover: std.ArrayListUnmanaged(Cover) = .empty, + /// renderFrame's decor instances, group by group (buildDecor). + decor: std.ArrayListUnmanaged(CellInstance) = .empty, + + /// The faces and the glyphs drawn from them. + atlas: Atlas, + font_name: [255]u8 = @splat(0), + font_name_len: u8 = 0, + /// A replica client's: the session's font request it last followed + /// (syncReplicaFont), as a hash of the request. + session_font_request: ?u64 = null, + px: f32, + tagline_px: f32, + tagline_percent: u8, + tagline_width: u32, + tagline_height: u32, + cell_w: u32, + cell_h: u32, + ascent: i32, + tagline_baseline: i32, + + words: Words = .{}, + + touch: Touch = .{}, + /// A Mac trackpad's gestures (macos_trackpad.m decodes them). + trackpad: Trackpad = .{}, + /// The workspace tag's pet (Pet), on the window's own clock. + pet_state: pet.State = .{}, + /// The cursor's jump trail (JumpTrail), on the window's own clock. + trail: JumpTrail = .{}, + /// The caret's ease, on the window's own clock (Caret). + caret: Caret = .{}, + /// The window's clock for the frame being drawn (Shell.ownNow), and + /// what moved the glide's view since the last (stepGlide): the pane a + /// wheel scrolled, one a touchpad moves by the pixel. + now_ns: u64 = 0, + glide_wheeled: ?usize = null, + glide_direct: ?usize = null, + /// The last key, click or wheel, which the blink holds for. + input_ns: u64 = 0, + live_ctrl: bool = false, + live_alt: bool = false, + + scroll_pane: ?usize = null, + scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, + scroll_body_y: u16 = 0, // that rect's first BODY row + scroll_body_h: u16 = 0, // and its BODY rows, which a taller tag leaves fewer of + scroll_held_px: f32 = 0, // its tree-sitter context band, which never moves + scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered + scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since + scroll_delta: f32 = 0, // finite raw distance waiting for the render batch + scroll_lag: f32 = 0, // picture position - core position, in rows + scroll_edge: []pardes.Cell = &.{}, // the row that just left the pane + scroll_edge_len: u16 = 0, + /// Loop steps since the last fractional turn: past `settle_after`, a + /// resting `scroll_lag` eases onto the core's row (stepScroll). + scroll_idle: u8 = 0, + /// G6: a wheel's notches, whole lines, scroll the core at once and the + /// picture follows on a spring (Glide), never the other way round. + scroll_notch: i32 = 0, + /// A touchpad's fraction toward the next turn sent to a program that + /// owns the wheel (Term.Modes.wheel). + program_wheel: f32 = 0, + /// A trackpad's horizontal fraction toward the next turn (wheelAt). + program_wheel_x: f32 = 0, + glide: Glide = .{}, + /// PARDES_FRAMES_DEMO: the timedemo (its script's steps), its next step + /// and when it started; null when none runs. + demo: []const pardes.FrameStats.Step = &.{}, + demo_next: ?usize = null, + demo_start_ns: u64 = 0, + /// The tick the last paced frame was sampled at (waitInput), and + /// whether this loop's wait read an input (drawn at once, not paced). + pace_ns: u64 = 0, + input_seen: bool = false, + /// G14: the cells last drawn and when each last changed. + /// The cursor's blink (blinkNow): when the frame drawn last arrived, + /// a redraw owed for an edge, and this frame's cursor mode and alpha. + frame_arrival_ns: u64 = 0, + blink_due: bool = false, + no_blink: bool = false, + cursor_quad_alpha: f32 = 0, + pointer_present: bool = false, + arrow_cursor: ?*c.SDL_Cursor = null, + link_cursor: ?*c.SDL_Cursor = null, + box_cursor: ?*c.SDL_Cursor = null, + pointer_shape: pardes.Surface.PointerShape = .arrow, + pointer_cell: ?MouseCell = null, + /// The core the hit test asks (hitTest), while a local session runs; + /// null attached, where the session's tag is another process's. + hit_core: ?*pardes.Pardes = null, + + /// Pixels the capture holds past the grid (PARDES_TEST_PAD). + capture_pad: u32 = 0, + capture_dir: []const u8 = "", + /// PARDES_TEST_SERIES: every captured frame is kept too, numbered, for a + /// frame series to look at. + capture_series: bool = false, + captured: u32 = 0, + + applied_window_opacity: u8 = 100, + /// What a window is opened again with (reopenWindow): the flags (not + /// hidden), its size when it was closed (present keeps its present mode). + win_flags: c.SDL_WindowFlags = 0, + /// A native Wayland window: transparent at the first WindowOpacity + /// under 100 (syncWindowOpacity). + wayland: bool = false, + window_w: c_int = 1120, + window_h: c_int = 720, + /// The window runNative destroys at the end: the one open then, if any. + window_slot: ?*?*c.SDL_Window = null, + + gamepad: ?*c.SDL_Gamepad = null, + /// The gamepad subsystem started (startGamepads). + gamepads: bool = false, + pad_x: f32 = 0, + pad_y: f32 = 0, + pad_scroll: f32 = 0, // fractional vertical wheel ticks (left stick) + pad_scroll_h: f32 = 0, // fractional horizontal wheel ticks (left stick) + deck: deck.Deck = .{}, +}; + +/// What a window held of its own let go (closeWindow lets the window go). +fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { + g.glide.deinit(gpa); + gpa.free(g.scroll_edge); + g.prepared_images.deinit(gpa); +} + +fn setGuiFontName(g: *Gui, fallback: []const u8) void { + const name = if (g.atlas.fontName()) |name_z| std.mem.span(name_z) else fallback; + const len = @min(name.len, g.font_name.len); + @memcpy(g.font_name[0..len], name[0..len]); + g.font_name_len = @intCast(len); +} + +fn observeGuiFont(g: *const Gui, core: *pardes.Pardes) void { + const size: u16 = @intFromFloat(@round(g.px * 100.0)); + _ = core.observeFont(g.font_name[0..g.font_name_len], size, .pixels); +} + +fn acknowledgeGuiFont(g: *const Gui, core: *pardes.Pardes) void { + const size: u16 = @intFromFloat(@round(g.px * 100.0)); + _ = core.acknowledgeFont(g.font_name[0..g.font_name_len], size, .pixels); +} + +/// A replica client's font is the window's raster state: it follows the +/// session's request by the face's name on this machine (fonts.fromSession), +/// never acknowledging it or otherwise changing the replicated core. +fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator) bool { + const f = &core.settings.font; + const path = f.requested_path.get(); + const name = f.requested_name.get(); + if (path.len == 0 and name.len == 0) return false; + var hash = std.hash.Wyhash.init(0); + hash.update(path); + hash.update(name); + hash.update(std.mem.asBytes(&f.requested_size_hundredths)); + const request = hash.final(); + if (g.session_font_request == request) return false; + g.session_font_request = request; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const face = fonts.fromSession(arena.allocator(), path, name) orelse { + log.warn("the session's font is not installed here: {s}", .{name}); + return false; + }; + const bytes = filesystem.readFile(gpa, face.path) catch return false; + if (!g.atlas.setFont(gpa, bytes)) return false; + if (f.requested_size_hundredths != 0) + g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100; + setGuiFontName(g, face.name); + refitFont(g, null); + return true; +} + +fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { + _ = g.atlas.addFallback(gpa, font_ttf, false); + + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + for (fonts.fallbacks(arena_state.allocator())) |candidate| { + if (g.atlas.fallback_count == max_fallback_fonts) break; + const bytes = filesystem.readFile(gpa, candidate.path) catch continue; + _ = g.atlas.addFallback(gpa, bytes, true); + } +} + +const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 }; +const MouseCell = struct { col: u16, row: u16, body_hit: ?pardes.Mouse.BodyHit = null, tag_hit: ?pardes.TagHit = null, rule_above: bool = false }; + +/// How near a row's top edge a press is on the rule drawn there between two +/// panes: the rule's 2 px and a pixel either side, in logical pixels (dp). +const rule_grab_px: f32 = 3; +const WindowGeometry = struct { + window_w: f32, + window_h: f32, + pixel_w: f32, + pixel_h: f32, +}; + +fn windowGeometry(window: *c.SDL_Window) WindowGeometry { + var ww: c_int = 0; + var wh: c_int = 0; + var pw: c_int = 0; + var ph: c_int = 0; + _ = c.SDL_GetWindowSize(window, &ww, &wh); + _ = c.SDL_GetWindowSizeInPixels(window, &pw, &ph); + return .{ + .window_w = @floatFromInt(@max(ww, 1)), + .window_h = @floatFromInt(@max(wh, 1)), + .pixel_w = @floatFromInt(@max(pw, 1)), + .pixel_h = @floatFromInt(@max(ph, 1)), + }; +} + +const GridCells = struct { cols: u16, rows: u16 }; + +fn windowCells(g: *const Gui) GridCells { + var pw: c_int = 0; + var ph: c_int = 0; + _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); + return .{ + .cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))), + .rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))), + }; +} + +const Point = struct { x: f32, y: f32 }; + +fn windowPointToPixels(geometry: WindowGeometry, x: f32, y: f32) Point { + return .{ + .x = x * geometry.pixel_w / geometry.window_w, + .y = y * geometry.pixel_h / geometry.window_h, + }; +} + +fn fixedCellLayout(g: *const Gui) CellLayout { + return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; +} + +const Group = Cells.Group; + +/// The frame's draw groups, bottom to top: the page and the panes, the +/// notices floating over them, the debug box the core paints over those, +/// and ink (the bar cursors; the cursor's glide draws after it). +const Groups = struct { + items: [4]Group = @splat(.{}), + notices: usize = 1, + debug: usize = 2, + ink: usize = 3, + len: usize = 4, +}; + +/// What draws a grid cell, marked once a frame from the layers and the +/// regions (coverFrame), so the cell loops read it rather than search. +const Cover = packed struct(u16) { + /// A layer draws it; the grid's copy is not drawn. + layer: bool = false, + /// Under the debug box: drawn from the grid over the panes. + floating: bool = false, + /// In a pane's grip, `grip_offset` cells from its left: the grip's + /// glyph is the cell that far to the left. + grip: bool = false, + grip_offset: u4 = 0, + /// In the focused pane's or column's tag rows. + focus: bool = false, + /// At a column's left edge, where a tag's anchor is inset. + anchor: bool = false, + /// In a dirty pane's grip. + dirty: bool = false, + /// In a pane's grip (not a column's). + pane_grip: bool = false, + /// In a grip's first row, where its button is. + grip_top: bool = false, + /// In an unfocused pane's tag or body rows while InactiveDim fades them. + dim: bool = false, + _: u3 = 0, +}; + +/// Marks the grid cells a body or tag layer covers, which the layers paint +/// themselves, and what the regions say of the rest. Filling each rectangle +/// once replaces scanning every layer for every cell, which was a third of +/// the gui's CPU on a full screen of text. +fn coverFrame(cover: []Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer, regions: []const pardes.Region) void { + @memset(cover, .{}); + const mark = struct { + fn rect(into: []Cover, width: u16, height: u16, r: pardes.Rect, comptime field: []const u8, value: anytype) void { + const right = @min(width, @as(u32, r.x) + r.w); + if (r.x >= right) return; + var y: u32 = r.y; + while (y < @min(height, @as(u32, r.y) + r.h)) : (y += 1) + for (into[y * width ..][r.x..right]) |*cell| { + @field(cell, field) = value; + }; + } + }; + for (body_layers) |*layer| { + if (layer.rows != 0) mark.rect(cover, cols, rows, layer.viewport, "layer", true); + } + for (tag_layers) |*layer| { + if (layer.rows != 0) mark.rect(cover, cols, rows, .{ .x = layer.viewport.x, .y = layer.viewport.y, .w = layer.viewport.w, .h = layer.rows }, "layer", true); + } + // The column bar's rows, which the focused column's tint spans. + var bar: ?pardes.Rect = null; + for (regions) |region| { + if (region.kind == .column_grip) bar = region.rect; + } + // InactiveDim: an unfocused pane's tag and body rows (Dim.begin). + if (dim.amount > 0) for (regions) |region| { + if ((region.kind == .tag or region.kind == .body) and dim.of(region.owner)) mark.rect(cover, cols, rows, region.rect, "dim", true); + }; + for (regions) |region| switch (region.kind) { + .grip, .column_grip => { + mark.rect(cover, cols, rows, region.rect, "grip", true); + for (0..@min(region.rect.w, 16)) |offset| mark.rect(cover, cols, rows, .{ .x = region.rect.x +| @as(u16, @intCast(offset)), .y = region.rect.y, .w = 1, .h = region.rect.h }, "grip_offset", @as(u4, @intCast(offset))); + if (region.kind == .grip and region.active) mark.rect(cover, cols, rows, region.rect, "focus", true); + if (region.dirty) mark.rect(cover, cols, rows, region.rect, "dirty", true); + if (region.kind == .grip) mark.rect(cover, cols, rows, region.rect, "pane_grip", true); + mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w, .h = @min(1, region.rect.h) }, "grip_top", true); + }, + .tag => if (region.active) mark.rect(cover, cols, rows, region.rect, "focus", true), + .column => { + mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = 0, .w = 1, .h = rows }, "anchor", true); + if (region.active) if (bar) |b| mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = b.y, .w = region.rect.w, .h = b.h }, "focus", true); + }, + .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), + else => {}, + }; +} + +pub fn run(init: std.process.Init, opts: pardes.Options, detached: bool) !void { + return runNative(init, opts, detached, null); +} + +/// `pardes-gui --attach=:` (and `:`, +/// through ssh, main.zig): this window a replica client of a session +/// elsewhere, as the tty's `runClient` is a terminal's (`clientSession`). +pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far: bool) !void { + return runNative(init, opts, false, .{ .path = path, .session = session, .far = far }); +} + +const Dial = struct { path: []const u8, session: []const u8, far: bool }; + +fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, dial: ?Dial) !void { + const gpa = init.gpa; + const env = init.environ_map; + + const test_mode = env.get("PARDES_TEST") != null; + const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); + if (test_mode and capture_dir == null) { + log.err("PARDES_TEST requires PARDES_TEST_CAPTURE_DIR", .{}); + return error.SdlInit; + } + if (test_mode) if (env.get("PARDES_TEST_LATENCY")) |path| { + var path_buf: [4096]u8 = undefined; + if (std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0)) |z| + latency_fd = libc.open(z, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)) + else |_| {} + }; + + // SDL frees with whichever functions are current, so they go in before + // its first call, while nothing of SDL's exists yet. + sdl_allocator = gpa; + if (!c.SDL_SetMemoryFunctions(sdl_heap.malloc, sdl_heap.calloc, sdl_heap.realloc, sdl_heap.free)) { + log.err("SDL_SetMemoryFunctions: {s}", .{c.SDL_GetError()}); + return error.SdlInit; + } + _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI", "1"); // SDL_HINT_JOYSTICK_HIDAPI + _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI_STEAMDECK", "1"); // ..._STEAMDECK + if (comptime builtin.os.tag == .macos) _ = c.SDL_SetHint(c.SDL_HINT_MAC_SCROLL_MOMENTUM, "1"); + // The gamepads after the first frame (startGamepads). + if (!c.SDL_Init(c.SDL_INIT_VIDEO)) { + log.err("SDL_Init: {s}", .{c.SDL_GetError()}); + return error.SdlInit; + } + // SDL allocates from gpa (above), so what it still holds at exit is in a + // Debug build's leak report. The window, the GPU device and everything + // made on it go back first (the defers below run before this one). What + // is left is SDL 3.4.4's: its Vulkan backend never frees two 32-byte + // arrays per command buffer (VULKAN_INTERNAL_DestroyCommandPool; SDL's + // main branch frees them). + defer c.SDL_Quit(); + // No title bar or frame from anyone: borderless asks the compositor for + // none (xdg-decoration's client side, which SDL then leaves undrawn). + var win_flags: c.SDL_WindowFlags = c.SDL_WINDOW_RESIZABLE | c.SDL_WINDOW_BORDERLESS; + if (!test_mode) win_flags |= c.SDL_WINDOW_HIGH_PIXEL_DENSITY; + // A test run renders to the capture texture; keep it off the desktop. + if (test_mode) win_flags |= c.SDL_WINDOW_HIDDEN; + // Background-only opacity needs per-pixel alpha (whole-window compositor + // opacity would dim the text as well), so a transparent window, which + // the GPU API will not claim: it presents through SDL_Renderer, EGL and + // GL beside Vulkan, and its first present is slow. So a window starts + // opaque, and is made again transparent at the first WindowOpacity + // under 100 (syncWindowOpacity): SDL takes the flag only at creation. + const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); + const reopen_flags = win_flags; + // `--detach`: a window never shown, closed once the session is up. + if (detached) win_flags |= c.SDL_WINDOW_HIDDEN; + // `--geometry=WxH[+X+Y]`, as X11 programs take it. + var want_w: c_int = 1120; + var want_h: c_int = 720; + var want_at: ?[2]c_int = null; + if (opts_in.geometry) |spec| geometry: { + const x_at = std.mem.indexOfScalar(u8, spec, 'x') orelse break :geometry; + const plus = std.mem.indexOfAnyPos(u8, spec, x_at, "+-") orelse spec.len; + want_w = std.math.clamp(std.fmt.parseInt(c_int, spec[0..x_at], 10) catch break :geometry, 200, 16384); + want_h = std.math.clamp(std.fmt.parseInt(c_int, spec[x_at + 1 .. plus], 10) catch break :geometry, 120, 16384); + if (plus == spec.len) break :geometry; + const second = std.mem.indexOfAnyPos(u8, spec, plus + 1, "+-") orelse break :geometry; + const gx = std.fmt.parseInt(c_int, spec[plus + @intFromBool(spec[plus] == '+') .. second], 10) catch break :geometry; + const gy = std.fmt.parseInt(c_int, spec[second + @intFromBool(spec[second] == '+') ..], 10) catch break :geometry; + want_at = .{ gx, gy }; + } + const window = c.SDL_CreateWindow("pardes", want_w, want_h, win_flags) orelse { + log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); + return error.SdlInit; + }; + var window_slot: ?*c.SDL_Window = window; + if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); + defer if (window_slot) |open| c.SDL_DestroyWindow(open); + if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); + updateDisplayScale(window); + // On Linux the desktop's own cursor theme draws them (the compositor's + // cursor-shape protocol, else XCURSOR_THEME), at its size and scale: + // the arrow is its default, acme's box its move, as the plan9 theme + // has them. Elsewhere acme's bitmaps, at 16 pixels. + const themed_cursors = builtin.os.tag == .linux; + const arrow_cursor = if (themed_cursors) + c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_DEFAULT) + else + c.SDL_CreateCursor(&p9_arrow_set, &p9_arrow_mask, 16, 16, 1, 1); + defer if (arrow_cursor) |cursor| c.SDL_DestroyCursor(cursor); + const link_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER); + defer if (link_cursor) |cursor| c.SDL_DestroyCursor(cursor); + // Its hot spot the middle, as acme's {-7, -7} offset puts it. + const box_cursor = if (themed_cursors) + c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_MOVE) + else + c.SDL_CreateCursor(&p9_box_set, &p9_box_mask, 16, 16, 7, 7); + defer if (box_cursor) |cursor| c.SDL_DestroyCursor(cursor); + if (arrow_cursor) |cur| { + _ = c.SDL_SetCursor(cur); + } else log.err("SDL_CreateCursor: {s}", .{c.SDL_GetError()}); + var presenter = try Present.init(window, .{ + .test_mode = test_mode, + .surface_opacity = false, + .present_modes = &.{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }, + .debug = true, + }); + defer presenter.deinit(); + + font_allocator = gpa; + var atlas = Atlas.init(gpa, font_ttf) catch |err| { + log.err("the font atlas: {t}", .{err}); + return err; + }; + // HarfBuzz's process-wide objects are made once and never freed: made + // from the default heap, they stay out of a Debug build's leak report. + font_allocator = std.heap.smp_allocator; + atlas.prime(); + font_allocator = gpa; + // A harness forcing a density (PARDES_TEST_SCALE) draws the text as a + // person on that display would size it, so its chrome is seen at the + // proportion it has there. A live window keeps the size the user sets. + const px: f32 = if (test_mode) 27.0 * std.math.clamp(display_scale, 1, 4) else 27.0; + var cw: c_int = 10; + var chh: c_int = 20; + var asc: c_int = 16; + atlas.cellMetrics(px, &cw, &chh, &asc); + const cell_w: u32 = @intCast(@max(cw, 1)); + const cell_h: u32 = @intCast(@max(chh, 1)); + const tagline = taglineRaster(&atlas, px, cell_w, cell_h, config.gui_tagline_font_percent); + if (test_mode) { + const cols = envU16(env, "PARDES_TEST_COLS") orelse 80; + const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24; + // PARDES_TEST_PAD: extra pixels past the grid, as a real window has. + const pad = envU16(env, "PARDES_TEST_PAD") orelse 0; + _ = c.SDL_SetWindowSize(window, @intCast(cols * cell_w + pad), @intCast(rows * cell_h + pad)); + _ = c.SDL_SyncWindow(window); + } + + var cells = try Cells.init(presenter.device, presenter.swapchain_format, max_overlay_vertices); + // The pipelines, textures and buffers it holds, whatever they were + // regrown to, before the device (presenter's defer). + defer cells.deinit(gpa); + + const overlay_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices); + defer gpa.free(overlay_vertices); + + var g: Gui = .{ + .window = window, + .arrow_cursor = arrow_cursor, + .link_cursor = link_cursor, + .box_cursor = box_cursor, + .present = &presenter, + .cells = &cells, + .overlay_vertices = overlay_vertices, + .atlas = atlas, + .px = px, + .tagline_px = tagline.px, + .tagline_percent = config.gui_tagline_font_percent, + .tagline_width = tagline.width, + .tagline_height = tagline.height, + .cell_w = cell_w, + .cell_h = cell_h, + .ascent = asc, + .tagline_baseline = tagline.baseline, + .capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0, + .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, + .capture_dir = capture_dir orelse "", + .demo = if (env.get("PARDES_FRAMES_DEMO")) |path| try pardes.FrameStats.readScript(init.arena.allocator(), init.io, path) else &.{}, + .demo_next = if (env.get("PARDES_FRAMES_DEMO") != null) 0 else null, + .win_flags = reopen_flags, + .wayland = native_wayland, + .window_w = want_w, + .window_h = want_h, + .window_slot = &window_slot, + }; + defer if (g.gamepad) |pad| c.SDL_CloseGamepad(pad); + setGuiFontName(&g, "Adwaita Mono"); + loadFallbackFonts(&g, gpa); + defer g.atlas.deinit(gpa); + defer g.words.deinit(gpa); + defer { + if (g.addon_gpu) |*gpu| gpu.deinit(); + g.prepared_images.deinit(gpa); + g.art.deinit(gpa); + if (g.art_arena) |*arena| arena.deinit(); + g.cover.deinit(gpa); + g.decor.deinit(gpa); + } + defer gpa.free(g.scroll_edge); // grown on demand by stepScroll + defer g.glide.deinit(gpa); + resetGlyphAtlas(&g); + + // The window is dragged by the workspace tag's blank (hitTest): the + // compositor moves it, as it does a title bar. + if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) + log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); + if (dial) |to| return clientSession(init, &g, opts_in, test_mode, to); + try localSession(init, &g, opts_in, test_mode, detached); +} + +/// Detach: the window closed (and with it its swapchain or renderer); the +/// device, the atlas and the pipelines stay for the next one. +fn closeWindow(g: *Gui) void { + _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h); + _ = c.SDL_StopTextInput(g.window); + g.present.detach(g.window); + c.SDL_DestroyWindow(g.window); + if (g.window_slot) |slot| if (slot.* == g.window) { + slot.* = null; + }; +} + +/// `pardes-gui --attach`: a window again, as the first was made, at the +/// size the last one had. False when the display will not give one. +fn reopenWindow(g: *Gui) bool { + const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; + if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); + if (!g.present.attach(window)) { + c.SDL_DestroyWindow(window); + return false; + } + g.window = window; + if (g.window_slot) |slot| slot.* = window; + updateDisplayScale(window); + // ponytail: another view's window asks the hit test of whichever + // window's share the Gui holds then (the workspace tag sits in the same + // place in every view); a test per window if one moves it. + if (!g.present.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g); + _ = c.SDL_StartTextInput(window); + return true; +} + +fn localSession( + init: std.process.Init, + g: *Gui, + opts_in: pardes.Options, + test_mode: bool, + detached: bool, +) !void { + const io = init.io; + const gpa = init.gpa; + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + host_io.startWorkers(allocs); + defer host_io.stopWorkers(); + var opts = opts_in; + opts.addons = pardes.Addon.scan(); + opts.image_allocator = allocs.image; + opts.tree_sitter_allocator = allocs.tree_sitter; + opts.frame_allocator = allocs.frame; + var pw: c_int = 0; + var ph: c_int = 0; + if (opts.load_path != null) { + _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); + opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))); + opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))); + } + var core = if (upgrade.resumed) |*rec| + try upgrade.load(gpa, allocs.pardes, opts, rec) + else if (opts.load_path) |lp| blk: { + const bytes = try @import("core").filesystem.readFile(gpa, lp); + defer gpa.free(bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); + } else try pardes.Pardes.init(allocs.pardes, opts); + defer core.deinit(); + g.hit_core = core; + defer g.hit_core = null; + core.view().frontend.windowed = true; + core.view().frontend.native_images = true; + core.view().frontend.native_image_patches = true; + observeGuiFont(g, core); + syncTaglineFont(g, core); + + var prompt_rcs = host_io.Shell.prepare(); + defer prompt_rcs.deinit(); + + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(0); + var queue: Queue = .{ + .io = io, + .gpa = gpa, + .lsp_allocator = allocs.lsp, + .wake_fn = sdlWake, + }; + defer { + if (queue.lsp_task) |*task| task.future.cancel(io); + // Its worker may be waiting on the queue for room. + core.stream.cancelTask(); + queue.deinit(); + } + var pipe_tasks: PipeTasks = .{}; + defer pipe_tasks.cancelAll(io); + var inotify_fd: c_int = file_watch.init(true); + var watch_reader: ?std.Thread = null; + var watch_stop: [2]c_int = .{ -1, -1 }; + defer if (inotify_fd >= 0) { + if (watch_reader) |thread| { + _ = host_io.writeFd(watch_stop[1], "x"); + thread.join(); + } + for (watch_stop) |fd| if (fd >= 0) { + _ = libc.close(fd); + }; + file_watch.stop(inotify_fd); + _ = libc.close(inotify_fd); + inotify_fd = -1; + }; + var watches: file_watch.Table = @splat(null); + var fs = ninep_io.start(io, gpa, core); + defer if (fs) |f| f.deinit(gpa); + + var shell: Shell = .{ + .core = core, + .gui = g, + .io = io, + .gpa = gpa, + .lsp_allocator = allocs.lsp, + .prompt_rcs = &prompt_rcs, + .ptys = &ptys, + .gens = &gens, + .queue = &queue, + .pipe_tasks = &pipe_tasks, + .inotify_fd = inotify_fd, + .watches = &watches, + .fs = fs, + .test_mode = test_mode, + .test_clock = if (test_mode) host_io.testClock() else null, + .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, + }; + defer shell.job_tasks.cancelAll(io); + defer shell.shutdownPtys(); + // A virtual clock never blinks: goldens and feel series hold still. + g.no_blink = shell.test_clock != null; + frame_probe = &core.frames; + frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; + const host = shell.host(); + core.host = host; + pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; + defer pardes.Kind.drawer = null; + shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .detached = detached }; + defer shell.peers.deinit(); + // Before the core goes: each client sees its link end. + defer shell.peers.dropAll(shell.core); + + while (core.nextEffect()) |e| core.perform(e); + // An upgraded session's shells, once a fresh session's own has a + // directory to adopt them in. + if (upgrade.resumed) |*rec| { + shell.resumePtys(rec); + while (core.nextEffect()) |e| core.perform(e); + } + for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = try queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), gens[id]); + }; + if (inotify_fd >= 0) { + watch_stop = try stopPipe(); + watch_reader = try std.Thread.spawn(.{}, watchThread, .{ inotify_fd, watch_stop[0], &queue }); + } + if (fs) |f| try f.watch(&queue, wakeFs); + + _ = c.SDL_StartTextInput(g.window); + // An upgraded session's window, its view's again. + if (upgrade.resumed) |*rec| if (!rec.fresh and !detached) shell.resumeWindow(); + + if (test_mode) setStdinRaw() catch {}; + shell.threads_ok = true; + pardes.lsp.setStatusSink(&queue, Queue.lspStatus); + defer pardes.lsp.setStatusSink(null, null); + host_io.setExitWake(&queue, Queue.wakeForExit); + defer host_io.setExitWake(null, null); + if (detached) { + shell.closeTheWindow(); + // Nothing else may wake the first wait. + daemon.watch(&shell, deliverNote); + } + + while (!core.quit) { + pardes.turn.bump(&pardes.turn.restores); + try core.pump(host); + // Its unit to each replica client, and theirs taken in. + shell.peers.boundary(core); + upgrade.locate(); + // Asked in the step (the word), done between steps: the session whole. + if (shell.upgrade_asked) |pane| shell.upgradeNow(pane); + // A window asked for again, or an adopted shell, from the daemon's + // thread through the queue; started after the first frame. + daemon.watch(&shell, deliverNote); + if (core.quit) break; // a session that ended does not restore into one + if (core.takeRestore()) |rp| blk: { + const nc = host_io.restoreCore(gpa, core, rp, &shell.peers, inotify_fd, &watches) orelse break :blk; + pipe_tasks.cancelAll(io); + queue.discardCompletions(); + // One view, the window's (host_io.restoreCore). + shell.gview = 0; + shell.stopPtys(); + g.cells.clearImages(); + g.prepared_images.clearRetainingCapacity(); + nc.view().frontend.native_images = true; + nc.view().frontend.native_image_patches = true; + nc.host = host; + if (fs) |f| f.reset(nc); + nc.view().frontend.windowed = true; + core.deinit(); + core = nc; + frame_probe = &nc.frames; // the old core's ring went with it + g.hit_core = nc; + shell.core = nc; + shell.surface = null; + observeGuiFont(g, core); + syncTaglineFont(g, core); + } + } + + if (fs) |f| { + f.deinit(gpa); + fs = null; + shell.fs = null; + } +} + +/// A window's link to a session elsewhere (`clientSession`): what the +/// window's input made, fed to the replica once its own view is put back, +/// and what the link's reader took off the stream. +const Client = struct { + link: replica.Link, + io: std.Io, + gpa: std.mem.Allocator, + /// The window's inputs since the last feed, their texts in `texts`: + /// read over its own view (`Replica.within`), applied after it. + pending: std.ArrayListUnmanaged(pardes.Event) = .empty, + texts: std.heap.ArenaAllocator, + /// The reader's, under `lock`: what it took, and whether the link ended. + lock: std.Io.Mutex = .init, + inbox: std.ArrayListUnmanaged(replica.Said) = .empty, + taken: std.ArrayListUnmanaged(replica.Said) = .empty, + ended: bool = false, + /// The size the window last posted while its view is not that size + /// yet (the session has not taken it, or speculation stopped at it): + /// posted once, not again each pass while it waits. + posted: ?@FieldType(pardes.Event, "resize") = null, + + fn deinit(cl: *Client) void { + cl.pending.deinit(cl.gpa); + cl.texts.deinit(); + cl.inbox.deinit(cl.gpa); + cl.taken.deinit(cl.gpa); + } + + fn post(cl: *Client, ev: pardes.Event) void { + var e = ev; + const a = cl.texts.allocator(); + switch (e) { + .key => |*k| k.text = a.dupe(u8, k.text) catch "", + .paste, .command => |*b| b.* = a.dupe(u8, b.*) catch return, + else => {}, + } + cl.pending.append(cl.gpa, e) catch {}; + } + + /// What the window's input made, applied at once and sent. + fn feed(cl: *Client) void { + for (cl.pending.items) |ev| { + const r = cl.link.r; + const predicted = r.echo.stats.predicted; + cl.link.input(ev); + // PARDES_TEST_LATENCY: the input, and whether it shows at once + // (applied, or its echo predicted), for the frame that shows it. + latencyNote("I {d} {d} {d}\n", .{ r.next_seq - 1, monoNs(), @intFromBool(r.applied == r.pending.items.len or r.echo.stats.predicted > predicted) }); + } + cl.pending.clearRetainingCapacity(); + _ = cl.texts.reset(.retain_capacity); + } + + /// The reader's: a message of the stream, for the loop, which it wakes. + fn said(cl: *Client, msg: replica.Said) bool { + cl.lock.lockUncancelable(cl.io); + defer cl.lock.unlock(cl.io); + cl.inbox.append(cl.gpa, msg) catch return false; + sdlWake(null); + return true; + } + + /// What the reader took, in its order, and the link's end after it. + fn takeSaid(cl: *Client) void { + cl.lock.lockUncancelable(cl.io); + std.mem.swap(std.ArrayListUnmanaged(replica.Said), &cl.inbox, &cl.taken); + const ended = cl.ended; + cl.lock.unlock(cl.io); + for (cl.taken.items) |msg| { + // PARDES_TEST_LATENCY: when a terminal's delta came (an echo's). + if (msg == .screen) latencyNote("S {d}\n", .{monoNs()}); + cl.link.take(msg); + // And after a unit, the first of its own inputs not confirmed. + if (msg == .unit) { + const r = cl.link.r; + latencyNote("U {d} {d}\n", .{ monoNs(), if (r.pending.items.len > 0) r.pending.items[0].seq else r.next_seq }); + } + } + cl.taken.clearRetainingCapacity(); + if (ended) { + cl.link.quit = true; + cl.link.gone = true; + } + } + + /// Its own view drawn in the window, outside any step, as the tty's + /// client draws its terminal (tui.zig `Client.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; + 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; + // Its render's end is marked as it presents (`present`). + core.frames.mark_render = core.frames.mark_update; + r.draw(.{ .ctx = s, .f = present }); + cl.link.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), if (s.gui) |g| frontendMoving(g) else false, cl.link.owed); + core.present_skipped = skipped; + core.needs_frame = needs; + cl.link.drawn(s.presented); + } +}; + +/// The session's stream, onto the client's inbox: its units, and its end. +fn clientReader(cl: *Client, fd: c_int, rest: *replica.Framer) void { + replica.readLink(cl.gpa, fd, rest, cl, Client.said); + cl.lock.lockUncancelable(cl.io); + cl.ended = true; + cl.lock.unlock(cl.io); + sdlWake(null); +} + +/// What the window does over its own view (`Replica.within`), its inputs +/// posted to the client (`Input.client`): an SDL event dispatched, its size +/// (the tagline's face too), the pointer under a frame that moved, the +/// timedemo's and the test feed's steps. +const OwnView = struct { + g: *Gui, + in: *Input, + s: *Shell, + sev: ?*const c.SDL_Event = null, + pointer: bool = false, + eof: bool = false, + + fn run(v: *OwnView, core: *pardes.Pardes) anyerror!void { + if (v.sev) |sev| return dispatch(v.g, v.in, sev); + const g = v.g; + if (syncReplicaFont(g, core, v.s.gpa)) v.s.client.?.link.dirty = true; + if (scrollRows(g, v.in, v.s.gpa)) v.s.client.?.link.dirty = true; + if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.client.?.link.dirty = true; + const geom = windowCells(g); + const cl = v.s.client.?; + if (resizeOf(core.view(), geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| { + if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) v.in.post(ev); + cl.posted = ev.resize; + } else cl.posted = null; + if (v.pointer) refreshPresentedPointer(g, v.in); + runDemo(g, v.in, core); + if (v.s.test_mode) { + if (v.s.feed.pump(v.s.gpa, v.in, g) catch return error.TestFeed) v.eof = true; + } + } +}; + +/// `pardes-gui --attach=:`: the window, made as a session's +/// is, a replica client of that session (docs/next-daemon.md, "Phase 6: GUI +/// replica notes"). Its own core, loaded from the session's dump, applies +/// its input at once (src/replica.zig) and draws its own view; the +/// session's units are the truth it rolls back to. The tty's `runClient`, with +/// a window for a terminal. +fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: Dial) !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 buf: [800]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes-gui: --attach: " ++ fmt ++ "\n", args) catch "pardes-gui: --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 + // and its stream in zstd, as the tty's client (replica.zig `Have`). + const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else to.far; + 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; + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + pardes.Term.start(allocs.image); + pardes.Kind.heap = allocs.addon; + pardes.syntax.start(allocs.tree_sitter); + defer { + pardes.Term.stop(); + pardes.syntax.stop(); + } + var o = opts_in; + o.image_allocator = allocs.image; + var joined: replica.Joined = undefined; + var r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + + var client: Client = .{ .link = .{ .r = r, .fd = joined.fd }, .io = io, .gpa = gpa, .texts = .init(gpa) }; + defer client.deinit(); + const link = &client.link; + try link.fromEnv(gpa, init.environ_map); + defer link.deinit(gpa); + // A client spawns, watches and serves nothing: the Shell's tables are + // empty ones, there for what draws. + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(0); + var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, .wake_fn = sdlWake }; + defer queue.deinit(); + var pipe_tasks: PipeTasks = .{}; + var watches: file_watch.Table = @splat(null); + const prompt_rcs: host_io.Shell.PromptFiles = .{}; + var shell: Shell = .{ + .core = r.core(), + .gui = g, + .io = io, + .gpa = gpa, + .lsp_allocator = allocs.lsp, + .prompt_rcs = &prompt_rcs, + .ptys = &ptys, + .gens = &gens, + .queue = &queue, + .pipe_tasks = &pipe_tasks, + .inotify_fd = -1, + .watches = &watches, + .test_mode = test_mode, + .client = &client, + }; + pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; + defer pardes.Kind.drawer = null; + defer shell.job_tasks.cancelAll(io); + g.no_blink = test_mode; + defer g.hit_core = null; + _ = c.SDL_StartTextInput(g.window); + if (test_mode) setStdinRaw() catch {}; + // A join a pass: the first, and one after the replica diverged or the + // session let it go to upgrade. The window stays as it is. + while (true) { + const core = r.core(); + g.session_font_request = null; + shell.core = core; + shell.gview = joined.view; + shell.surface = null; + g.hit_core = core; + frame_probe = &core.frames; + link.reset(r, &joined); + client.posted = null; + client.ended = false; + // ponytail: why it joined again is the window's title (and its + // log) until a key, where a terminal's client draws it over its + // frame: a window's frame is the core's cells, which it cannot write. + var titled = link.notice_len > 0; + if (titled) { + var title: [260]u8 = undefined; + _ = c.SDL_SetWindowTitle(g.window, std.fmt.bufPrintSentinel(&title, "pardes: {s}", .{link.notice()}, 0) catch "pardes"); + log.warn("{s}", .{link.notice()}); + } + const reader = try std.Thread.spawn(.{}, clientReader, .{ &client, joined.fd, &joined.rest }); + var in: Input = .{ .core = core, .shell = &shell, .client = &client }; + // What it is, then its size, are its view's first inputs. + link.input(.{ .frontend = .{ .windowed = true, .native_images = true, .native_image_patches = true } }); + var drew = false; + var again = false; + while (!link.quit) { + core.frames.period_ns = refreshNs(g); + var own: OwnView = .{ .g = g, .in = &in, .s = &shell, .pointer = drew }; + r.within(&own, OwnView.run); + client.feed(); + if (own.eof) break; + // Its predicted echo judged and caught up, once a frame. + if (r.echoFrame()) link.dirty = true; + drew = false; + if (link.dirty) { + client.draw(&shell); + drew = shell.presented; + } else if (again and shell.presented) if (shell.surface) |frame| { + // A blink, the window's own motion: the last frame again, + // moved on, as the session's own window draws it (pollFrame). + g.now_ns = shell.ownNow(); + shell.presented = renderFrame(g, gpa, core, frame) catch false; + drew = shell.presented; + }; + again = false; + // The window's own motions (its glide, its caret, a jump's + // trail) and its blink are on its clock: no unit need come. + const minimized = !test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; + const moving = !minimized and frontendMoving(g); + const blink = if (minimized or shell.surface == null) null else blinkNow(g, core.settings.cursor_blink); + const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; + // A latency trace's feed paces the loop, as the session's own + // window's (waitInput): its poll on stdin is the wait, and SDL's, + // which polls a clock and a lock a millisecond at a time with + // the offscreen driver, is not waited too (a frame a loop more). + var ms: c_int = if (latency_fd >= 0) 0 else if (test_mode) 16 else -1; + if (demoDue(g)) |due| ms = if (ms < 0) due else @min(ms, due); + if (predicting or link.owed) ms = if (ms < 0) frame_ms else @min(ms, frame_ms); + // A touchpad's fraction settling onto a row (scrollRows). + if (moving or g.scroll_lag != 0 or g.scroll_delta != 0) { + const frame_wait: c_int = @intCast(@max(1, (refreshNs(g) + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); + ms = if (ms < 0) frame_wait else @min(ms, frame_wait); + } + if (blink) |b| if (if (b.edge) refreshNs(g) else b.next_ns) |ns| { + const wait: c_int = @intCast(@min(std.math.maxInt(c_int), ns / std.time.ns_per_ms + 1)); + ms = if (ms < 0) wait else @min(ms, wait); + }; + if (link.quietCheck()) |wait| ms = if (ms < 0) @intCast(wait) else @min(ms, @as(c_int, @intCast(wait))); + // Idle, its frame drawn: the next input needs no copy taken. + if (ms != 0 or latency_fd >= 0) r.ready(); + if (shell.surface != null) startGamepads(g); + var sev = std.mem.zeroes(c.SDL_Event); + g.input_seen = false; + var got = c.SDL_WaitEventTimeout(&sev, ms); + const timed_out = !got; + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_USER) continue; + var one: OwnView = .{ .g = g, .in = &in, .s = &shell, .sev = &sev }; + r.within(&one, OwnView.run); + client.feed(); + if (link.quit) break; + } + client.takeSaid(); + // Its draws done (api.draw: this window's own pictures). + if (shell.takeDraws()) link.dirty = true; + r.settle(); + // A rollback since it drew: drawn again, never moved on from + // cells the copy put back. + if (r.moved) { + r.moved = false; + link.dirty = true; + } + if (titled and link.notice_len == 0) { + titled = false; + _ = c.SDL_SetWindowTitle(g.window, "pardes"); + } + if (link.owed or r.echo.changed) link.dirty = true; + if (moving or (blink != null and (blink.?.edge or timed_out))) again = true; + 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 reader ends with the link: what it took meanwhile is let go. + _ = libc.shutdown(joined.fd, 2); + reader.join(); + client.lock.lockUncancelable(io); + for (client.inbox.items) |msg| switch (msg) { + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .checked => {}, + }; + client.inbox.clearRetainingCapacity(); + client.lock.unlock(io); + _ = libc.close(joined.fd); + joined.rest.deinit(gpa); + 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) Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}); + return; + } + // The session again, the core it leaves held meanwhile. + r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, r) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + } +} + +const frame_ms: c_int = @intCast(pardes.frame_ns / std.time.ns_per_ms); + +const StdinFeed = struct { + parser: vaxis.Parser = .{}, + /// Inside the driver's bracketed paste: its keys are the paste's text. + in_paste: bool = false, + paste: std.ArrayList(u8) = .empty, + cache: vaxis.GraphemeCache = .{}, + buf: [1024]u8 = undefined, + fill: usize = 0, + last_cols: u16 = 0, + last_rows: u16 = 0, + + /// The test driver's keys and events since the last call, posted to + /// `in`; true once its input has ended. + fn pump(f: *StdinFeed, gpa: std.mem.Allocator, in: *Input, g: ?*Gui) !bool { + var ws: posix.winsize = std.mem.zeroes(posix.winsize); + if (posix.system.ioctl(0, posix.T.IOCGWINSZ, @intFromPtr(&ws)) == 0 and + ws.col > 0 and ws.row > 0 and ws.col <= 1000 and ws.row <= 1000 and + (ws.col != f.last_cols or ws.row != f.last_rows)) + { + f.last_cols = ws.col; + f.last_rows = ws.row; + applyResize(in, g, ws.col, ws.row); + } + + var fds = [_]posix.pollfd{.{ .fd = 0, .events = posix.POLL.IN, .revents = 0 }}; + pardes.turn.rest(); + const polled = posix.poll(&fds, 16); + pardes.turn.wake(); + _ = polled catch return false; + if ((fds[0].revents & posix.POLL.IN) == 0) return (fds[0].revents & (posix.POLL.HUP | posix.POLL.ERR)) != 0; + const rn = libc.read(0, f.buf[f.fill..].ptr, f.buf.len - f.fill); + if (rn < 0) return false; + if (rn > 0) latencyNote("R {d}\n", .{monoNs()}); + if (rn == 0) return true; + const len = f.fill + @as(usize, @intCast(rn)); + f.fill = 0; + + var seq_start: usize = 0; + while (seq_start < len) { + // ESC]777;;BEL, the driver's own: + // mouse;;;;[;] + // mouse;wheel;;;[;]: a mouse event at + // window pixels, built as SDL would and run through dispatch, + // so a driver exercises the real pointer path (pixel to cell, + // tag and body hits). SGR mouse carries only cells. + // finger;;;;; + // One the read cut short, or what may yet begin one, waits for + // the next read. + const rest = f.buf[seq_start..len]; + const osc = "\x1b]777;"; + if (std.mem.startsWith(u8, rest, osc) or std.mem.startsWith(u8, osc, rest)) { + const bel = std.mem.indexOfScalar(u8, rest, 0x07) orelse { + std.mem.copyForwards(u8, f.buf[0..rest.len], rest); + f.fill = rest.len; + break; + }; + seq_start += bel + 1; + const event = rest[osc.len..bel]; + const semi = std.mem.indexOfScalar(u8, event, ';') orelse event.len; + const fields = event[@min(semi + 1, event.len)..]; + if (std.mem.eql(u8, event[0..semi], "mouse")) { + if (g) |gp| { + var parts = std.mem.splitScalar(u8, fields, ';'); + const kind = parts.next() orelse ""; + const second = parts.next() orelse ""; + const button = std.fmt.parseInt(u8, second, 10) catch 0; + const x = std.fmt.parseFloat(f32, parts.next() orelse "") catch 0; + const y = std.fmt.parseFloat(f32, parts.next() orelse "") catch 0; + // An optional fifth field holds modifiers as xterm + // counts them: shift 4, meta (alt) 8, ctrl 16. + const held = std.fmt.parseInt(u8, parts.next() orelse "0", 10) catch 0; + var sev = std.mem.zeroes(c.SDL_Event); + const k = std.meta.stringToEnum(enum { wheel, focus, motion, down, up }, kind) orelse .up; + switch (k) { + .wheel => { + // ESC]777;mouse;wheel;;;BEL: + // a whole number is a mouse's notches, else a touchpad's. + const amount = std.fmt.parseFloat(f32, second) catch 0; + sev.type = c.SDL_EVENT_MOUSE_WHEEL; + sev.wheel.y = amount; + sev.wheel.integer_y = @intFromFloat(@trunc(amount)); + sev.wheel.mouse_x = x; + sev.wheel.mouse_y = y; + }, + // ESC]777;mouse;focus;<1 gained, 0 lost>;0;0BEL + .focus => sev.type = if (button != 0) c.SDL_EVENT_WINDOW_FOCUS_GAINED else c.SDL_EVENT_WINDOW_FOCUS_LOST, + .motion => { + sev.type = c.SDL_EVENT_MOUSE_MOTION; + sev.motion.x = x; + sev.motion.y = y; + sev.motion.state = if (button == 0 or button > 5) 0 else @as(u32, 1) << @intCast(button - 1); + }, + .down, .up => { + sev.type = if (k == .down) c.SDL_EVENT_MOUSE_BUTTON_DOWN else c.SDL_EVENT_MOUSE_BUTTON_UP; + sev.button.button = button; + sev.button.down = k == .down; + sev.button.x = x; + sev.button.y = y; + }, + } + const before = c.SDL_GetModState(); + var mods: c.SDL_Keymod = 0; + if (held & 4 != 0) mods |= c.SDL_KMOD_LSHIFT; + if (held & 8 != 0) mods |= c.SDL_KMOD_LALT; + if (held & 16 != 0) mods |= c.SDL_KMOD_LCTRL; + c.SDL_SetModState(mods); + dispatch(gp, in, &sev); + c.SDL_SetModState(before); + } + } else if (std.mem.eql(u8, event[0..semi], "finger")) { + if (parseFinger(fields)) |finger| if (g) |gp| { + var wpw: c_int = 0; + var wph: c_int = 0; + _ = c.SDL_GetWindowSizeInPixels(gp.window, &wpw, &wph); + const win_w: f32 = @floatFromInt(@max(wpw, 1)); + const win_h: f32 = @floatFromInt(@max(wph, 1)); + handleFinger(&gp.touch, in, finger, win_w, win_h, @floatFromInt(gp.cell_w), @floatFromInt(gp.cell_h), @floatFromInt(gp.tagline_width)); + }; + } + continue; + } + + const result = f.parser.parse(f.buf[seq_start..len], gpa) catch break; + if (result.n == 0) { // partial sequence: shift to front, read more + std.mem.copyForwards(u8, f.buf[0 .. len - seq_start], f.buf[seq_start..len]); + f.fill = len - seq_start; + break; + } + seq_start += result.n; + const event = result.event orelse continue; + switch (event) { + .key_press => |key| if (f.in_paste) { + // A newline reads as Ctrl-J, as the tty's paste has it. + const text = vaxis_input.pasteBytes(key); + f.paste.appendSlice(gpa, text) catch {}; + } else { + postKey(in, key, if (key.text) |t| f.cache.put(t) else ""); + }, + .paste_start => { + f.in_paste = true; + f.paste.clearRetainingCapacity(); + }, + .paste_end => { + f.in_paste = false; + if (f.paste.items.len > 0) in.post(.{ .paste = f.paste.items }); + f.paste.clearAndFree(gpa); + }, + .mouse => |m| { + 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, + .none => .none, + else => null, + }; + if (button) |b| { + in.post(.{ .mouse = .{ + .button = b, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + .col = @intCast(@max(m.col, 0)), + .row = @intCast(@max(m.row, 0)), + .ctrl = m.mods.ctrl, + .shift = m.mods.shift, + .alt = m.mods.alt, + } }); + } + }, + .winsize => |vw| { + applyResize(in, g, @intCast(vw.cols), @intCast(vw.rows)); + }, + .paste => |text| { + in.post(.{ .paste = text }); + gpa.free(@constCast(text)); + }, + else => {}, + } + } + return false; + } + + fn applyResize(in: *Input, g: ?*Gui, cols: u16, rows: u16) void { + if (g) |gp| { + _ = c.SDL_SetWindowSize(gp.window, @intCast(cols * gp.cell_w), @intCast(rows * gp.cell_h)); + _ = c.SDL_SyncWindow(gp.window); + } else { + in.post(.{ .resize = .{ .cols = cols, .rows = rows } }); + } + } +}; + +fn parseFinger(payload: []const u8) ?Finger { + var parts = std.mem.splitScalar(u8, payload, ';'); + const type_name = parts.next() orelse return null; + const id_s = parts.next() orelse return null; + const x_s = parts.next() orelse return null; + const y_s = parts.next() orelse return null; + const pressure_s = parts.next() orelse return null; + if (parts.next() != null) return null; + _ = std.fmt.parseFloat(f32, pressure_s) catch return null; + const Name = enum { SDL_EVENT_FINGER_DOWN, down, SDL_EVENT_FINGER_MOTION, motion, SDL_EVENT_FINGER_UP, up, SDL_EVENT_FINGER_CANCELED, cancel }; + const kind: @FieldType(Finger, "kind") = switch (std.meta.stringToEnum(Name, type_name) orelse return null) { + .SDL_EVENT_FINGER_DOWN, .down => .down, + .SDL_EVENT_FINGER_MOTION, .motion => .motion, + .SDL_EVENT_FINGER_UP, .up => .up, + .SDL_EVENT_FINGER_CANCELED, .cancel => .cancel, + }; + return .{ + .kind = kind, + .id = std.fmt.parseInt(u64, id_s, 10) catch return null, + .x = std.fmt.parseFloat(f32, x_s) catch return null, + .y = std.fmt.parseFloat(f32, y_s) catch return null, + }; +} + +fn setStdinRaw() !void { + var term = try posix.tcgetattr(0); + term.iflag.BRKINT = false; + term.iflag.ICRNL = false; + term.iflag.INPCK = false; + term.iflag.ISTRIP = false; + term.iflag.IXON = false; + term.oflag.OPOST = false; + term.lflag.ECHO = false; + term.lflag.ICANON = false; + term.lflag.IEXTEN = false; + term.lflag.ISIG = false; + term.cc[@backingInt(posix.V.MIN)] = 1; + term.cc[@backingInt(posix.V.TIME)] = 0; + try posix.tcsetattr(0, .NOW, term); +} + +/// A key parsed from the stdin a test window reads, posted as the tty +/// posts one (vaxis_input): F-keys, Insert and the keypad included. `text` +/// is the key's text as the feed keeps it. +fn postKey(in: *Input, key: vaxis.Key, text: []const u8) void { + var ev = vaxis_input.keyEvent(key); + ev.key.text = text; + in.post(ev); +} + +const Input = struct { + core: *pardes.Pardes, + /// The shell whose window this is (views.zig: its view is `gview`). + shell: ?*Shell = null, + /// A replica client's (`runClient`): its inputs go to its link, never + /// straight to the core, which only reads here. + client: ?*Client = null, + quit: bool = false, + + fn post(in: *Input, ev: pardes.Event) void { + if (in.client) |r| return r.post(ev); + // The window's input is its own view's, a replica client's input + // the session's last or not. + if (in.shell) |s| if (s.core.live != s.gview) { + _ = s.windowView(); + }; + in.core.update(ev); + } + + fn close(in: *Input) void { + if (in.client) |r| { + r.link.quit = true; + in.quit = true; + return; + } + if (in.shell) |s| { + // The window, with replica clients: they keep the session, + // as a Detach would, the daemon holding it. + if (s.peers.count() > 0 and daemon.kept()) return s.closeTheWindow(); + } + in.core.quit = true; + in.quit = true; + } +}; + +fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { + if (comptime builtin.os.tag == .macos) { + if (sev.type == c.ui_macos_trackpad_event_type()) { + dispatchTrackpad(g, in, @ptrCast(@alignCast(sev))); + return; + } + } + // An input's time, for its latency to the frame that answers it + // (FrameStats): SDL's stamp, moved onto the monotonic clock. + switch (sev.type) { + c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_WHEEL => { + g.input_seen = true; + g.input_ns = monoNs(); + if (frame_probe) |probe| probe.input(monoNs() -| (c.SDL_GetTicksNS() -| sev.common.timestamp)); + }, + else => {}, + } + switch (sev.type) { + c.SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED => { + updateDisplayScale(g.window); + // Underlines are drawn into the glyphs a logical pixel thick. + resetGlyphAtlas(g); + if (in.client) |r| { + r.link.dirty = true; + } else in.core.needs_frame = true; + }, + else => {}, + } + switch (sev.type) { + c.SDL_EVENT_QUIT => { + in.shell = null; + in.close(); + }, + c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), + c.SDL_EVENT_WINDOW_FOCUS_GAINED => { + in.post(.{ .focus = true }); + if (in.client == null) upgrade.noticeNewer(in.core); + }, + c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }), + c.SDL_EVENT_WINDOW_MOUSE_LEAVE => { + g.pointer_present = false; + in.post(.pointer_leave); + }, + c.SDL_EVENT_KEY_DOWN => { + g.live_ctrl = (sev.key.mod & c.SDL_KMOD_CTRL) != 0; + g.live_alt = (sev.key.mod & c.SDL_KMOD_ALT) != 0; + const step: f32 = if (!g.live_ctrl) 0 else switch (sev.key.key) { + c.SDLK_EQUALS, c.SDLK_PLUS, c.SDLK_KP_PLUS => font_px_step, + c.SDLK_MINUS, c.SDLK_UNDERSCORE, c.SDLK_KP_MINUS => -font_px_step, + else => 0, + }; + if (step != 0) return setFontPx(g, in, std.math.clamp(g.px + step, font_px_min, font_px_max)); + keyDown(in, sev.key.key, sev.key.mod); + }, + c.SDL_EVENT_KEY_UP => { + g.live_ctrl = (sev.key.mod & c.SDL_KMOD_CTRL) != 0; + g.live_alt = (sev.key.mod & c.SDL_KMOD_ALT) != 0; + }, + c.SDL_EVENT_TEXT_INPUT => { + const tptr = sev.text.text orelse return; + var tlen: usize = 0; + while (tptr[tlen] != 0) : (tlen += 1) {} + if (tlen == 0) return; + const text: []const u8 = tptr[0..tlen]; + const view = std.unicode.Utf8View.init(text) catch return; + var it = view.iterator(); + var at: usize = 0; + while (it.nextCodepoint()) |cp| : (at = it.i) { + in.post(.{ .key = .{ .cp = cp, .text = text[at..it.i], .ctrl = g.live_ctrl, .alt = g.live_alt } }); + } + }, + c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => { + const b = sev.button; + const raw_button = if (comptime builtin.os.tag == .macos) + (if (b.down) g.trackpad.press(b.button) else g.trackpad.release(b.button) orelse return) + else + b.button; + const button: pardes.Mouse.Button = switch (raw_button) { + 1 => .left, + 2 => .middle, + 3 => .right, + 4 => .back, + 5 => .forward, + else => return, + }; + const mc = pointAt(g, in.core, b.x, b.y); + var ev = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()); + // Let go past the window's edge (SDL follows a held button out + // of the window: Wayland's implicit grab, X11's capture). + const win = windowGeometry(g.window); + ev.outside = !b.down and (b.x < 0 or b.y < 0 or b.x >= win.window_w or b.y >= win.window_h); + in.post(.{ .mouse = ev }); + }, + c.SDL_EVENT_MOUSE_MOTION => { + const m = sev.motion; + const physical_held: ?pardes.Mouse.Button = if ((m.state & c.SDL_BUTTON_LMASK) != 0) + .left + else if ((m.state & c.SDL_BUTTON_MMASK) != 0) + .middle + else if ((m.state & c.SDL_BUTTON_RMASK) != 0) + .right + else + null; + // A trackpad's latched button (Trackpad.press), not SDL's. + const held: ?pardes.Mouse.Button = if (comptime builtin.os.tag == .macos) + (if (g.trackpad.forced) null else if (g.trackpad.button) |b| switch (b) { + 1 => .left, + 2 => .middle, + 3 => .right, + else => physical_held, + } else physical_held) + else + physical_held; + const mc = pointAt(g, in.core, m.x, m.y); + in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, pointerMods()) }); + }, + c.SDL_EVENT_MOUSE_WHEEL => { + const w = sev.wheel; + if (w.y == 0 and w.x == 0) return; + const mc = pointAt(g, in.core, w.mouse_x, w.mouse_y); + wheelAt(g, in, .{ .x = w.x, .y = w.y, .integer_y = w.integer_y, .mods = pointerMods() }, mc); + }, + c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP, c.SDL_EVENT_FINGER_CANCELED => { + const f = sev.tfinger; + // Indirect Mac touches are decoded by AppKit at the pointer, + // never as absolute positions across the window. + if (comptime builtin.os.tag == .macos) if (f.touchID == c.SDL_MOUSE_TOUCHID) return; + const finger: Finger = .{ + .kind = switch (sev.type) { + c.SDL_EVENT_FINGER_DOWN => .down, + c.SDL_EVENT_FINGER_MOTION => .motion, + c.SDL_EVENT_FINGER_UP => .up, + else => .cancel, + }, + .id = @intCast(f.fingerID), + .x = f.x, + .y = f.y, + }; + var pw: c_int = 0; + var ph: c_int = 0; + _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); + const win_w: f32 = @floatFromInt(@max(pw, 1)); + const win_h: f32 = @floatFromInt(@max(ph, 1)); + const fcw: f32 = @floatFromInt(g.cell_w); + const fch: f32 = @floatFromInt(g.cell_h); + handleFinger(&g.touch, in, finger, win_w, win_h, fcw, fch, @floatFromInt(g.tagline_width)); + }, + // The window's font size; a Linux touchpad's pinch stays unused. + c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => if (comptime builtin.os.tag == .macos) setFontPx(g, in, Trackpad.pinch(g.px, sev.pinch.scale)), + c.SDL_EVENT_GAMEPAD_ADDED => { + if (g.gamepad == null) g.gamepad = c.SDL_OpenGamepad(sev.gdevice.which); + }, + c.SDL_EVENT_GAMEPAD_REMOVED => { + if (g.gamepad) |pad| { + c.SDL_CloseGamepad(pad); + g.gamepad = null; + } + }, + c.SDL_EVENT_GAMEPAD_BUTTON_DOWN, + c.SDL_EVENT_GAMEPAD_BUTTON_UP, + c.SDL_EVENT_GAMEPAD_AXIS_MOTION, + c.SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN, + c.SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION, + c.SDL_EVENT_GAMEPAD_TOUCHPAD_UP, + => { + const pad_input: deck.Input = switch (sev.type) { + c.SDL_EVENT_GAMEPAD_BUTTON_DOWN, c.SDL_EVENT_GAMEPAD_BUTTON_UP => .{ .button = .{ + .idx = sev.gbutton.button, + .down = sev.gbutton.down, + } }, + c.SDL_EVENT_GAMEPAD_AXIS_MOTION => .{ .axis = .{ + .idx = sev.gaxis.axis, + .value = sev.gaxis.value, + } }, + else => .{ .touch = .{ + .pad = @intCast(std.math.clamp(sev.gtouchpad.touchpad, 0, 255)), + .phase = switch (sev.type) { + c.SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN => .down, + c.SDL_EVENT_GAMEPAD_TOUCHPAD_UP => .up, + else => .motion, + }, + .x = sev.gtouchpad.x, + .y = sev.gtouchpad.y, + .pressure = sev.gtouchpad.pressure, + } }, + }; + var acts: [3]deck.Action = undefined; + for (acts[0..g.deck.feed(pad_input, &acts)]) |act| switch (act) { + .move => |mv| { + const geometry = windowGeometry(g.window); + const old = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); + const dx = mv.dx * geometry.window_w / geometry.pixel_w; + const dy = mv.dy * geometry.window_h / geometry.pixel_h; + g.pad_x = std.math.clamp(g.pad_x + dx, 0, geometry.window_w - 1); + g.pad_y = std.math.clamp(g.pad_y + dy, 0, geometry.window_h - 1); + c.SDL_WarpMouseInWindow(g.window, g.pad_x, g.pad_y); + g.pointer_present = true; + const mc = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); + g.pointer_cell = mc; + if (mc.col == old.col and mc.row == old.row) continue; + const held = heldPointerButton(g); + in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); + }, + .click => |ck| { + const button: pardes.Mouse.Button = switch (ck.which) { + .select => .left, + .execute => .middle, + .look => .right, + }; + const mc = pointAt(g, in.core, g.pad_x, g.pad_y); + in.post(.{ .mouse = .{ + .button = button, + .kind = if (ck.down) .press else .release, + .col = mc.col, + .row = mc.row, + .tag_hit = mc.tag_hit, + .body_hit = mc.body_hit, + } }); + }, + .wheel => |ticks| { + const mc = pointAt(g, in.core, g.pad_x, g.pad_y); + var left = ticks; + while (left != 0) { + left += if (ticks > 0) -1 else 1; + in.post(.{ .mouse = .{ + .button = if (ticks > 0) .wheel_down else .wheel_up, + .kind = .press, + .col = mc.col, + .row = mc.row, + .tag_hit = mc.tag_hit, + .body_hit = mc.body_hit, + } }); + } + }, + .key => |k| in.post(.{ + .key = switch (k) { + .n => .{ .cp = 'n', .text = "n" }, + .cap_n => .{ .cp = 'N', .text = "N" }, + .enter => .{ .cp = pardes.Key.enter }, + .tab => .{ .cp = pardes.Key.tab }, + .tty_toggle => .{ .cp = in.core.opts.tty_toggle, .ctrl = true }, + }, + }), + .rumble => if (g.gamepad) |pad| { + _ = c.SDL_RumbleGamepad(pad, 0x4000, 0x4000, 80); + }, + }; + }, + else => {}, + } +} + +fn keyDown(in: *Input, sym: c.SDL_Keycode, mod: c.SDL_Keymod) void { + const ctrl = (mod & c.SDL_KMOD_CTRL) != 0; + const alt = (mod & c.SDL_KMOD_ALT) != 0; + const shift = (mod & c.SDL_KMOD_SHIFT) != 0; + const gui_mod = (mod & c.SDL_KMOD_GUI) != 0; + const cp: u21 = switch (sym) { + c.SDLK_RETURN, c.SDLK_KP_ENTER => pardes.Key.enter, + c.SDLK_BACKSPACE => pardes.Key.backspace, + c.SDLK_TAB => pardes.Key.tab, + c.SDLK_ESCAPE => pardes.Key.escape, + c.SDLK_LEFT => pardes.Key.left, + c.SDLK_RIGHT => pardes.Key.right, + c.SDLK_UP => pardes.Key.up, + c.SDLK_DOWN => pardes.Key.down, + c.SDLK_HOME => pardes.Key.home, + c.SDLK_END => pardes.Key.end, + c.SDLK_PAGEUP => pardes.Key.page_up, + c.SDLK_PAGEDOWN => pardes.Key.page_down, + c.SDLK_DELETE => pardes.Key.delete, + c.SDLK_INSERT => pardes.Key.insert, + c.SDLK_PRINTSCREEN => pardes.Key.print_screen, + c.SDLK_SCROLLLOCK => pardes.Key.scroll_lock, + c.SDLK_PAUSE => pardes.Key.pause, + c.SDLK_APPLICATION => pardes.Key.menu, + c.SDLK_F1...c.SDLK_F12 => pardes.Key.f1 + @as(u21, @intCast(sym - c.SDLK_F1)), + c.SDLK_F13...c.SDLK_F24 => pardes.Key.f1 + 12 + @as(u21, @intCast(sym - c.SDLK_F13)), + else => blk: { + if (!(ctrl or alt or gui_mod)) break :blk 0; + if (sym < 128 and sym >= ' ') break :blk @intCast(sym); + break :blk 0; + }, + }; + if (cp == 0) return; + in.post(.{ .key = .{ .cp = cp, .ctrl = ctrl, .alt = alt, .shift = shift } }); +} + +fn gridCellAtDimensions( + core: *const pardes.Pardes, + x: f32, + y: f32, + body_w: f32, + body_h: f32, + tagline_w: f32, +) MouseCell { + const row: u16 = @intFromFloat(@min(@floor(@max(y, 0) / @max(body_h, 1)), 10_000)); + var point: MouseCell = .{ .col = @intFromFloat(@min(@floor(@max(x, 0) / @max(body_w, 1)), 10_000)), .row = row }; + // On the rule over this row, which is where two panes meet if they do. + point.rule_above = row > 0 and @max(y, 0) - @as(f32, @floatFromInt(row)) * @max(body_h, 1) < dp(rule_grab_px); + if (onGrid(core, x / @max(body_w, 1), y / @max(body_h, 1))) for (core.surface.tagLayers()) |*layer| { + if (layer.tagHit(x, y, body_w, body_h, tagline_w, @floatFromInt(core.view().row_metrics.tagline_h))) |hit| { + point.tag_hit = hit; + break; + } + }; + return point; +} + +/// Whether a point, in cells, is on the grid. +fn onGrid(core: *const pardes.Pardes, x: f32, y: f32) bool { + return std.math.isFinite(x) and std.math.isFinite(y) and x >= 0 and y >= 0 and + x < @as(f32, @floatFromInt(core.view().screen_w)) and y < @as(f32, @floatFromInt(core.view().screen_h)); +} + +fn gridCellAtPixels(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { + var point = gridCellAtDimensions(core, x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width)); + if (onGrid(core, x / @as(f32, @floatFromInt(g.cell_w)), y / @as(f32, @floatFromInt(g.cell_h)))) for (core.surface.bodyLayers()) |*layer| { + if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| { + point.body_hit = hit; + break; + } + }; + return point; +} + +/// A wheel turned over grid cell `mc` (SDL's sign: up positive): the +/// part of dispatch after the pointer is placed, so a test can turn it. +fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { + if (w.y != 0 and std.math.isFinite(w.y)) { + const core = in.core; + const hit: ?usize = for (core.panes, 0..) |slot, i| { + if (slot == null) continue; + const r = core.view().rects[i]; + if (mc.col >= r.x and mc.col < r.x + r.w and mc.row >= r.y and mc.row < r.y + r.h) break i; + } else null; + if (g.scroll_pane) |old| if (hit == null or hit.? != old) { + resetScroll(g); + }; + if (hit) |id| { + const pane = core.panes[id].?; + if (pane.addon != null) { + // A kind's (a PDF's strip): the turn as it came, a + // touchpad's fraction of a notch too (pa_mouse.amount). + resetScroll(g); + in.post(.{ .mouse = .{ .button = if (w.y < 0) .wheel_down else .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt, .amount = @abs(w.y) } }); + } else if (!w.mods.shift and pane.isTerminal() and pardes.Term.modes(pane.terminal).wheel) { + // The program's (codex, htop, less): every whole turn goes + // to it, no glide, for nothing of ours moves. Shift keeps + // a terminal's wheel pardes's. + resetScroll(g); + g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y); + while (g.program_wheel >= 1) : (g.program_wheel -= 1) + in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); + while (g.program_wheel <= -1) : (g.program_wheel += 1) + in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); + } else if (in.client != null) { + // A replica client's notch is whole rows at once, with no + // glide; a touchpad's fraction is the window's picture + // (scrollRows), its whole rows ordinary inputs. + if (notchOf(w.y, w.integer_y)) |lines| { + g.program_wheel = @floatFromInt(lines); + } else { + g.scroll_pane = id; + g.scroll_col = mc.col; + g.scroll_row = mc.row; + g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); + } + while (g.program_wheel >= 1) : (g.program_wheel -= 1) + in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); + while (g.program_wheel <= -1) : (g.program_wheel += 1) + in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); + } else { + g.scroll_pane = id; + g.scroll_col = mc.col; + g.scroll_row = mc.row; + // A mouse wheel's notch is a whole line and + // glides (G6); a touchpad's fraction moves the + // picture by itself, under the finger. + if (notchOf(w.y, w.integer_y)) |lines| { + g.scroll_notch +|= lines; + } else g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); + } + } + } + var horizontal: i32 = if (w.x == 0 or !std.math.isFinite(w.x)) 0 else if (w.x > 0) 1 else -1; + if (w.precise and std.math.isFinite(w.x)) { + g.program_wheel_x += std.math.clamp(w.x, -64, 64); + horizontal = @intFromFloat(@trunc(g.program_wheel_x)); + g.program_wheel_x -= @floatFromInt(horizontal); + } + while (horizontal != 0) { + in.post(.{ .mouse = .{ + .button = if (horizontal > 0) .wheel_right else .wheel_left, + .kind = .press, + .col = mc.col, + .row = mc.row, + .tag_hit = mc.tag_hit, + .body_hit = mc.body_hit, + .ctrl = w.mods.ctrl, + .shift = w.mods.shift, + .alt = w.mods.alt, + } }); + horizontal += if (horizontal > 0) -1 else 1; + } +} + +/// `precise`: a Mac trackpad's columns (dispatchTrackpad), whose +/// horizontal fraction is kept toward the next turn. +const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, precise: bool = false, mods: PointerMods = .{} }; + +/// The window's font at `want` pixels: a key's step, a pinch. A client's +/// view is sized by its next loop, as its input. +fn setFontPx(g: *Gui, in: *Input, want: f32) void { + if (want == g.px) return; + g.px = want; + if (in.client) |r| { + refitFont(g, null); + r.link.dirty = true; + } else { + refitFont(g, in.core); + observeGuiFont(g, in.core); + } +} + +/// A Mac trackpad's gesture, decoded by macos_trackpad.m (Trackpad.zig's +/// policy): fingers, a pinch's zoom, a swipe's Back/Forward, a rotation's +/// n/N, a force click's Look, and a two-finger scroll by the pixel. +fn dispatchTrackpad(g: *Gui, in: *Input, ev: *const c.UITrackpadEvent) void { + g.input_seen = true; + switch (ev.kind) { + c.UI_TRACKPAD_FINGERS => g.trackpad.countFingers(@intCast(@max(ev.fingers, 0))), + c.UI_TRACKPAD_PINCH => if (g.trackpad.magnify(g.px, ev.a, ev.phase)) |want| setFontPx(g, in, want), + c.UI_TRACKPAD_HISTORY => { + if (ev.a == 0 or !std.math.isFinite(ev.a)) return; + const back = ev.a < 0; + const jumps = &in.core.view().jumps; + const can_jump = jumps.n > 0 and (if (back) jumps.cur > 0 else jumps.cur + 1 < jumps.n); + in.post(.{ .command = if (back) "Back" else "Forward" }); + if (comptime builtin.os.tag == .macos) if (can_jump) c.ui_macos_trackpad_haptic(); + }, + c.UI_TRACKPAD_ROTATE => { + const pane = in.core.panes[in.core.view().active] orelse return; + // Search-step keys never become text in insert/raw mode. + if (pane.body.mode != .normal) return; + var ticks = g.trackpad.rotate(ev.a, ev.phase); + while (ticks != 0) { + in.post(.{ .key = .{ .cp = if (ticks > 0) 'N' else 'n' } }); + if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_haptic(); + ticks += if (ticks > 0) -1 else 1; + } + }, + c.UI_TRACKPAD_PRESSURE => { + const previous = g.trackpad.force(ev.a) orelse return; + const mc = mouseCell(g, in.core, ev.x, ev.y); + in.post(.{ .mouse = pointerMouse(if (previous == 2) .middle else .left, .release, mc, pointerMods()) }); + in.post(.{ .mouse = pointerMouse(.right, .press, mc, pointerMods()) }); + in.post(.{ .mouse = pointerMouse(.right, .release, mc, pointerMods()) }); + }, + c.UI_TRACKPAD_SCROLL => { + const mc = pointAt(g, in.core, ev.x, ev.y); + // AppKit reports points; the grid is measured in backing pixels. + const geometry = windowGeometry(g.window); + const rows = ev.b * geometry.pixel_h / geometry.window_h / @as(f32, @floatFromInt(g.cell_h)); + const cols = -ev.a * geometry.pixel_w / geometry.window_w / @as(f32, @floatFromInt(g.cell_w)); + wheelAt(g, in, .{ .x = cols, .y = rows, .precise = true, .mods = pointerMods() }, mc); + }, + else => {}, + } +} + +/// The modifiers held with a pointer event, as the core's Mouse carries them. +const PointerMods = struct { ctrl: bool = false, shift: bool = false, alt: bool = false, super: bool = false }; + +/// The core's Mouse for an SDL press, release or move over cell `mc`. +fn pointerMouse(button: pardes.Mouse.Button, kind: pardes.Mouse.Kind, mc: MouseCell, mods: PointerMods) pardes.Mouse { + return .{ + .button = button, + .kind = kind, + .col = mc.col, + .row = mc.row, + .tag_hit = mc.tag_hit, + .body_hit = mc.body_hit, + .rule_above = (kind == .press or kind == .release) and mc.rule_above, + .ctrl = mods.ctrl, + .shift = mods.shift, + .alt = mods.alt, + .super = mods.super, + }; +} + +fn pointerMods() PointerMods { + const m = c.SDL_GetModState(); + return .{ .ctrl = (m & c.SDL_KMOD_CTRL) != 0, .shift = (m & c.SDL_KMOD_SHIFT) != 0, .alt = (m & c.SDL_KMOD_ALT) != 0, .super = (m & c.SDL_KMOD_GUI) != 0 }; +} + +fn mouseCellWithGeometry(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32, geometry: WindowGeometry) MouseCell { + const physical = windowPointToPixels(geometry, x, y); + return gridCellAtPixels(g, core, physical.x, physical.y); +} + +fn mouseCell(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { + return mouseCellWithGeometry(g, core, x, y, windowGeometry(g.window)); +} + +/// The pointer at window point (x, y), as an event or the gamepad puts it +/// there: where the window keeps it, and the cell under it. +fn pointAt(g: *Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { + g.pad_x = x; + g.pad_y = y; + g.pointer_present = true; + const mc = mouseCell(g, core, x, y); + g.pointer_cell = mc; + return mc; +} + +/// SDL's hit test, asked as the pointer moves over the window: a blank cell +/// of the workspace tag (tagline.workspaceBlank) is the window's to drag, as +/// a title bar is. SDL gives the compositor a B1 press there (Wayland's +/// xdg_toplevel.move, X11's _NET_WM_MOVERESIZE, macOS's own drag), so the +/// press never reaches the core; B2 and B3 there still do. +fn hitTest(_: ?*c.SDL_Window, area: [*c]const c.SDL_Point, data: ?*anyopaque) callconv(.c) c.SDL_HitTestResult { + const g: *Gui = @ptrCast(@alignCast(data orelse return c.SDL_HITTEST_NORMAL)); + const core = g.hit_core orelse return c.SDL_HITTEST_NORMAL; + if (area == null) return c.SDL_HITTEST_NORMAL; + const mc = mouseCell(g, core, @floatFromInt(area.*.x), @floatFromInt(area.*.y)); + return if (pardes.tagline.workspaceBlank(core, mc.col, mc.row, mc.tag_hit)) c.SDL_HITTEST_DRAGGABLE else c.SDL_HITTEST_NORMAL; +} + +fn heldPointerButton(g: *const Gui) ?pardes.Mouse.Button { + const buttons = c.SDL_GetMouseState(null, null); + if ((buttons & c.SDL_BUTTON_LMASK) != 0 or g.deck.r2_held or g.deck.rpad_click) return .left; + if ((buttons & c.SDL_BUTTON_MMASK) != 0 or g.deck.l2_held) return .middle; + if ((buttons & c.SDL_BUTTON_RMASK) != 0 or g.deck.look_held) return .right; + return null; +} + +fn refreshPresentedPointer(g: *Gui, in: *Input) void { + if (!g.pointer_present) return; + const mc = mouseCell(g, in.core, g.pad_x, g.pad_y); + const moved = g.pointer_cell == null or g.pointer_cell.?.col != mc.col or g.pointer_cell.?.row != mc.row; + g.pointer_cell = mc; + if (!moved) return; + const held = heldPointerButton(g); + in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); +} + +fn pollGamepad(g: *Gui, in: *Input) void { + const pad = g.gamepad orelse return; + const geometry = windowGeometry(g.window); + const deadzone: f32 = 8000; + const ax: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_RIGHTX)); + const ay: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_RIGHTY)); + const old = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); + const speed: f32 = @as(f32, @floatFromInt(g.cell_h)) * 0.4; + const speed_x = speed * geometry.window_w / geometry.pixel_w; + const speed_y = speed * geometry.window_h / geometry.pixel_h; + const pointer_moved = @abs(ax) > deadzone or @abs(ay) > deadzone; + if (@abs(ax) > deadzone) g.pad_x = std.math.clamp(g.pad_x + ax / 32767.0 * speed_x, 0, geometry.window_w - 1); + if (@abs(ay) > deadzone) g.pad_y = std.math.clamp(g.pad_y + ay / 32767.0 * speed_y, 0, geometry.window_h - 1); + if (pointer_moved) { + g.pointer_present = true; + c.SDL_WarpMouseInWindow(g.window, g.pad_x, g.pad_y); + } + const mc = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); + if (g.pointer_present) { + g.pointer_cell = mc; + if (mc.col != old.col or mc.row != old.row) { + const held = heldPointerButton(g); + in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); + } + } + const lx: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_LEFTX)); + const ly: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_LEFTY)); + if (@abs(ly) > deadzone) g.pad_scroll += ly / 32767.0 * 0.15; + if (@abs(lx) > deadzone) g.pad_scroll_h += lx / 32767.0 * 0.15; + while (@abs(g.pad_scroll) >= 1.0) { + const button: pardes.Mouse.Button = if (g.pad_scroll < 0) .wheel_up else .wheel_down; + g.pad_scroll += if (g.pad_scroll < 0) 1.0 else -1.0; + in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit } }); + } + while (@abs(g.pad_scroll_h) >= 1.0) { + const button: pardes.Mouse.Button = if (g.pad_scroll_h < 0) .wheel_left else .wheel_right; + g.pad_scroll_h += if (g.pad_scroll_h < 0) 1.0 else -1.0; + in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit } }); + } +} + +const Shell = struct { + core: *pardes.Pardes, + /// The window's, while one is open; null while detached (`detached` has + /// it). + gui: ?*Gui = null, + detached: ?*Gui = null, + /// Shells a dead session left (Adopt), each waiting for the spawn of + /// the terminal pane made for it. + adoptions: host_io.Adoptions = .{}, + io: std.Io, + gpa: std.mem.Allocator, + fs: ?*ninep_io.Listener = null, + lsp_allocator: std.mem.Allocator, + prompt_rcs: *const host_io.Shell.PromptFiles, + ptys: *[pardes.MAX_PANES]?Pty, + gens: *[pardes.MAX_PANES]u32, + queue: *Queue, + /// What drainQueue takes each wakeup, kept rather than rebuilt. + batch: Queue.Batch = .{}, + pipe_tasks: *PipeTasks, + job_tasks: PipeTasks = .{}, + inotify_fd: c_int, + watches: *file_watch.Table, + threads_ok: bool = false, + test_mode: bool = false, + feed: StdinFeed = .{}, + presented: bool = false, + skipped_presents: u8 = 0, + surface: ?*const pardes.Surface = null, + /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), in test mode. + test_clock: ?u64 = null, + /// The display rate a virtual clock stands in for (PARDES_TEST_HZ). + test_hz: u64 = 60, + /// The tick a paced frame is sampled at (waitInput): the clock the + /// core is advanced to while anything moves. + paced_ns: ?u64 = null, + /// The view the window shows (views.zig); a second window on the + /// session is a replica client of it (`pardes-gui --attach`). + gview: u8 = 0, + /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). + upgrade_asked: ?u8 = null, + /// This window a replica client of a session elsewhere (`runClient`). + client: ?*Client = null, + /// The session's replica clients (src/replica.zig), on sockets: views + /// of their own with no window here. + 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 (tui.zig's `mail_only`). + mail_only: bool = false, + waited: bool = false, + /// 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, + + fn closePaneShell(ctx: ?*anyopaque, pane: u8) void { + shellOf(ctx).closePty(pane); + } + + fn closePty(s: *Shell, pane: u8) void { + const pt = if (s.ptys[pane]) |*pt| pt else return; + // Out of the queue first, which lets go a reader waiting for room + // in it; then its read is canceled (or, at its end, it is joined). + s.queue.cancelReader(pane, s.gens[pane]); + if (pt.reader) |*reader| { + reader.cancel(s.queue.io); // the Io it was started on (startReader) + pt.reader = null; + } + _ = libc.close(pt.fd); + daemon.closed(pt.pid); + host_io.retireShell(pt.pid); + s.ptys[pane] = null; + } + + fn stopPtys(s: *Shell) void { + for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); + for (s.gens) |*gen| gen.* +%= 1; + } + + fn shutdownPtys(s: *Shell) void { + s.stopPtys(); + host_io.waitRetired(); + } + + fn reconcilePtys(s: *Shell) void { + for (s.ptys, 0..) |slot, pane| if (slot) |pt| { + const current = s.core.panes[pane]; + if (current == null or current.?.serial != pt.serial or !current.?.isTerminal()) + s.closePty(@intCast(pane)); + }; + } + + fn host(s: *Shell) pardes.Host { + return .{ .ctx = s, .vtable = &vtable }; + } + + /// Detach: the window closed, the session left running with no + /// window, for `pardes-gui --attach` to open one again. + fn detachWindow(ctx: ?*anyopaque) void { + const s = shellOf(ctx); + // A replica client's: its link ends. + if (s.peers.detach(s.core.live)) return; + if (s.gui == null) return s.core.reportFailure(s.core.view().active, "Detach: no window is open"); + if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session; closing its window ends it"); + s.closeTheWindow(); + } + + /// The window's own clock: the test's virtual one, the paced tick, else + /// SDL's. + fn ownNow(s: *const Shell) u64 { + return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); + } + + /// The Gui's window's view live, for what the window does to its own + /// (its size, its scroll): a replica client's input may have been the + /// last. True when it was not, and is now. + fn windowView(s: *Shell) bool { + if (s.core.live == s.gview or !pardes.views.isOpen(s.core, s.gview)) return false; + s.core.toView(s.gview); + return true; + } + + /// With replica clients, a wait takes one person's input and its pump + /// 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; + if (!s.peers.recording) return false; + const native_gesture = if (comptime builtin.os.tag == .macos) sev.type == c.ui_macos_trackpad_event_type() else false; + if (!native_gesture) switch (sev.type) { + c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP, c.SDL_EVENT_MOUSE_MOTION, c.SDL_EVENT_MOUSE_WHEEL, c.SDL_EVENT_WINDOW_FOCUS_GAINED, c.SDL_EVENT_WINDOW_FOCUS_LOST, c.SDL_EVENT_WINDOW_MOUSE_LEAVE, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP => {}, + else => return false, + }; + if (s.took_input) { + s.held = sev.*; + return true; + } + s.took_input = true; + return false; + } + + fn closeTheWindow(s: *Shell) void { + const g = s.gui orelse return; + closeWindow(g); + s.detached = g; + s.gui = null; + s.presented = false; + s.surface = null; + // Its clients look at it still (Peers keeps it attended). + s.peers.detached = true; + s.core.unattended = s.peers.count() == 0; + daemon.setState(true); + } + + fn openTheWindow(s: *Shell) void { + const g = s.detached orelse return; + if (!reopenWindow(g)) { + log.err("--attach: no window: {s}", .{c.SDL_GetError()}); + return daemon.setState(true); + } + s.gui = g; + s.detached = null; + s.peers.detached = false; + s.core.unattended = false; + s.core.needs_frame = true; + resetScroll(g); + daemon.setState(false); + } + + fn watched(ctx: ?*anyopaque) bool { + return shellOf(ctx).gui != null; + } + + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = shellOf(ctx); + s.adoptions.ask(s.core, pane); + } + + fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { + const s = shellOf(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 and + /// daemon link kept open across (upgrade.zig); the new process opens + /// its windows again. Returns only when it could not be, as it was. + fn upgradeNow(s: *Shell, pane: u8) void { + 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"); + // The new process starts SDL's video afresh, and that fails with no + // display at all (the screen off and its outputs gone): it ended the + // session (a detached one's hidden window needs one too). + var displays: c_int = 0; + if (c.SDL_GetDisplays(&displays)) |list| c.SDL_free(list); + if (displays == 0) return core.reportFailure(pane, "Upgrade: the display has no screen now (off, or gone), and the new build could not open its window; this session stays as it is until one is back"); + // 9P is served while the new binary is asked, 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, and what was read goes in: drained, + // the readers stopped (a reader waiting for room has it then), and + // what they pushed meanwhile drained. + s.drainQueue(); + for (s.ptys) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| { + r.cancel(s.queue.io); + pt.reader = null; + }; + s.drainQueue(); + 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, .window = s.gui != null, .exe = path }; + for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd); + var at_buf: [1024:0]u8 = undefined; + const failed = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why); + // As it was: its ptys read on. + for (s.ptys, 0..) |*slot, id| if (slot.*) |*pt| if (pt.fd >= 0 and pt.reader == null) { + pt.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), s.gens[id]) catch null; + }; + 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.adoptions.adoptShell(s.core, k.pid, k.fd); + continue; + } + s.ptys[k.pane] = .{ .fd = k.fd, .pid = k.pid, .serial = pane.?.serial, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; + } + } + + /// An upgraded session's window, its view's again; every other view + /// but a replica client's, kept for its rejoin (views.away), closes. + fn resumeWindow(s: *Shell) void { + s.gview = s.core.live; + for (0..pardes.views.max) |i| { + const k: u8 = @intCast(i); + if (k != s.gview and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.core.closeView(k); + } + } + + const vtable: pardes.Host.VTable = .{ + .wait_input = waitInput, + .now = guiNow, + .present = present, + .post_present = postPresent, + .poll_frame = pollFrame, + .watched = watched, + .detach = detachWindow, + .adopt = adopt, + .upgrade = upgradeAsked, + .spawn = spawnPane, + .pty_write = ptyWrite, + .pty_resize = ptyResize, + .pty_signal = ptySignal, + .close_pty = closePaneShell, + .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, + .start = host_io.startDetached, + .lsp = lsp, + .pipe = pipe, + .search = search, + .hand_over = handOver, + .job = kindJob, + }; + + /// The command panes' exits, told once their output is in (host_io). + fn takeExits(s: *Shell) void { + host_io.takeExits(s.core, s.ptys, s, closeWatched); + } + + fn closeWatched(s: *Shell, id: usize) void { + s.closePty(@intCast(id)); + } + + /// A client's queue holds its draws alone: each landed for its pane's + /// next paint. Whether any came. + fn takeDraws(s: *Shell) bool { + s.queue.takeInto(&s.batch); + for (s.batch.slice()) |m| switch (m) { + .kind_job => |j| { + s.job_tasks.finish(s.io, j.id); + j.land(s.core); + }, + else => m.deinit(s.gpa, s.lsp_allocator), + }; + return s.batch.slice().len > 0; + } + + fn drainQueue(s: *Shell) void { + s.reconcilePtys(); + // After this batch's output, which an exit is told behind. + defer s.takeExits(); + s.queue.takeInto(&s.batch); + const msgs = &s.batch; + if (msgs.len > 0) s.mail_only = false; + var check_files = false; + for (msgs.slice()) |m| switch (m) { + .output => |o| { + if (s.gens[o.pane] == o.gen) + s.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); + s.gpa.free(o.bytes); + }, + .eof => |e| { + if (s.gens[e.pane] == e.gen) eof: { + if (e.failure) |err| { + s.closePty(e.pane); + s.core.readerFailed(e.pane, err); + break :eof; + } + const pt = if (s.ptys[e.pane]) |*pt| pt else { + s.core.update(.{ .eof = .{ .pane = e.pane } }); + break :eof; + }; + // 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(s.core, s.ptys, e.pane, s, closeWatched); + break :eof; + } + // 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 unwatched = if (s.core.panes[e.pane]) |pane| pane.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status != null) pt.pid = 0; // reaped: no shell to retire + s.closePty(e.pane); + if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); + s.core.update(.{ .eof = .{ .pane = e.pane } }); + } + }, + .lsp => |l| { + s.core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } }); + if (l.rows) |rows| s.lsp_allocator.free(rows); + }, + .lsp_status => |text| { + var mbuf: [256]u8 = undefined; + s.core.setStatus(s.core.view().active, message.stamp(&mbuf, "lsp", text)); + s.lsp_allocator.free(text); + }, + .pipe => |response_value| { + var response = response_value; + s.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 => |b| { + s.core.update(.{ .search = b }); + b.deinit(s.gpa); + }, + .handed => |h| { + s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); + s.gpa.free(h.words); + }, + .kind_job => |j| { + s.job_tasks.finish(s.io, j.id); + j.land(s.core); + }, + .files_changed => check_files = true, + .fs_ready => {}, + .window => if (s.gui == null) s.openTheWindow(), + .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), + }; + if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) + s.queue.push(.files_changed); + } +}; + +fn wakeFs(ctx: ?*anyopaque) void { + const q: *Queue = @ptrCast(@alignCast(ctx.?)); + q.push(.fs_ready); +} + +fn shellOf(ctx: ?*anyopaque) *Shell { + return @ptrCast(@alignCast(ctx.?)); +} + +fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { + const s = shellOf(ctx); + const core = s.core; + var in: Input = .{ .core = core, .shell = s }; + s.mail_only = true; + s.took_input = false; + defer s.waited = true; + if (s.gui) |g| { + if (s.surface != null) startGamepads(g); + var sev = std.mem.zeroes(c.SDL_Event); + // Idle is asleep until an event: SDL's own, and the user events the + // shell's queue raises for a terminal's output, a completion, a file + // system request. What the shell moves or times itself polls every + // frame: a smooth scroll, a gamepad's sticks, the test stdin feed, + // a present to retry. A minimized window sleeps through the core's animation + // too: nothing shows it, and it is caught up at once when the window + // is back. + const polls = g.scroll_lag != 0 or g.scroll_delta != 0 or g.scroll_notch != 0 or frontendMoving(g) or g.gamepad != null or s.test_mode or core.needs_frame; + const minimized = !s.test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; + // A latency trace is fed on stdin, whose poll below paces the loop: + // waiting here too would make every tick cost two frames. + const poll_ms: c_int = 16; + const waited: c_int = if (latency_fd >= 0) 0 else if (minimized) -1 else if (timeout_ms != 0) @min(@as(c_int, @intCast(@min(timeout_ms, std.math.maxInt(c_int)))), if (polls) poll_ms else std.math.maxInt(c_int)) else if (polls) poll_ms else -1; + // The cursor's blink is the window's to time (Gui.input_ns): + // a frame a loop through an edge, else a wake at the next one; none + // while the window is minimized or unfocused. A virtual clock never + // blinks, so goldens hold still. + const blink = if (s.test_clock != null or minimized or s.surface == null) null else blinkNow(g, s.core.settings.cursor_blink); + const blink_ms: ?c_int = if (blink) |b| (if (b.edge) 1 else if (b.next_ns) |next| @as(c_int, @intCast(@min(std.math.maxInt(c_int), next / std.time.ns_per_ms + 1))) else null) else null; + const blinked: c_int = if (blink_ms) |b| (if (waited < 0) b else @min(waited, b)) else waited; + // The timedemo's next step is a wake too. + var ms: c_int = if (demoDue(g)) |due| (if (blinked < 0) due else @min(blinked, due)) else blinked; + // While anything moves, frames are paced as a game's are: one a + // display refresh, on a grid of ticks a period apart, each sampled + // at its tick (guiNow), however early or late the loop got there. + // Input that comes between two ticks is acted on as it comes (the + // core's state is never held back) and drawn at the next tick. Not + // paced, the loop ran as fast as it could present (the soft present + // has no vsync), ~230 frames a second on a 60 Hz display, and the + // compositor showed whichever was newest at each refresh: motion + // sampled at random phase, uneven steps, a judder in every scroll. + // ponytail: the period is the display mode's refresh and the grid's + // phase is our own, not the display's (no vblank time to read on the + // soft present); a 59.94 Hz display drifts a tick every 17 s. The + // upgrade: the presentation feedback protocol's timestamps. + const paced = s.test_clock == null and latency_fd < 0 and !s.test_mode and !minimized and frontendMoving(g); + var tick: u64 = 0; + if (paced) { + const period = refreshNs(g); + const now = c.SDL_GetTicksNS(); + // A motion from rest draws at once; one under way, at its next + // tick, skipping (never bunching) the ticks a slow frame missed. + tick = if (g.pace_ns != 0 and now -| g.pace_ns < 2 * period) g.pace_ns + period else now; + if (tick < now) tick += (now - tick) / period * period; + // Waited out polling, below. + ms = 0; + } + g.input_seen = false; + // An input held from the last wait (`split`) is this one's, at once. + const held = s.held; + s.held = null; + if (held) |h| sev = h; + // The wait is the 9P connections' turn with the core. + pardes.turn.rest(); + const got = held != null or c.SDL_WaitEventTimeout(&sev, ms); + pardes.turn.wake(); + // A virtual clock: while a render-time animation moves, each loop + // is a presented frame and moves it by one display frame + // (PARDES_TEST_HZ), events or not, as a real display's present + // would; otherwise a wait that ran out moves it exactly to the + // core's wake. + // Through an edge, or woken for the next: the shell redraws the last + // frame with the new alpha, no core render. + if (blink_ms != null and (blink.?.edge or !got)) g.blink_due = true; + if (s.test_clock) |*virtual| { + if (frontendMoving(g)) { + const display = virtual.* + std.time.ns_per_s / s.test_hz; + virtual.* = if (core.nextWake()) |due| @max(virtual.*, @min(due, display)) else display; + } else if (timeout_ms != 0 and (!got or !core.needs_frame)) { + // A wait that ran out, or one a stray event cut short while + // nothing owes a frame: time moves to the core's wake all + // the same, so a steady trickle of events (a pty's, the + // test feed's) cannot hold a virtual clock still forever. + virtual.* = @max(virtual.*, core.nextWake() orelse virtual.*); + } + } + if (got) { + // A run of queued motions is one move to its last position (the + // handler reads only absolute x/y and held buttons): acting on + // each would repeat hover and selection work the next undoes. + var motion: ?c.SDL_Event = null; + while (true) { + if (s.split(&sev)) break; + if (sev.type == c.SDL_EVENT_MOUSE_MOTION and (motion == null or motion.?.motion.windowID == sev.motion.windowID)) { + motion = sev; + } else { + if (motion) |*m| { + _ = s.windowView(); + dispatch(g, &in, m); + } + motion = null; + if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { + motion = sev; + } else { + _ = s.windowView(); + dispatch(g, &in, &sev); + } + } + if (!c.SDL_PollEvent(&sev)) break; + } + if (motion) |*m| { + _ = s.windowView(); + dispatch(g, &in, m); + } + } + runDemo(g, &in, core); + // Paced: what came before the tick is in; wait out the rest of it, + // unless an input came: its frame is drawn at once (the paced loop + // never adds a tick to an input's latency), and the ticks after it + // run from it. A stream's repeat too: the picture it moves is on + // the stream's straight line wherever it is sampled, so drawing it + // between two ticks costs no evenness, and holding it to the tick + // cost a held key 7 ms of latency. + if (paced and g.input_seen) tick = c.SDL_GetTicksNS(); + // The tick is waited out polling, not asleep, as a game's frame + // limiter spins: asleep between 60 Hz frames, the CPU's clock fell + // (intel_pstate, 4.9 GHz down toward 0.8) and every frame, an + // input's first among them, took 2-5x as long: input-to-present p50 + // 1.9 ms spinning against 7-8 ms asleep. + // ponytail: a core while something moves (~250 ms a scroll); a + // sleep to a millisecond short of the tick if the power matters more. + while (paced and !g.input_seen and s.held == null) { + if (tick -| c.SDL_GetTicksNS() < 50 * std.time.ns_per_us) break; + pardes.turn.rest(); + const more = c.SDL_PollEvent(&sev); + pardes.turn.wake(); + if (more) { + if (!s.split(&sev)) { + _ = s.windowView(); + dispatch(g, &in, &sev); + while (c.SDL_PollEvent(&sev)) { + if (s.split(&sev)) break; + _ = s.windowView(); + dispatch(g, &in, &sev); + } + } + } else { + // The events asked for every 100 µs, the core busy between. + const until = c.SDL_GetTicksNS() + 100 * std.time.ns_per_us; + while (c.SDL_GetTicksNS() < @min(until, tick)) std.atomic.spinLoopHint(); + } + runDemo(g, &in, core); + if (g.input_seen) tick = c.SDL_GetTicksNS(); + } + s.paced_ns = if (paced) tick else null; + if (paced) g.pace_ns = tick; + } else waitDetached(core, timeout_ms); + if (s.test_mode) { + if (s.feed.pump(s.gpa, &in, s.gui) catch true) { + core.quit = true; + return; + } + } + s.drainQueue(); + if (s.gui) |g| pollGamepad(g, &in); +} + +/// Detached: no window, asleep until the queue's wake (an SDL user event: +/// a pty's output, the daemon's window request), the core's next wake, or a +/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them, +/// messages go on the clock (the pump's, after this wait), which wakes it. +fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { + var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1; + for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { + ms = if (ms < 0) 100 else @min(ms, 100); + break; + }; + var sev = std.mem.zeroes(c.SDL_Event); + pardes.turn.rest(); + var got = c.SDL_WaitEventTimeout(&sev, ms); + pardes.turn.wake(); + while (got) : (got = c.SDL_PollEvent(&sev)) { + if (sev.type == c.SDL_EVENT_QUIT) core.quit = true; + } +} + +fn pollFrame(ctx: ?*anyopaque) void { + const s = shellOf(ctx); + s.reconcilePtys(); + const core = s.core; + if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); + // The authority owns its terminals even with its window closed. + pollCwds(core, s.ptys); + const g = s.gui orelse { + if (core.settings.window_opacity_pending) { + var unchanged_opacity: u8 = 100; + finishWindowOpacity(core, &unchanged_opacity, if (core.settings.window_opacity == 100) null else "requires a native SDL window"); + } + return; + }; + // A replica client's view live: the window's own view back before what + // the window does to it (its size, its scroll, its font). + if (core.live != s.gview) { + const geom = windowCells(g); + const due = g.scroll_pane != null or g.scroll_notch != 0 or g.glide.moving() or + core.settings.font.tagline_percent != g.tagline_percent or core.settings.font.pending or + (if (core.views[s.gview]) |*own| resizeOf(own, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height) != null else false); + if (due) _ = s.windowView(); + } + syncWindowOpacity(g, core); + core.frames.period_ns = refreshNs(g); + syncTaglineFont(g, core); + if (core.takeFontRequest()) |path| blk: { + const bytes = filesystem.readFile(s.gpa, path) catch { + core.rejectFont(); + break :blk; + }; + if (!g.atlas.setFont(s.gpa, bytes)) { + log.err("ui_font_new failed: {s}", .{path}); + core.rejectFont(); + break :blk; + } + if (core.settings.font.requested_size_hundredths != 0) + g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100; + setGuiFontName(g, core.settings.font.requested_name.get()); + refitFont(g, core); + acknowledgeGuiFont(g, core); + } + const geom = windowCells(g); + if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g); + stepScroll(g, core, s.gpa); + if (s.test_mode) writeTestStatus(g, core, s.presented); + // A blink edge, or the window's own motion (its glide, its caret, a + // jump's trail): the last frame again, moved on, no core render. + if ((g.blink_due or frontendMoving(g)) and !core.needs_frame and s.presented) if (s.surface) |frame| { + g.blink_due = false; + g.now_ns = s.ownNow(); + s.presented = renderFrame(g, s.gpa, core, frame) catch false; + }; +} + +/// PARDES_FRAMES_CAPTURE's directory, and how many frames it has. +var frame_capture_dir: ?[]const u8 = null; +var frame_capture_count: u32 = 0; + +fn captureSeries(pixels: []const u8, w: u32, h: u32) void { + const dir = frame_capture_dir orelse return; + var path_buf: [4096]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{d:0>6}.bgra", .{ dir, frame_capture_count }, 0) catch return; + const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, pixels.ptr, pixels.len); + _ = libc.close(fd); + const times = std.fmt.bufPrintSentinel(&path_buf, "{s}/times.txt", .{dir}, 0) catch return; + const tf = libc.open(times, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, @as(libc.mode_t, 0o644)); + if (tf < 0) return; + var line_buf: [96]u8 = undefined; + const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}\n", .{ frame_capture_count, monoNs(), w, h }) catch unreachable; // four numbers fit 96 + _ = libc.write(tf, line.ptr, line.len); + _ = libc.close(tf); + frame_capture_count += 1; +} + +/// The core's frame probe (FrameStats), for the latency of the inputs the +/// shell reads and the zones its own work goes in; null in tests. +var frame_probe: ?*pardes.FrameStats = null; + +/// How long until the timedemo's next step, ms; null when none runs. +fn demoDue(g: *const Gui) ?c_int { + const next = g.demo_next orelse return null; + if (g.demo_start_ns == 0 or next >= g.demo.len) return 0; + const at = g.demo_start_ns + @as(u64, g.demo[next].at_ms) * std.time.ns_per_ms; + return @intCast(@min(std.math.maxInt(c_int), (at -| monoNs()) / std.time.ns_per_ms)); +} + +/// PARDES_FRAMES_DEMO: the steps of FrameStats.demo whose time has come, +/// through the paths the window's own wheel and keys take, over the +/// focused pane's body; its clock starts at the first loop. Its end +/// ends the session (PARDES_FRAMES has the timings then). +fn runDemo(g: *Gui, in: *Input, core: *pardes.Pardes) void { + const v = core.view(); + const steps = g.demo; + var next = g.demo_next orelse return; + const now = monoNs(); + if (g.demo_start_ns == 0) { + g.demo_start_ns = now; + core.frames.demo_ns = now; + core.frames.demo = g.demo; + } + defer g.demo_next = next; + while (next < steps.len and g.demo_start_ns + @as(u64, steps[next].at_ms) * std.time.ns_per_ms <= now) : (next += 1) { + const r = v.rects[v.active]; + if (steps[next].act != .phase) g.input_seen = true; + switch (steps[next].act) { + .wheel => |notches| { + core.frames.input(now); + wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); + }, + .touch => |lines| { + core.frames.input(now); + wheelAt(g, in, .{ .y = -lines }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); + }, + .key => |key| { + core.frames.input(now); + in.post(.{ .key = key }); + }, + .phase => {}, + .click => |click| { + core.frames.input(now); + const pane = core.panes[v.active] orelse continue; + const top = core.bodyTop(pane, r); + const row: u16 = top + @as(u16, @intFromFloat(click.at * @as(f32, @floatFromInt(r.h -| pane.tag_rows -| 1)))); + const col: u16 = if (click.rail) r.x else r.x + config.GUTTER + 4; + for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| in.post(.{ .mouse = .{ .button = click.button, .kind = kind, .col = col, .row = row } }); + }, + .rail_wheel => |notches| { + core.frames.input(now); + wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x, .row = r.y + r.h / 2 }); + }, + .paste => |text| { + core.frames.input(now); + in.post(.{ .paste = text }); + }, + .exec => |line| { + core.frames.input(now); + var newest: u32 = 0; + for (core.panes) |slot| if (slot) |pane| { + newest = @max(newest, pane.serial); + }; + _ = pardes.exec.executeFrom(core, v.active, line, false); + // What it opened is what the next steps scroll. + for (core.panes, 0..) |slot, id| if (slot) |pane| if (pane.serial > newest) { + v.active = id; + core.needs_frame = true; + }; + }, + .end => in.close(), + } + } +} + +/// The blink now, from the frame's time since input and how long ago it +/// arrived; null where nothing blinks (off, idle, an unfocused window). +/// The cursor's opacity under blink: solid while typing and for +/// `hold_ns` after, then on and off with an eased edge, solid again after +/// `idle_ns` of no input. `edge` says whether it is mid-edge (a frame is +/// owed), `next_ns` when the next edge starts (a wake). +pub const Blink = struct { + pub const hold_ns: u64 = 500 * std.time.ns_per_ms; + pub const idle_ns: u64 = 10 * std.time.ns_per_s; + pub const half_ns: u64 = 530 * std.time.ns_per_ms; + pub const edge_ns: u64 = 80 * std.time.ns_per_ms; + + alpha: f32, + edge: bool, + next_ns: ?u64, + + pub fn at(now_ns: u64, input_ns: u64) Blink { + const since = now_ns -| input_ns; + if (since < hold_ns) return .{ .alpha = 1, .edge = false, .next_ns = input_ns + hold_ns + half_ns - edge_ns }; + if (since >= hold_ns + idle_ns) return .{ .alpha = 1, .edge = false, .next_ns = null }; + const t = (since - hold_ns) % (2 * half_ns); + const cycle_start = now_ns - t; + // On for a half, easing out over its last `edge_ns`; off for a half, + // easing back in over its last. + if (t < half_ns - edge_ns) return .{ .alpha = 1, .edge = false, .next_ns = cycle_start + half_ns - edge_ns }; + if (t < half_ns) return .{ .alpha = 1 - smooth(@as(f32, @floatFromInt(t - (half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; + if (t < 2 * half_ns - edge_ns) return .{ .alpha = 0, .edge = false, .next_ns = cycle_start + 2 * half_ns - edge_ns }; + return .{ .alpha = smooth(@as(f32, @floatFromInt(t - (2 * half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; + } + + fn smooth(x: f32) f32 { + const u = std.math.clamp(x, 0, 1); + return u * u * (3 - 2 * u); + } +}; + +fn blinkNow(g: *const Gui, on: bool) ?Blink { + if (g.no_blink or !on or !g.caret.placed) return null; + if (c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_INPUT_FOCUS == 0) return null; + const since = monoNs() -| g.input_ns; + // Relative to now: `next_ns` is how long until the next edge. + const b = Blink.at(since, 0); + return .{ .alpha = b.alpha, .edge = b.edge, .next_ns = if (b.next_ns) |next| next -| since else null }; +} + +/// One refresh of the display the window is on, in ns; a frame of the +/// core's where the display does not say. +fn refreshNs(g: *const Gui) u64 { + const mode = c.SDL_GetCurrentDisplayMode(c.SDL_GetDisplayForWindow(g.window)) orelse return pardes.frame_ns; + if (!(mode.*.refresh_rate > 1)) return pardes.frame_ns; + return @intFromFloat(@as(f64, std.time.ns_per_s) / mode.*.refresh_rate); +} + +fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8) void { + core.windowOpacityDone(applied.*, failure); + applied.* = core.settings.window_opacity; +} + +fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void { + if (!core.settings.window_opacity_pending) return; + // The first opacity under 100 on Wayland: the window made again, + // transparent, presenting through SDL_Renderer from then on (the + // capture's format, the swapchain's, is one it uploads). At a start's + // own WindowOpacity this is before its first frame, so unseen. + const unorm = g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM or g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + if (g.wayland and !g.present.surface_opacity and core.settings.window_opacity < 100 and unorm) { + // A `--detach` session's window stays hidden. + const hidden = c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_HIDDEN; + const mode = g.present.present_mode; + closeWindow(g); + g.present.soft_present = true; + g.present.surface_opacity = true; + g.present.present_mode = c.SDL_GPU_PRESENTMODE_VSYNC; + g.win_flags |= c.SDL_WINDOW_TRANSPARENT | hidden; + log.info("WindowOpacity under 100: the window made again, transparent, presenting through SDL_Renderer", .{}); + if (!reopenWindow(g)) { + // No renderer for it: opaque again, as it was. + g.present.soft_present = false; + g.present.surface_opacity = false; + g.present.present_mode = mode; + g.win_flags &= ~@as(c.SDL_WindowFlags, c.SDL_WINDOW_TRANSPARENT); + if (!reopenWindow(g)) core.quit = true; + } + g.win_flags &= ~hidden; + } + // Offscreen captures also support per-pixel alpha. Never approximate this + // with SDL_SetWindowOpacity: that would make foreground text translucent. + finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100) + null + else + "background transparency requires a native Wayland or alpha-capable SDL window"); +} + +fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { + const s = shellOf(ctx); + const core = s.core; + // A replica client draws outside the pump, which marks it there. + if (s.client != null) core.frames.mark_render = pardes.FrameStats.nowNs(); + const g = s.gui orelse return; + frame_started_ns = monoNs(); + const frame = surface; + s.surface = frame; + g.frame_arrival_ns = monoNs(); + g.now_ns = s.ownNow(); + s.presented = renderFrame(g, s.gpa, core, frame) catch |err| blk: { + log.err("render: {t}", .{err}); + break :blk false; + }; + // A skipped swapchain image would otherwise hide this input's frame until + // the next event. A few retries only: a minimized window never gets one. + s.skipped_presents = if (s.presented) 0 else s.skipped_presents +| 1; + if (!s.presented and s.skipped_presents <= 3) core.present_skipped = true; +} + +/// The gamepad subsystem, started once the first frame is drawn, as the +/// loop first waits: its scan (udev, hidapi, libusb) took 40 ms of a start. +/// A pad plugged in already is added by it (GAMEPAD_ADDED). +fn startGamepads(g: *Gui) void { + if (g.gamepads) return; + g.gamepads = true; + if (!c.SDL_InitSubSystem(c.SDL_INIT_GAMEPAD)) log.warn("SDL_InitSubSystem(GAMEPAD): {s}", .{c.SDL_GetError()}); +} + +fn postPresent(ctx: ?*anyopaque) void { + const s = shellOf(ctx); + const g = s.gui orelse return; + // No image (a minimized window): nothing was drawn to point at. + if (!s.presented) return; + // A client's view live: the window's frame counts when its own view is + // live and drawn. + if (s.core.live != s.gview) return; + var in: Input = .{ .core = s.core }; + refreshPresentedPointer(g, &in); + s.core.presented(); +} + +fn guiNow(ctx: ?*anyopaque) u64 { + const s = shellOf(ctx); + if (s.waited) { + s.waited = false; + if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns; + } + return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); +} + +fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + const s = shellOf(ctx); + if (s.adoptions.take(pane)) |a| return takeShell(s, 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.view().screen_h, s.core.view().screen_w) catch |err| { + if (running) return s.core.restartFailed(pane, err); + return s.core.shellFailed(pane, err); + }; + s.closePty(pane); + if (s.ptys[pane] != null) { + _ = libc.close(child.file.handle); + host_io.retireShell(child.pid); + return s.core.reportError(pane, "shell", error.WorkersBusy); + } + s.gens[pane] +%= 1; + const command = s.core.panes[pane].?.command != null; + const pt: Pty = .{ .fd = child.file.handle, .pid = child.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; + s.ptys[pane] = pt; + var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + if (host_io.shellCwd(pt.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); + if (!s.threads_ok) return; + s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { + s.closePty(pane); + return s.core.reportError(pane, "terminal reader", err); + }; +} + +/// An adopted shell, running already, as pane `pane`'s: told the size twice +/// (one it never had, then the pane's), which makes it redraw. +fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { + s.closePty(pane); + s.gens[pane] +%= 1; + s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .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) return; + s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { + s.closePty(pane); + return s.core.reportError(pane, "terminal reader", err); + }; +} + +/// The daemon's thread: what it says, onto the queue (drainQueue). +fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { + const s: *Shell = @ptrCast(@alignCast(ctx)); + const q = s.queue; + switch (note) { + .attach => |a| { + // A terminal for a window session: the daemon refuses that kind + // before it is sent, so only an old one's would be here. + if (a.tty >= 0) _ = libc.close(a.tty); + if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a window session takes no terminal"}); + if (a.tty < 0) q.push(.window); + }, + .adopted => |a| { + for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); + q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); + }, + // Joined at the next step boundary (Peers, any thread). + .replica => |j| s.peers.handed(j.fd, j.view), + } +} + +fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const s = shellOf(ctx); + if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.fd, bytes); +} + +fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + const s = shellOf(ctx); + if (s.ptys[pane]) |pt| { + const ws = host_io.ptyWinsize(s.core, cols, rows); + _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); + } +} + +fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + const s = shellOf(ctx); + // A command whose exit is recorded is reaped: its group may be another's. + if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); +} + +fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { + const s = shellOf(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.ttyTaken(pt.pid, pt.fd); +} + +fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { + const s = shellOf(ctx); + const pt = s.ptys[pane] orelse return null; + return host_io.foregroundName(pt.pid, pt.fd, buf); +} + +fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const s = shellOf(ctx); + const pt = s.ptys[pane] orelse return false; + return host_io.killJob(pt.pid, pt.fd); +} + +fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { + const s = shellOf(ctx); + host_io.writeFile(s.core, s.watches, pane, path, bytes); +} + +fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { + host_io.writeDump(shellOf(ctx).core, bytes); +} + +fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { + const s = shellOf(ctx); + if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, s.watches, pane, on, mode)) + s.queue.push(.files_changed); +} + +fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { + const s = shellOf(ctx); + if (file_watch.applyThemeEffect( + s.core, + s.gpa, + s.inotify_fd, + s.watches, + generation, + on, + )) s.queue.push(.files_changed); +} + +fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { + const s = shellOf(ctx); + host_io.dumpThemes(s.core, s.io, s.gpa, pane); +} + +fn putClipboard(gpa: std.mem.Allocator, text: []const u8) void { + const z = gpa.dupeSentinel(u8, text, 0) catch return; + defer gpa.free(z); + _ = c.SDL_SetClipboardText(z.ptr); +} + +fn takeClipboard() ?[:0]u8 { + const raw = c.SDL_GetClipboardText() orelse return null; + const text = std.mem.span(raw); + if (text.len == 0) { + c.SDL_free(raw); + return null; + } + return text; +} + +fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { + putClipboard(shellOf(ctx).gpa, text); +} + +fn readClipboard(ctx: ?*anyopaque) void { + const text = takeClipboard() orelse return; + defer c.SDL_free(text.ptr); + shellOf(ctx).core.update(.{ .paste = text }); +} + +fn openLink(ctx: ?*anyopaque, url: []const u8) void { + _ = ctx; + look.openLink(url); // desktop browser +} + +fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { + const s = shellOf(ctx); + if (s.threads_ok) return s.queue.startLsp(s.core, req); + s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); +} + +fn pipe(ctx: ?*anyopaque, id: u32) void { + const s = shellOf(ctx); + if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe); + s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); + s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); +} + +/// A draw (api.draw) on a worker, as a job is. +fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { + const s = shellOf(ctx); + return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob); +} + +fn kindJob(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { + const s = shellOf(ctx); + if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob); + host_io.KindJob.runHere(s.core, pane, serial, token); +} + +fn search(ctx: ?*anyopaque, gen: u32) void { + const s = shellOf(ctx); + if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.queue, Queue.pushSearch); + pardes.Stream.runHere(s.core, gen); +} + +/// Handover `seq`'s dump to its file, and a worker to carry it to another +/// window (Handover.start). A new window is as big as this one, and where +/// the pointer let go of it when the display lets a window say where it +/// goes (X11; on Wayland the compositor places it). +fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { + const s = shellOf(ctx); + const Handover = pardes.Handover; + const path = Handover.dumpPath(s.gpa, seq) catch |err| return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); + // A dump not written, or not carried, goes: what failed is said. + const cwd = std.Io.Dir.cwd(); + cwd.writeFile(s.io, .{ .sub_path = path, .data = bytes, .flags = .{ .permissions = .fromMode(0o600) } }) catch { + cwd.deleteFile(s.io, path) catch {}; + s.gpa.free(path); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = "cannot write its dump" } }); + }; + const job = s.gpa.create(Handover.Job) catch { + cwd.deleteFile(s.io, path) catch {}; + s.gpa.free(path); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = "out of memory" } }); + }; + job.* = .{ .gpa = s.gpa, .seq = seq, .path = path, .post = Queue.pushHanded, .post_ctx = s.queue }; + if (s.fs) |f| { + job.own_len = @min(f.path().len, job.own.len); + @memcpy(job.own[0..job.own_len], f.path()[0..job.own_len]); + } + if (s.gui) |g| { + var w: c_int = 0; + var h: c_int = 0; + _ = c.SDL_GetWindowSize(g.window, &w, &h); + var gx: f32 = 0; + var gy: f32 = 0; + _ = c.SDL_GetGlobalMouseState(&gx, &gy); + const placed = !std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); + const geometry = (if (placed) + std.fmt.bufPrint(&job.geometry, "{d}x{d}+{d}+{d}", .{ w, h, @as(i32, @intFromFloat(gx)) - 40, @as(i32, @intFromFloat(gy)) - 10 }) + else + std.fmt.bufPrint(&job.geometry, "{d}x{d}", .{ w, h })) catch unreachable; // four c_ints fit 64 + job.geometry_len = geometry.len; + } + s.core.handover.start(s.io, job) catch |err| { + cwd.deleteFile(s.io, path) catch {}; + s.gpa.free(path); + s.gpa.destroy(job); + return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); + }; +} + +fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { + for (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.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(id, cwd); + }; +} + +fn accumulateWheelDelta(pending: f32, raw_y: f32) f32 { + if (!std.math.isFinite(raw_y)) return pending; + const next = pending - raw_y; + return if (std.math.isFinite(next)) next else pending; +} + +fn boundScrollDelta(lag: f32, delta: f32, body_rows: u16) f32 { + const limit: f32 = @floatFromInt(body_rows); + return std.math.clamp(lag + delta, -limit, limit) - lag; +} + +fn applyScrollDelta(lag: f32, delta: f32) struct { lag: f32, rows: i32 } { + var l = lag + delta; + var rows: i32 = 0; + while ((delta > 0 and l > 0) or (delta < 0 and l < 0)) { + const down = l > 0; + l += if (down) -1 else 1; + rows += if (down) 1 else -1; + } + return .{ .lag = l, .rows = rows }; +} + +/// A mouse wheel's step as whole lines (down positive), or null for a +/// touchpad's fraction, which follows the finger as it is. +fn notchOf(raw_y: f32, integer_y: i32) ?i32 { + if (!std.math.isFinite(raw_y) or integer_y == 0 or raw_y != @round(raw_y)) return null; + return @intFromFloat(std.math.clamp(-raw_y, -64, 64)); +} + +const Glide = pardes.glide.Glide; + +/// Feeds a wheel's notches to the core, and keeps what moved the view for +/// the frame's glide (Glide.frame). +fn stepGlide(g: *Gui, core: *pardes.Pardes) void { + const notch = g.scroll_notch; + g.scroll_notch = 0; + var wheeled: ?usize = null; + if (notch != 0) wheel: { + const id = g.scroll_pane orelse break :wheel; + const pane = core.panes[id] orelse { + resetScroll(g); + break :wheel; + }; + const r = core.view().rects[id]; + if (r.h <= pane.tag_rows or r.w <= config.GUTTER) { + resetScroll(g); + break :wheel; + } + var left = notch; + while (left != 0) { + const down = left > 0; + left += if (down) -1 else 1; + const was = pane.scroll(); + // Shift: pardes's own scroll, never a program's wheel. + core.update(.{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = g.scroll_col, .row = g.scroll_row, .shift = true } }); + if (pane.scroll() == was) break; + wheeled = id; + } + if (wheeled != null) core.needs_frame = true; + } + if (wheeled != null) g.glide_wheeled = wheeled; + // Not a view a touchpad is moving by the pixel. + g.glide_direct = if (g.scroll_lag != 0 or g.scroll_delta != 0) g.scroll_pane else null; +} + +/// The window's own motions under way (its glide, its caret, a jump's +/// trail): it draws their frames itself, on its own clock. +fn frontendMoving(g: *const Gui) bool { + return g.glide.moving() or g.caret.moving() or g.trail.active; +} + +/// The frame's glide (Glide.frame) on the window's clock, with what moved +/// its view since the last. +fn glideFrame(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + g.glide.frame(gpa, surface, g.now_ns, g.glide_wheeled, g.glide_direct); + g.glide_wheeled = null; +} + +/// The window's loop over a text pane under a wheel, as waitInput and the +/// pump run it but with no window: a frame's turns (wheelAt), pollFrame's +/// stepScroll, and a frame drawn only when one is owed (the core's +/// needs_frame, or the window's own motion). `drawn` is the picture the +/// window shows, its first line and its offset, as of the last frame drawn; +/// `now` the picture as the window holds it. +const WheelRun = struct { + g: Gui, + core: *pardes.Pardes, + arena: std.heap.ArenaAllocator, + mc: MouseCell, + drawn: f32 = 0, + now_ns: u64 = std.time.ns_per_s, + + fn init(gpa: std.mem.Allocator, core: *pardes.Pardes) !WheelRun { + var wr: WheelRun = .{ .g = testGui(10, 20, 6, 12), .core = core, .arena = .init(gpa), .mc = undefined }; + const r = core.view().rects[core.view().active]; + wr.mc = .{ .col = r.x + 10, .row = r.y + r.h / 2 }; + core.advance(wr.now_ns); + _ = try core.render(wr.arena.allocator()); + try wr.frame(gpa, &.{}); + return wr; + } + + fn deinit(wr: *WheelRun, gpa: std.mem.Allocator) void { + wr.g.glide.deinit(gpa); + gpa.free(wr.g.scroll_edge); + wr.arena.deinit(); + } + + /// The picture as the window holds it now, in lines. + fn picture(wr: *const WheelRun) f32 { + const line: f32 = @floatFromInt(wr.core.panes[wr.core.view().active].?.scroll()); + return line + if (wr.g.glide.follow.offset != 0) wr.g.glide.follow.offset else wr.g.scroll_lag; + } + + /// One frame: SDL's turns (up positive), then a frame if one is owed. + fn frame(wr: *WheelRun, gpa: std.mem.Allocator, turns: []const f32) !void { + var in: Input = .{ .core = wr.core }; + for (turns) |y| wheelAt(&wr.g, &in, .{ .y = y, .integer_y = @intFromFloat(@trunc(y)) }, wr.mc); + wr.now_ns += std.time.ns_per_s / 60; + wr.core.advance(wr.now_ns); + stepScroll(&wr.g, wr.core, gpa); + if (!wr.core.needs_frame and !frontendMoving(&wr.g)) return; + _ = wr.arena.reset(.retain_capacity); + const s = try wr.core.render(wr.arena.allocator()); + wr.g.now_ns = wr.now_ns; + glideFrame(&wr.g, gpa, s); + wr.core.needs_frame = false; + wr.drawn = wr.picture(); + } +}; + +/// The scripted scroll sequence of the glide tests: a frame a 60 Hz +/// refresh, as the paced loop draws them (waitInput, then stepGlide, the +/// core's render and the frame's measure), an input on the frames `script` +/// names; each frame's picture offset and the core's first line. +const GlideRun = struct { + const Step = struct { frame: usize, key: pardes.Key }; + offsets: [600]f32 = undefined, + lines: [600]i64 = undefined, + carets: [600]f32 = undefined, + cells: [600]f32 = undefined, + frames: usize = 0, + + fn play(seq: *GlideRun, g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator, arena: *std.heap.ArenaAllocator, script: []const Step, frames: usize) !void { + var now: u64 = core.clock.now_ns; + var next: usize = 0; + for (0..frames) |frame| { + while (next < script.len and script[next].frame == frame) : (next += 1) core.update(.{ .key = script[next].key }); + now += std.time.ns_per_s / 60; + core.advance(now); + stepGlide(g, core); + _ = arena.reset(.retain_capacity); + const s = try core.render(arena.allocator()); + g.now_ns = now; + glideFrame(g, gpa, s); + seeCaret(g, s, fixedCellLayout(g), @floatFromInt(@as(u32, s.rows) * g.cell_h), now); + seq.offsets[frame] = g.glide.follow.offset; + seq.lines[frame] = @intCast(core.panes[core.view().active].?.file.?.scroll); + seq.carets[frame] = caretRow(g, s, now) orelse -1; + seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; + } + seq.frames = frames; + } + + /// The caret's invariants over the run: while its cell stays and it is + /// on it, it does not move a pixel; it only ever closes on its cell (a + /// twentieth of a row of play for a jump's bow); it lands within half a + /// second of its last change. + fn checkCaret(seq: *const GlideRun) !void { + var changed: usize = 0; + for (1..seq.frames) |k| { + if (seq.cells[k] < 0 or seq.cells[k - 1] < 0) continue; + if (seq.cells[k] != seq.cells[k - 1]) changed = k; + if (seq.cells[k] == seq.cells[k - 1] and seq.carets[k - 1] == seq.cells[k - 1]) try std.testing.expectEqual(seq.carets[k - 1], seq.carets[k]); + try std.testing.expect(@abs(seq.carets[k] - seq.cells[k]) <= @abs(seq.carets[k - 1] - seq.cells[k]) + 0.05); + if (k - changed == 30) try std.testing.expectEqual(seq.cells[k], seq.carets[k]); + } + } + + /// Frames from `from` until the picture is still: the scroll's glide. + fn settle(seq: *const GlideRun, from: usize) usize { + var k = from; + while (k < seq.frames and seq.offsets[k] != 0) k += 1; + return k - from; + } +}; + +fn resetScroll(g: *Gui) void { + g.scroll_pane = null; + g.scroll_delta = 0; + g.scroll_lag = 0; + g.scroll_idle = 0; + g.scroll_edge_len = 0; + g.scroll_notch = 0; + g.glide.stop(); +} + +/// Loop steps with no turn before a resting fraction settles; the share of +/// what is left a step takes (the glide's spring over a 60 Hz frame, +/// Follow.omega); and what is close enough to land on at once (under a +/// pixel of a row). +const settle_after = 2; +const settle_step: f32 = 1 - @exp(-pardes.glide.Follow.omega / 60.0); +const settle_land: f32 = 0.02; + +fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { + stepGlide(g, core); + var in: Input = .{ .core = core }; + _ = scrollRows(g, &in, gpa); +} + +/// A touchpad's fraction: the picture moved by it, and each whole row it +/// crosses posted to `in` (a replica client's go to its link, applied +/// after its view is parked again). True when the picture moved. +fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { + const core = in.core; + const id = g.scroll_pane orelse return false; + const pane = core.panes[id] orelse { + resetScroll(g); + return false; + }; + // A fine wheel's or a touchpad's turns stopped (SDL tells no gesture's + // end): the picture eases the rest of the way onto the core's row, on + // the glide's law, a step a frame, so it never rests a fraction of a + // row off its cells. The core's row is the next whole row the way the + // turns went (the lag is behind it going down, ahead going up), so the + // settle never moves against them; a turn mid-settle goes on from it. + if (g.scroll_delta != 0) { + g.scroll_idle = 0; + } else if (g.scroll_lag != 0 and g.glide.follow.offset == 0) { + g.scroll_idle +|= 1; + if (g.scroll_idle > settle_after) + g.scroll_delta = if (@abs(g.scroll_lag) < settle_land) -g.scroll_lag else -g.scroll_lag * settle_step; + } + const queued_delta = g.scroll_delta; + g.scroll_delta = 0; + if (queued_delta == 0) { + if (g.scroll_lag == 0 and g.scroll_notch == 0 and !g.glide.moving()) resetScroll(g); + return false; + } + const r = core.view().rects[id]; + if (r.h <= pane.tag_rows) { + resetScroll(g); + return false; + } + const delta = boundScrollDelta(g.scroll_lag, queued_delta, r.h - pane.tag_rows); + const st = applyScrollDelta(g.scroll_lag, delta); + var left = st.rows; + while (left != 0) { + const down = left > 0; + left += if (down) -1 else 1; + const was = pane.scroll(); + in.post(.{ + .mouse = .{ + .button = if (down) .wheel_down else .wheel_up, + .kind = .press, + .col = g.scroll_col, + .row = g.scroll_row, + .shift = true, // pardes's own scroll, never a program's wheel + }, + }); + // A replica client's rows apply after its view is parked again: + // its scroll has not moved yet. + if (in.client == null and pane.scroll() == was) { + resetScroll(g); + return false; + } + } + // The picture moved, by a fraction or back onto the core's row with + // the core where it was: that is a frame too, or the window rests on + // the last one, a fraction of a row off, and the next turn's frame + // jumps from there (against the turn when it reverses). + const moved = st.rows != 0 or st.lag != g.scroll_lag; + if (moved and in.client == null) core.needs_frame = true; + g.scroll_lag = st.lag; + g.scroll_rect = r; + const body_y = core.bodyTop(pane, r); + g.scroll_body_y = body_y; + g.scroll_body_h = r.h -| pane.tag_rows; + if (st.rows != 0) { + const s = &core.surface; + g.scroll_edge_len = 0; + if (r.w > config.GUTTER and r.h > pane.tag_rows and r.x + r.w <= s.cols) { + const bw = r.w - config.GUTTER; + const bh = g.scroll_body_h; + const k: u16 = @intCast(@min(@abs(st.rows), @as(i32, bh))); + const held = @min(pane.context_rows, bh - k); + const srow = body_y + (if (st.rows > 0) held + k - 1 else bh - k); + if (srow < s.rows) { + if (g.scroll_edge.len < bw) { + gpa.free(g.scroll_edge); + g.scroll_edge = gpa.alloc(pardes.Cell, bw) catch &.{}; + } + if (g.scroll_edge.len >= bw) { + @memcpy(g.scroll_edge[0..bw], s.cells[@as(usize, srow) * s.cols + r.x + config.GUTTER ..][0..bw]); + g.scroll_edge_len = bw; + } + } + } + } + if (g.scroll_lag == 0) resetScroll(g); + return moved; +} + +/// A scrolling body's picture: its rows moved by the lag, a glide's or a +/// touchpad's fraction of a row, and in the gap that opens the rows that +/// left. +fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: [3]u8, held: u16) u32 { + g.scroll_held_px = 0; + const glide = &g.glide; + const gliding = glide.follow.offset != 0; + const pane = if (gliding) glide.pane else g.scroll_pane orelse return 0; + const lag = if (gliding) glide.follow.offset else g.scroll_lag; + if (lag == 0) return 0; + const r = if (gliding) glide.rect else g.scroll_rect; + const bh = if (gliding) glide.body_h else g.scroll_body_h; + const y0 = if (gliding) glide.body_y else g.scroll_body_y; + const bw = r.w -| config.GUTTER; + const x0 = r.x + config.GUTTER; + if (bw == 0 or bh == 0 or x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us + // The scissor the shifted rows are drawn in is the scroll's. + g.scroll_rect = r; + g.scroll_body_y = y0; + g.scroll_body_h = bh; + var shifted = layout; + shifted.y_off -= lag * layout.h; + const kept = holdContext(g, surface, pane, held, bh, layout); + shifted.y_off += kept.lift; + // Only the rows the scissor shows: lagging a body or more, every body + // row is past the edge, and drawing them all was twice the frame's + // instances for the length of a long glide. + const gone: u16 = @intFromFloat(@min(@floor(@abs(lag)), @as(f32, @floatFromInt(bh)))); + var row = y0 + kept.rows + if (lag > 0) gone else 0; + const row_end = y0 + bh - if (lag < 0) gone else 0; + // A touchpad's block caret moves with its row; a glide's is drawn from + // its own springs (the quad), never carried by the text. + const caret: u32 = if (surface.cursor) |cu| (if (gliding or cu.bar) std.math.maxInt(u32) else @as(u32, cu.y) * surface.cols + cu.x) else std.math.maxInt(u32); + var n: u32 = 0; + while (row < row_end) : (row += 1) { + const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; + const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; + var col = x0; + while (col < x0 + bw) : (col += 1) { + emitInstance(g, instances, base + n, col, row, shifted, win_w, win_h, cellFontRole(&line[col]), line, col, row_cursor, @as(u32, row) * surface.cols + col == caret, page); + n += 1; + } + } + // A body layer's held rows are compact, so it has rows past the grid's + // (lifted into the body by what they save): the moving rows go on with + // them, or the band under the grid's last row shows the layer's, still. + if (pane < surface.body_layers.len and surface.body_layers[pane].context_rows != 0) { + const layer = &surface.body_layers[pane]; + if (layer.cols == bw) for (bh..layer.rows) |k| { + const line = layer.cells[k * layer.cols ..][0..layer.cols]; + for (0..bw) |c_i| { + emitInstance(g, instances, base + n, x0 + @as(u16, @intCast(c_i)), y0 + @as(u16, @intCast(k)), shifted, win_w, win_h, cellFontRole(&line[c_i]), line, c_i, null, false, page); + n += 1; + } + }; + } + if (!gliding) { + // A touchpad's fraction opens one row, the one that left: under the + // held rows, where the moving rows start. + if (g.scroll_edge_len >= bw) { + const erow: u16 = if (lag > 0) y0 + bh else y0 + kept.rows - 1; + var i: u16 = 0; + while (i < bw) : (i += 1) { + emitInstance(g, instances, base + n, x0 + i, erow, shifted, win_w, win_h, cellFontRole(&g.scroll_edge[i]), g.scroll_edge[0..bw], i, null, false, page); + n += 1; + } + } + return n; + } + // A glide's: rows past the top while the picture lags a move down, past + // the bottom for one up; as many as it opens. + const gap: u16 = @intFromFloat(@min(@ceil(@abs(lag)), @as(f32, @floatFromInt(@as(u32, bh) * Glide.reach)))); + const nkept = if (lag < 0) glide.nabove else glide.nbelow; + const rows = if (lag < 0) glide.above else glide.below; + for (0..@min(gap, nkept)) |i| { + const cells = rows[i * bw ..][0..bw]; + // Row -1 - i above the moving rows (under the held ones), or bh + i + // below the body, in grid rows. + const at_row: i32 = if (lag < 0) @as(i32, y0 + kept.rows) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); + var at = shifted; + // emitInstance takes an unsigned row: move the layout instead. + at.y_off += @as(f32, @floatFromInt(at_row - @as(i32, y0))) * layout.h; + for (0..bw) |c_i| { + emitInstance(g, instances, base + n, x0 + @as(u16, @intCast(c_i)), y0, at, win_w, win_h, cellFontRole(&cells[c_i]), cells, c_i, null, false, page); + n += 1; + } + } + return n; +} + +/// A scrolling body's tree-sitter context rows hold still: the shifted +/// rows start under them and are clipped below their band, and where a +/// body layer stacks them at the tagline's height +/// the rows under them are drawn up to meet them, where the layer has them. +fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh: u16, layout: CellLayout) struct { rows: u16, lift: f32 } { + const rows = @min(held, bh); + const layered = id < surface.body_layers.len and surface.body_layers[id].rows != 0 and surface.body_layers[id].context_rows != 0; + const row_px = if (layered) std.math.clamp(@as(f32, @floatFromInt(g.tagline_height)), 1, @max(1, layout.h)) else layout.h; + g.scroll_held_px = @as(f32, @floatFromInt(rows)) * row_px; + return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; +} + +fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { + const r = g.scroll_rect; + const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; + const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px; + const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; + const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px); + const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); + const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); + const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); + const y1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(py + ph))), y0, @as(i32, @intCast(sh))); + return .{ .x = x0, .y = y0, .w = x1 - x0, .h = y1 - y0 }; +} + +/// A placement the window shows as a texture: pixels, not glyph art. +fn texturePlacement(place: pardes.Placement) bool { + return !place.art.glyph and validImageBytes(place) != null; +} + +fn surfaceHasNativeKey(surface: *const pardes.Surface, key: u64) bool { + for (surface.placements.items) |place| { + if (texturePlacement(place) and place.key == key) return true; + } + return false; +} + +fn validImageBytes(place: pardes.Placement) ?u32 { + const r = place.raster; + // Rows packed: a texture upload takes no stride. + if (r.w == 0 or r.h == 0 or r.stride != r.w * 4) return null; + const bytes = std.math.mul(usize, r.stride, r.h) catch return null; + if (bytes > std.math.maxInt(u32)) return null; + return @intCast(bytes); +} + +/// Where the placement's pixels go in its cells: where it says, or fitted +/// there (no larger than it is, at the top left). +fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.NativeGeometry { + if (place.at) |at| return .{ .src = place.src, .dst = at }; + const bound_w = std.math.mul(u32, place.dst.w, g.cell_w) catch return null; + const bound_h = std.math.mul(u32, place.dst.h, g.cell_h) catch return null; + const fit = pardes.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null; + return .{ .src = place.src, .dst = fit.dst }; +} + +fn uploadNativeTexture( + g: *Gui, + gpa: std.mem.Allocator, + cmd: *c.SDL_GPUCommandBuffer, + place: pardes.Placement, +) !void { + const byte_len = validImageBytes(place) orelse return error.BadImage; + const r = place.raster; + const dirty: ?Cells.Dirty = if (place.dirty) |d| .{ .from = d.from, .y = d.y, .h = d.h } else null; + try g.cells.image(gpa, cmd, place.key, r.bytes()[0..byte_len], r.w, r.h, r.stride, dirty); +} + +fn appendPreparedImage(g: *Gui, gpa: std.mem.Allocator, place: pardes.Placement) void { + const texture = g.cells.native_images.get(place.key) orelse return; + if (nativePlaceGeometry(g, place) == null) return; + g.prepared_images.append(gpa, .{ .place = place, .texture = texture }) catch {}; +} + +fn emitPreparedImage( + g: *Gui, + surface: *const pardes.Surface, + instance: *ImageInstance, + prepared: PreparedImage, + win_w: f32, + win_h: f32, +) bool { + const place = prepared.place; + const body_x = @as(u32, place.dst.x) * g.cell_w; + const body_y = @as(u32, place.dst.y) * g.cell_h; + const geometry = nativePlaceGeometry(g, place) orelse return false; + // A strip's pictures lie at its whole pixel: up by the fraction left. + var scroll: f64 = 0; + for (surface.regionList()) |r| if (r.kind == .body and r.owner == place.pane) { + scroll = r.scroll_px; + break; + }; + const px0 = @as(f32, @floatFromInt(body_x + geometry.dst.x)); + const py0 = @as(f32, @floatFromInt(body_y + geometry.dst.y)) - @as(f32, @floatCast(scroll - @floor(scroll))); + const px1 = px0 + @as(f32, @floatFromInt(geometry.dst.w)); + const py1 = py0 + @as(f32, @floatFromInt(geometry.dst.h)); + const image_w: f32 = @floatFromInt(place.raster.w); + const image_h: f32 = @floatFromInt(place.raster.h); + instance.* = .{ + .x0 = (px0 / win_w) * 2.0 - 1.0, + .y0 = 1.0 - (py0 / win_h) * 2.0, + .x1 = (px1 / win_w) * 2.0 - 1.0, + .y1 = 1.0 - (py1 / win_h) * 2.0, + .u0 = @as(f32, @floatFromInt(geometry.src.x)) / image_w, + .v0 = @as(f32, @floatFromInt(geometry.src.y)) / image_h, + .u1 = @as(f32, @floatFromInt(geometry.src.x + geometry.src.w)) / image_w, + .v1 = @as(f32, @floatFromInt(geometry.src.y + geometry.src.h)) / image_h, + }; + return true; +} + +fn prepareNativeImages( + g: *Gui, + gpa: std.mem.Allocator, + cmd: *c.SDL_GPUCommandBuffer, + surface: *const pardes.Surface, + groups: *Groups, + sw: u32, + sh: u32, +) bool { + for (surface.placements.items) |place| { + if (!texturePlacement(place)) continue; + uploadNativeTexture(g, gpa, cmd, place) catch continue; + } + + while (true) { + var stale: [pardes.MAX_PANES]u64 = undefined; + var stale_len: usize = 0; + var iterator = g.cells.native_images.iterator(); + while (iterator.next()) |entry| { + if (surfaceHasNativeKey(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| g.cells.releaseImage(key); + if (stale_len < stale.len) break; + } + + g.prepared_images.clearRetainingCapacity(); + // The pictures are the page's: the other groups float over them. + for (surface.placements.items) |place| + if (texturePlacement(place)) appendPreparedImage(g, gpa, place); + prepareAddonGpu(g, gpa, cmd, surface); + groups.items[0].image_start = 0; + groups.items[0].image_count = std.math.cast(u32, g.prepared_images.items.len) orelse return false; + + const capacity = std.math.cast(u32, g.prepared_images.items.len) orelse return false; + if (capacity == 0) return true; + const instances = g.cells.mapImages(gpa, capacity) orelse return false; + const win_w: f32 = @floatFromInt(sw); + const win_h: f32 = @floatFromInt(sh); + var idx: u32 = 0; + for (g.prepared_images.items) |prepared| { + // Drawn in this order, instance by instance (Cells.drawImages). + g.cells.images.appendAssumeCapacity(.{ .premultiplied = prepared.premultiplied, .texture = prepared.texture, .clip = imageScissor(g, prepared.place) }); + if (!emitPreparedImage(g, surface, &instances[idx], prepared, win_w, win_h)) continue; + idx += 1; + } + std.debug.assert(idx == capacity); + g.cells.uploadImages(cmd, idx); + return true; +} + +fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect { + return .{ + .x = @intCast(@as(u32, place.dst.x) * g.cell_w), + .y = @intCast(@as(u32, place.dst.y) * g.cell_h), + .w = @intCast(@as(u32, place.dst.w) * g.cell_w), + .h = @intCast(@as(u32, place.dst.h) * g.cell_h), + }; +} + +fn renderFrame( + g: *Gui, + gpa: std.mem.Allocator, + core: *pardes.Pardes, + canonical: *const pardes.Surface, +) !bool { + // The pictures a pane asks to see as glyph art, drawn into a copy of + // the frame (Art.zig); the rest are textures. + if (g.art_arena == null) g.art_arena = .init(gpa); + _ = g.art_arena.?.reset(.retain_capacity); + const surface = g.art.frame(gpa, g.art_arena.?.allocator(), canonical, true, g.cell_h) catch canonical; + if (surface.pointer_shape != g.pointer_shape) { + g.pointer_shape = surface.pointer_shape; + const cursor = switch (g.pointer_shape) { + .link => g.link_cursor, + .box => g.box_cursor orelse g.arrow_cursor, + else => g.arrow_cursor orelse c.SDL_GetDefaultCursor(), + }; + if (cursor) |value| _ = c.SDL_SetCursor(value); + } + g.words.memo = .{}; // positional, and this frame's cells are new + const cmd = g.cells.begin() orelse return false; + var command_consumed = false; + defer if (!command_consumed) { + Cells.submit(cmd); + }; + const frame_target = try g.present.acquireTarget(cmd, g.window, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse { + command_consumed = true; + Cells.submit(cmd); + return false; + }; + const target = frame_target.texture; + const sw = frame_target.w; + const sh = frame_target.h; + const win_w: f32 = @floatFromInt(sw); + const win_h: f32 = @floatFromInt(sh); + + // The frame's CPU side: groups, decor, cover and every instance, up to + // their upload. + const build_zone = tracy.zone(@src(), "gui frame build"); + const probe_build = monoNs(); + var building = true; + defer if (building) build_zone.end(); + const layout = fixedCellLayout(g); + const chrome = &surface.chrome; + // G6: what the scroll just done moved the pane's rows by, measured on + // this frame against the last (the glide follows it from there). + for (core.panes, &g.glide.held) |slot, *held| held.* = if (slot) |pane| pane.context_rows else 0; + glideFrame(g, gpa, surface); + var groups: Groups = .{}; + const now = g.now_ns; + seeCaret(g, surface, layout, win_h, now); + // While the cursor glides or blinks the cells' cursors are not drawn; + // the focused one is the overlay's quad. One or the other every frame + // (none only at a blink's off half). + const blink_alpha: f32 = if (blinkNow(g, core.settings.cursor_blink)) |b| b.alpha else 1; + // While a glide moves the text, the caret is its quad, drawn from its + // own springs, not a cell of the moving rows. + const gliding = g.caret.moving(); + const quad_mode = g.caret.placed and (gliding or blink_alpha < 1 or g.glide.follow.offset != 0); + // A little less than solid while it glides, so the glyphs it passes + // stay legible; solid again as it lands. + const caret_alpha: f32 = if (gliding) 0.85 + 0.15 * std.math.clamp(1 - g.caret.remaining(now) / 0.5, 0, 1) else 1; + g.cursor_quad_alpha = if (quad_mode) caret_alpha * blink_alpha else 0; + // The probe's view of this frame's motion (FrameStats.Frame). + core.frames.scroll = g.glide.follow.offset; + core.frames.caret = caretRow(g, surface, now) orelse 0; + const cursors_shown = !quad_mode; + var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh); + if (overlay_count != 0 and !g.cells.uploadOverlay(cmd, g.overlay_vertices[0..overlay_count])) + overlay_count = 0; + if (!prepareNativeImages(g, gpa, cmd, surface, &groups, sw, sh)) { + g.prepared_images.clearRetainingCapacity(); + for (groups.items[0..groups.len]) |*group| { + group.image_start = 0; + group.image_count = 0; + } + } + + const cells: u32 = @as(u32, surface.cols) * surface.rows; + try g.cover.resize(gpa, cells); + const covered = g.cover.items[0..cells]; + dim.begin(core.settings.inactive_dim, surface.regionList()); + coverFrame(covered, surface.cols, surface.rows, surface.bodyLayers(), surface.tagLayers(), surface.regionList()); + try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); + + const page = chrome.page orelse bg_default; + const background_opacity = backgroundOpacity(g.applied_window_opacity); + const clear: c.SDL_FColor = .{ + .r = @as(f32, @floatFromInt(page[0])) / 255.0 * background_opacity, + .g = @as(f32, @floatFromInt(page[1])) / 255.0 * background_opacity, + .b = @as(f32, @floatFromInt(page[2])) / 255.0 * background_opacity, + .a = background_opacity, + }; + + var shifted: u32 = 0; + var row: u16 = 0; + while (row < surface.rows) : (row += 1) { + var col: u16 = 0; + while (col < surface.cols) : (col += 1) { + const at = @as(usize, row) * surface.cols + col; + if (covered[at].layer and !covered[at].floating) continue; + const group_index = if (covered[at].floating) groups.debug else 0; + groups.items[group_index].cell_count = std.math.add(u32, groups.items[group_index].cell_count, cellInstanceCount(&surface.cells[at])) catch return error.GpuCapacity; + } + } + for (surface.bodyLayers()) |*layer| { + if (layer.rows == 0) continue; + const group = &groups.items[0]; + const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; + for (0..layer.rows) |lr| { + if (layer.rowTop(@intCast(lr), layout.h, @floatFromInt(g.tagline_height)) >= bottom) break; + group.cell_count += layer.cols + @as(u32, if (lr < layer.context_rows) 1 else 0) + @as(u32, @intFromBool(layer.hasContextBorderAfter(lr))); + } + } + for (surface.tagLayers()) |*layer| { + if (layer.rows == 0) continue; + const group_index = if (layer.kind == .notice) groups.notices else 0; + groups.items[group_index].cell_count += (tagLayerCellCount(g, layer) + 1) * layer.rows; + } + var cell_next: [4]u32 = @splat(0); + var cell_total: u32 = 0; + for (groups.items[0..groups.len], 0..) |*group, index| { + group.cell_start = cell_total; + cell_next[index] = cell_total; + cell_total = std.math.add(u32, cell_total, group.cell_count) catch return error.GpuCapacity; + } + const decor_len: u32 = @intCast(g.decor.items.len); + if (cell_total != 0 or decor_len != 0) { + // The shifted rows of a scroll: its body, a glide's rows past it, and + // a body layer's rows past the grid's. + const capacity = std.math.add(u32, cell_total, 3 * cells + decor_len) catch return error.GpuCapacity; + const instances = try g.cells.mapCells(capacity) orelse { + command_consumed = true; + Cells.submit(cmd); + return false; + }; + const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else cells; + const cursor_bar = if (surface.cursor) |cu| cu.bar else false; + row = 0; + while (row < surface.rows) : (row += 1) { + const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; + const line_cover = covered[@as(usize, row) * surface.cols ..][0..surface.cols]; + const line_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; + var col: u16 = 0; + while (col < surface.cols) : (col += 1) { + const at = @as(usize, row) * surface.cols + col; + if (covered[at].layer and !covered[at].floating) continue; + const group_index = if (covered[at].floating) groups.debug else 0; + emitSurfaceCell( + g, + chrome, + instances, + &cell_next[group_index], + col, + row, + layout, + win_w, + win_h, + line, + line_cover, + col, + line_cursor, + cursors_shown and at == cursor_idx and !cursor_bar and bodyLayerIn(surface.bodyLayers(), col, row) == null, + page, + ); + } + } + // Body layers first: a notice chip over a tree-sitter context band + // is a tag layer, and instances paint in emission order. + for (surface.bodyLayers()) |*layer| { + if (layer.rows == 0) continue; + emitBodyLayer(g, instances, &cell_next[0], layer, win_w, win_h, page, cursors_shown, chrome.topbar_rule); + } + for (surface.tagLayers()) |*layer| { + if (layer.rows == 0) continue; + // A notice floats over the panes. + const group_index = if (layer.kind == .notice) groups.notices else 0; + emitTagLayer(g, instances, &cell_next[group_index], layer, win_w, win_h, page, cursors_shown); + } + for (groups.items[0..groups.len], 0..) |group, index| + std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); + // The body's context rows, which its scroll leaves where they are. + const scrolling: ?usize = if (g.glide.follow.offset != 0) g.glide.pane else g.scroll_pane; + const held: u16 = if (scrolling) |id| if (core.panes[id]) |pane| pane.context_rows else 0 else 0; + shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); + @memcpy(instances[cell_total + shifted ..][0..decor_len], g.decor.items); + g.cells.uploadCells(cmd, cell_total + shifted + decor_len, &g.atlas); + } + + build_zone.end(); + building = false; + if (frame_probe) |probe| probe.zone(.gui_build, probe_build); + // Drawn only over a scroll's shifted rows (scrollScissor asks a scroll). + const scroll_clip = if (shifted != 0) scrollScissor(g, layout, sw, sh) else std.mem.zeroes(c.SDL_Rect); + g.cells.record(cmd, target, sw, sh, clear, background_opacity, groups.items[0..groups.len], groups.ink, cell_total, shifted, scroll_clip, overlay_count); + + command_consumed = true; + return finishFrame(g, gpa, cmd, frame_target); +} + +/// Submits the frame: captured, handed to the soft presenter, or presented. +fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Present.Target) !bool { + if (g.present.capture) { + try captureFrame(g, gpa, cmd, target.texture, target.w, target.h); + return true; + } + var took: Present.Timings = .{}; + const presented = try g.present.finishFrame(cmd, target, &captureSeries, &took); + // A soft present's wait for the GPU, its upload of the frame and its flip. + if (g.present.soft_present) if (frame_probe) |probe| { + const now = monoNs(); + probe.zone(.gui_wait, now -| took.wait_ns); + probe.zone(.gui_upload, now -| took.upload_ns); + probe.zone(.gui_flip, now -| took.flip_ns); + }; + return presented; +} + +const ResolvedCell = struct { + slot: Slot, + fg: [3]u8, + bg: [3]u8, + role: pardes.FontRole, +}; + +const taglineBandOffset = pardes.Layer.taglineBandOffset; + +/// The colours and atlas slot of `line[at]`. `cursor` is where the cursor sits +/// in `line`, block or bar: shaping breaks around it. +fn resolveCell(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole, is_cursor: bool, page: [3]u8) ResolvedCell { + const cell = &line[at]; + var fg = fg_default; + var bg = page; + var reverse = is_cursor; + if (!cell.default) { + const st = cell.style; + fg = switch (st.fg) { + .default => fg_default, + .index => |i| pardes.colors.xterm[i], + .rgb => |rgb| rgb, + }; + switch (st.bg) { + .default => {}, + .index => |i| bg = pardes.colors.xterm[i], + .rgb => |rgb| bg = rgb, + } + if (st.reverse) reverse = !reverse; + if (st.invisible) { + fg = bg; + // With a translucent background, painting bg-colored glyphs at + // full opacity would expose text that the terminal concealed, so + // cellSlot draws a concealed cell blank. + } + if (st.dim) for (&fg) |*ch| { + ch.* = @intCast(@as(u16, ch.*) * 6 / 10); + }; + } + if (reverse) std.mem.swap([3]u8, &fg, &bg); + + return .{ + .slot = cellSlot(g, line, at, cursor, role), + .fg = fg, + .bg = bg, + .role = role, + }; +} + +fn cellFontRole(cell: *const pardes.Cell) pardes.FontRole { + return if (cell.default) .body else cell.style.font_role; +} + +fn cellInstanceCount(cell: *const pardes.Cell) u32 { + return if (cellFontRole(cell) == .tagline) 2 else 1; +} + +fn tagLayerCellCount(g: *const Gui, layer: *const pardes.Layer) u32 { + const pixels = @as(u32, layer.viewport.w) * g.cell_w; + return @min(layer.cols, (pixels + g.tagline_width - 1) / g.tagline_width); +} + +fn emitTagLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const pardes.Layer, win_w: f32, win_h: f32, page: [3]u8, show_cursor: bool) void { + const bw: f32 = @floatFromInt(g.cell_w); + const bh: f32 = @floatFromInt(g.cell_h); + const tw: f32 = @floatFromInt(g.tagline_width); + const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; + const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; + const background: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = layer.bg } } }; + // A window is rarely a whole number of cells wide: a band that ends at + // the last column runs on through the leftover pixels to the edge. + const band_right = if (win_w - right < bw) @max(right, win_w) else right; + const faded = (layer.kind == .pane or layer.kind == .notice) and dim.of(layer.id); + // A row to each line, each a grid row with the tagline's glyphs. + for (0..layer.rows) |index| { + const y = layer.viewport.y + @as(u16, @intCast(index)); + emitInstance(g, instances, next.*, 0, y, .{ .w = band_right - left, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, .body, (&background)[0..1], 0, null, false, page); + next.* += 1; + const cells = layer.cells[index * layer.cols ..][0..layer.cols]; + const line_cursor: ?usize = if (layer.cursor) |cu| (if (cu.y == index) cu.x else null) else null; + for (0..tagLayerCellCount(g, layer)) |col| { + const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == index else false; + emitInstance(g, instances, next.*, @intCast(col), y, .{ .w = tw, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, .tagline, cells, col, line_cursor, cursor, page); + clipInstance(&instances[next.*], .{ -1e9, -1e9, right, 1e9 }, win_w, win_h); + if (faded and !cursor) dim.fade(&instances[next.*]); + next.* += 1; + } + } +} + +fn bodyLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { + for (layers) |*layer| { + const r = layer.viewport; + if (layer.rows > 0 and col >= r.x and col - r.x < r.w and row >= r.y and row - r.y < r.h) return layer; + } + return null; +} + +fn emitBodyLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const pardes.Layer, win_w: f32, win_h: f32, page: [3]u8, show_cursor: bool, border_rgb: [3]u8) void { + const bw: f32 = @floatFromInt(g.cell_w); + const bh: f32 = @floatFromInt(g.cell_h); + const tw: f32 = @floatFromInt(g.tagline_width); + const th: f32 = @floatFromInt(g.tagline_height); + const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; + const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; + const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * bh; + const faded = dim.of(layer.id); + for (0..layer.rows) |index| { + const row: u16 = @intCast(index); + const top = layer.rowTop(row, bh, th); + if (top >= bottom) break; + const height = layer.rowHeight(row, bh, th); + const header = row < layer.context_rows; + const role: pardes.FontRole = if (header) .tagline else .body; + const width = if (header) tw else bw; + if (header) { + var background: pardes.Cell = .{ .default = false, .style = layer.cells[index * layer.cols].style }; + background.style.font_role = .body; + emitInstance(g, instances, next.*, 0, 0, .{ .w = @as(f32, @floatFromInt(layer.viewport.w)) * bw, .h = height, .x_off = left, .y_off = top }, win_w, win_h, .body, (&background)[0..1], 0, null, false, page); + clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); + next.* += 1; + } + const line = layer.cells[index * layer.cols ..][0..layer.cols]; + const line_cursor: ?usize = if (layer.cursor) |cu| if (cu.y == row) cu.x else null else null; + for (0..layer.cols) |col| { + if (left + @as(f32, @floatFromInt(col)) * width >= right) break; + const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == row else false; + const glyph_top = top - (if (header) @as(f32, @floatFromInt(taglineBandOffset(0, win_h, g.cell_h, g.tagline_height))) else 0); + emitInstance(g, instances, next.*, 0, 0, .{ .w = width, .h = height, .x_off = left + @as(f32, @floatFromInt(col)) * width, .y_off = glyph_top }, win_w, win_h, role, line, col, line_cursor, cursor, page); + clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); + if (faded and !cursor) dim.fade(&instances[next.*]); + next.* += 1; + } + if (layer.hasContextBorderAfter(row)) { + const border: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = border_rgb } } }; + emitInstance(g, instances, next.*, 0, 0, .{ + .w = @as(f32, @floatFromInt(layer.viewport.w)) * bw, + .h = 1, + .x_off = left, + .y_off = top + height - 1, + }, win_w, win_h, .body, (&border)[0..1], 0, null, false, page); + clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); + next.* += 1; + } + } +} + +/// acme's Scrollwid column at a pane's or column's left edge, in window +/// pixels: where its button sits over its scrollbar, one width for both +/// (`rail_px` at acme's 17px font, scaled with the tagline, and always +/// short of the cell so the text keeps a gap), right of the column's rule. +fn scrollColumn(g: *const Gui, chrome: *const pardes.Chrome, col: u16, layout: CellLayout) [2]f32 { + const rule: f32 = if (col == 0) 0 else rulePx(chrome); + const x0 = @round(@as(f32, @floatFromInt(col)) * layout.w + rule); + const scaled: f32 = @round(@as(f32, @floatFromInt(@max(1, chrome.rail_px))) * @as(f32, @floatFromInt(g.tagline_height)) / 17); + // The rail and the grip are GUTTER cells wide; the text starts after. + const w = std.math.clamp(scaled, dp(4), @max(dp(4), @floor(layout.w * @as(f32, @floatFromInt(config.GUTTER))) - rule - dp(3))); + return .{ x0, x0 + w }; +} + +/// acme's button for the grip whose first cell is (col, row), in window +/// pixels: the scroll column wide, its tag row tall, from the rule above to +/// the rule below, so button and scrollbar read as one strip. +fn gripButton(g: *const Gui, chrome: *const pardes.Chrome, col: u16, row: u16, layout: CellLayout) [4]f32 { + const x = scrollColumn(g, chrome, col, layout); + const y0 = @round(@as(f32, @floatFromInt(row)) * layout.h); + return .{ x[0], y0, x[1], @round(@as(f32, @floatFromInt(row + 1)) * layout.h) }; +} + +/// A pane's button fill, from its region's state, not the grid's cells +/// (which are drawn for cell shells): dirty, focused, or the tag's ground. +fn gripFill(chrome: *const pardes.Chrome, focus: bool, dirty: bool) [3]u8 { + if (dirty) return chrome.grip_dirty; + return if (focus) chrome.grip_focus_ring else chrome.tag_bg; +} + +fn inkOn(bg: [3]u8) [3]u8 { + const lum = (@as(u16, bg[0]) * 3 + @as(u16, bg[1]) * 6 + @as(u16, bg[2])) / 10; + return if (lum > 140) .{ 0x00, 0x00, 0x00 } else .{ 0xff, 0xff, 0xff }; +} + +/// Cuts an instance's quad to a pixel rectangle (left, top, right, bottom), +/// its atlas window in proportion, so the glyph neither moves nor stretches +/// (a band is a stretched quad); nothing left, an empty quad. +fn clipInstance(instance: *CellInstance, r: [4]f32, win_w: f32, win_h: f32) void { + // In clip space, where y grows up: a quad's y0 is its top. + const left = r[0] / win_w * 2 - 1; + const right = r[2] / win_w * 2 - 1; + const top = 1 - r[1] / win_h * 2; + const bottom = 1 - r[3] / win_h * 2; + if (instance.x1 <= left or instance.x0 >= right or instance.y0 <= bottom or instance.y1 >= top) { + instance.x1 = instance.x0; + instance.y1 = instance.y0; + return; + } + if (instance.x0 < left) { + const fraction = (instance.x1 - left) / (instance.x1 - instance.x0); + instance.u0 = instance.u1 + (instance.u0 - instance.u1) * fraction; + instance.x0 = left; + } + if (instance.x1 > right) { + const fraction = (right - instance.x0) / (instance.x1 - instance.x0); + instance.u1 = instance.u0 + (instance.u1 - instance.u0) * fraction; + instance.x1 = right; + } + if (instance.y0 > top) { + const fraction = (top - instance.y1) / (instance.y0 - instance.y1); + instance.v0 = instance.v1 + (instance.v0 - instance.v1) * fraction; + instance.y0 = top; + } + if (instance.y1 < bottom) { + const fraction = (instance.y0 - bottom) / (instance.y0 - instance.y1); + instance.v1 = instance.v0 + (instance.v1 - instance.v0) * fraction; + instance.y1 = bottom; + } +} + +fn emitSurfaceCell( + g: *Gui, + chrome: *const pardes.Chrome, + instances: [*]CellInstance, + next: *u32, + col: u16, + row: u16, + body_layout: CellLayout, + win_w: f32, + win_h: f32, + line: []const pardes.Cell, + line_cover: []const Cover, + at: usize, + cursor: ?usize, + is_cursor: bool, + page: [3]u8, +) void { + const role = cellFontRole(&line[at]); + if (role == .tagline) { + const here = line_cover[at]; + // The workspace row's underlay is its own ground (a theme's status + // bar), else the focused or plain tag's. + const band_base: pardes.Cell = .{ + .style = .{ .bg = .{ .rgb = if (row < chrome.tagline_rows) chrome.tagline_bg else if (here.focus) chrome.tag_focus_bg else chrome.tag_bg }, .font_role = .tagline }, + .default = false, + }; + // The smaller font changes the ink, not the chrome's coverage. Painting + // this underlay at tagline height leaves page-colored gutters between + // adjacent workspace, column and pane tags at TaglineSize < 100. + emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .body, (&band_base)[0..1], 0, null, false, page); + next.* += 1; + // Tag glyphs keep their font size inside a full physical-width grip. + // A pane's grip cells are the cell shells' form (a dirty `*`): the + // button draws its own glyph over a blank of them. + var blank = line[at]; + blank.text[0] = ' '; + blank.len = 1; + if (here.pane_grip) + emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .tagline, (&blank)[0..1], 0, null, false, page) + else + emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .tagline, line, at, cursor, is_cursor, page); + // A grip's glyph is the cell at its left edge, and a blank one is + // no glyph: its marks are decor. + const glyph = &line[at - @min(here.grip_offset, at)]; + const grip = here.grip and here.grip_top and !glyph.default and glyph.printableAscii() != ' ' and !glyph.style.invisible; + const offset: u16 = if (grip) @min(here.grip_offset, at) else 0; + // An anchor starts at its column's rule: its left edge is inset by + // its top margin so the band frames it on the left as above and + // below, and its mark moves right by half that to stay centered. + const inset: u32 = if (line_cover[at - offset].anchor) taglineBandOffset(row, win_h, g.cell_h, g.tagline_height) else 0; + // A grip is acme's button: its fill is this cell's ground, cut to + // the button (and a dirty one's inset a pixel inside its ring, so + // the ring reads round it), its glyph centered in it. + const button = if (here.grip and here.grip_top) gripButton(g, chrome, col - @min(here.grip_offset, @as(u16, @intCast(at))), row, body_layout) else null; + if (grip) { + // A grip is one glyph centered across the gutter, not text: it is + // looked up by its codepoint's glyph, never shaped. + const drawn = g.atlas.glyphForCodepoint(cellCodepoint(glyph)); + const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = @bitCast(GlyphDecoration.fromCell(glyph)), .centered = true }); + const slot = cached orelse g.atlas.space_slot; + const b = button.?; + const center = (b[0] + b[2]) / 2 - @as(f32, @floatFromInt(col - offset)) * body_layout.w; + const shift: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, offset) * g.cell_w)) + @as(f32, @floatFromInt(config.GUTTER * g.cell_w)) / 2 - center else 0; + const resolved = resolveCell(g, glyph[0..1], 0, null, .tagline, false, page); + const ink = if (here.pane_grip) inkOn(gripFill(chrome, here.focus, here.dirty)) else resolved.fg; + instances[next.*].fr = @as(f32, @floatFromInt(ink[0])) / 255; + instances[next.*].fg = @as(f32, @floatFromInt(ink[1])) / 255; + instances[next.*].fb = @as(f32, @floatFromInt(ink[2])) / 255; + instances[next.*].u0 = (@as(f32, @floatFromInt(slot.u)) + shift) / atlas_w; + instances[next.*].v0 = @as(f32, @floatFromInt(slot.v)) / atlas_h; + instances[next.*].v1 = @as(f32, @floatFromInt(slot.v + g.tagline_height)) / atlas_h; + } + instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; + if (button) |b| { + // acme's button fills its tag row from the rule above to the rule + // below: the underlay is its fill, cut to its columns; a pane's + // from its region's state, not the grid's cell form (whose dirty + // `*` is the cell shells'), a column's its cell's own ground. + const base = &instances[next.* - 1]; + const own: [3]f32 = .{ instances[next.*].br, instances[next.*].bg, instances[next.*].bb }; + if (here.pane_grip) { + const fill = gripFill(chrome, here.focus, here.dirty); + base.br = @as(f32, @floatFromInt(fill[0])) / 255; + base.bg = @as(f32, @floatFromInt(fill[1])) / 255; + base.bb = @as(f32, @floatFromInt(fill[2])) / 255; + } else { + base.br = own[0]; + base.bg = own[1]; + base.bb = own[2]; + } + clipInstance(base, .{ b[0], -1e9, b[2], 1e9 }, win_w, win_h); + // Over it, only its own glyph; the band round it and the ring + // are decor (gripDecor). + if (here.pane_grip and !grip) { + instances[next.*].u0 = @as(f32, @floatFromInt(g.atlas.space_slot.u)) / atlas_w; + instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; + instances[next.*].v0 = @as(f32, @floatFromInt(g.atlas.space_slot.v)) / atlas_h; + instances[next.*].v1 = @as(f32, @floatFromInt(g.atlas.space_slot.v + g.tagline_height)) / atlas_h; + } + // Its ground is the fill again. + instances[next.*].br = base.br; + instances[next.*].bg = base.bg; + instances[next.*].bb = base.bb; + clipInstance(&instances[next.*], b, win_w, win_h); + } else if (inset > 0) { + instances[next.*].x0 += @as(f32, @floatFromInt(inset)) / win_w * 2; + instances[next.*].u0 += @as(f32, @floatFromInt(inset)) / atlas_w; + } + if (here.dim and !is_cursor) dim.fade(&instances[next.*]); + next.* += 1; + return; + } + emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, role, line, at, cursor, is_cursor, page); + if (line_cover[at].dim and !is_cursor) dim.fade(&instances[next.*]); + next.* += 1; +} + +fn emitInstance( + g: *Gui, + instances: [*]CellInstance, + idx: u32, + col: u16, + row: u16, + layout: CellLayout, + win_w: f32, + win_h: f32, + role: pardes.FontRole, + line: []const pardes.Cell, + at: usize, + cursor: ?usize, + is_cursor: bool, + page: [3]u8, +) void { + const resolved = resolveCell(g, line, at, cursor, role, is_cursor, page); + + const px0 = layout.x_off + @as(f32, @floatFromInt(col)) * layout.w; + const visual_h: f32 = if (resolved.role == .tagline) + @floatFromInt(g.tagline_height) + else + layout.h; + const band_offset: f32 = if (resolved.role == .tagline) + @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height)) + else + 0; + const py0 = layout.y_off + @as(f32, @floatFromInt(row)) * layout.h + band_offset; + const x0 = (px0 / win_w) * 2.0 - 1.0; + const x1 = ((px0 + layout.w) / win_w) * 2.0 - 1.0; + const y0 = 1.0 - (py0 / win_h) * 2.0; + const y1 = 1.0 - ((py0 + visual_h) / win_h) * 2.0; + const aw_f: f32 = @floatFromInt(atlas_w); + const ah_f: f32 = @floatFromInt(atlas_h); + const uv_w: u32 = if (resolved.role == .tagline) g.tagline_width else g.cell_w; + const uv_h: u32 = if (resolved.role == .tagline) g.tagline_height else g.cell_h; + + instances[idx] = .{ + .x0 = x0, + .y0 = y0, + .x1 = x1, + .y1 = y1, + .u0 = @as(f32, @floatFromInt(resolved.slot.u)) / aw_f, + .v0 = @as(f32, @floatFromInt(resolved.slot.v)) / ah_f, + .u1 = @as(f32, @floatFromInt(resolved.slot.u + uv_w)) / aw_f, + .v1 = @as(f32, @floatFromInt(resolved.slot.v + uv_h)) / ah_f, + .fr = @as(f32, @floatFromInt(resolved.fg[0])) / 255.0, + .fg = @as(f32, @floatFromInt(resolved.fg[1])) / 255.0, + .fb = @as(f32, @floatFromInt(resolved.fg[2])) / 255.0, + .br = @as(f32, @floatFromInt(resolved.bg[0])) / 255.0, + .bg = @as(f32, @floatFromInt(resolved.bg[1])) / 255.0, + .bb = @as(f32, @floatFromInt(resolved.bg[2])) / 255.0, + }; + // A block cursor is foreground UI ink, even though its color is carried + // in the reversed cell background. Keep it visible at WindowOpacity 0. + if (is_cursor) instances[idx].effect |= opaque_bg_bit; +} + +fn cellCodepoint(cell: *const pardes.Cell) u32 { + const grapheme = cell.grapheme(); + return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); +} + +fn firstCp(s: []const u8) u32 { + if (s.len == 0) return ' '; + const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return ' '; + if (n > s.len) return ' '; + return std.unicode.utf8Decode(s[0..n]) catch ' '; +} + +fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { + var cw: c_int = 10; + var chh: c_int = 20; + var asc: c_int = 16; + g.atlas.cellMetrics(g.px, &cw, &chh, &asc); + g.cell_w = @intCast(@max(cw, 1)); + g.cell_h = @intCast(@max(chh, 1)); + g.ascent = @intCast(@max(asc, 1)); + const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, g.tagline_percent); + g.tagline_px = tagline.px; + g.tagline_width = tagline.width; + g.tagline_baseline = tagline.baseline; + g.tagline_height = tagline.height; + + resetGlyphAtlas(g); + + if (core) |p| { + const geom = windowCells(g); + _ = updateCoreResize(p, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); + } + + resetScroll(g); +} + +// The first cell of the cleared atlas stays blank: the space slot. +fn resetGlyphAtlas(g: *Gui) void { + g.atlas.reset(g.cell_w); + g.words.clear(); +} + +fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { + if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return; + const geom = windowCells(g); + _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); +} + +/// The tagline's face at `percent` of the body's: whether it changed. +fn fitTaglineFont(g: *Gui, percent: u8) bool { + if (percent == g.tagline_percent) return false; + g.tagline_percent = percent; + const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, percent); + g.tagline_px = tagline.px; + g.tagline_width = tagline.width; + g.tagline_baseline = tagline.baseline; + g.tagline_height = tagline.height; + resetGlyphAtlas(g); + return true; +} + +/// What text draws, so a frame does not work it out again. `cells` is the +/// atlas slot of a codepoint no ligature can touch (`shape_slot` for one that +/// is shaped with its word); `map` is the atlas slot of every cell of a word +/// holding one, found by the word's text. Bounded: past `max_cells` word cells +/// it starts over, and the next frames look up what they show again (the +/// glyphs stay in the atlas). +const Words = struct { + cells: std.AutoHashMapUnmanaged(CellKey, Slot) = .empty, + map: std.AutoHashMapUnmanaged(u64, Word) = .empty, + /// Every word's codepoints and slots, end to end; a Word indexes both. + text: std.ArrayListUnmanaged(u32) = .empty, + slots: std.ArrayListUnmanaged(Slot) = .empty, + shaped: std.ArrayListUnmanaged(c.UIShapedCell) = .empty, + /// The word the last cell was in, so the rest of it costs a compare. It + /// is positional, so every frame forgets it: the cells change under it. + memo: Memo = .{}, + + const max_cells = 1 << 17; + const CellKey = packed struct(u64) { cp: u21, role: pardes.FontRole, decoration: GlyphDecoration, _: u30 = 0 }; + const shape_slot: Slot = .{ .u = std.math.maxInt(u32), .v = std.math.maxInt(u32) }; + const Word = struct { start: u32, len: u32, decoration: GlyphDecoration }; + const Memo = struct { + line: ?[*]const pardes.Cell = null, + len: usize = 0, + start: usize = 0, + end: usize = 0, + cursor: ?usize = null, + slots: usize = 0, + }; + + fn clear(w: *Words) void { + w.cells.clearRetainingCapacity(); + w.map.clearRetainingCapacity(); + w.text.clearRetainingCapacity(); + w.slots.clearRetainingCapacity(); + w.memo = .{}; + } + + fn deinit(w: *Words, gpa: std.mem.Allocator) void { + w.cells.deinit(gpa); + w.map.deinit(gpa); + w.text.deinit(gpa); + w.slots.deinit(gpa); + w.shaped.deinit(gpa); + } +}; + +/// What decides where a word ends, for one cell. A concealed cell is a space. +const WordCell = struct { cp: u32, decoration: GlyphDecoration, role: pardes.FontRole }; + +fn wordCell(cell: *const pardes.Cell) WordCell { + return .{ + .cp = if (!cell.default and cell.style.invisible) ' ' else cellCodepoint(cell), + .decoration = GlyphDecoration.fromCell(cell), + .role = cellFontRole(cell), + }; +} + +/// Whether a word ends between `a`, cell `i`, and `b`, cell `i + 1`: at a +/// space, a decoration or role change, either side of the cursor (Ghostty's +/// rule: the cell being edited shows its own glyph, so a ligature under the +/// cursor comes apart), and inside f|i, f|l and s|t, whose typographic +/// ligatures do not belong on a grid (Ghostty again). Colours never end a +/// word: a ligature spans a syntax colour change or a selection edge, and each +/// cell tints its own slice. +fn wordBreak(a: WordCell, b: WordCell, i: usize, cursor: ?usize) bool { + if (a.cp == ' ' or b.cp == ' ') return true; + // A rule is drawn by hand (ruleArms), never a slice of a shaped word. + if (ruleArms(a.cp) != null or ruleArms(b.cp) != null) return true; + if (cursor) |at| if (at == i or at == i + 1) return true; + if (a.role != b.role or !std.meta.eql(a.decoration, b.decoration)) return true; + return (a.cp == 'f' and (b.cp == 'i' or b.cp == 'l')) or (a.cp == 's' and b.cp == 't'); +} + +/// The atlas slot `line[at]` draws: blank for a plain space (or concealed +/// text), its own glyph when no ligature could replace that glyph (every +/// cell, in a font without ligatures), else its slice +/// of the word around it, shaped once and cached by the word's text. The +/// cells of a word being walked cost a compare. Taglines are not shaped: they are drawn at two pitches +/// (tagline_width in a tag layer, a whole cell in the grid), and a strip would +/// not line up in one of them. +fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole) Slot { + const words = &g.words; + const memo = words.memo; + if (memo.line == line.ptr and memo.len == line.len and memo.cursor == cursor and at >= memo.start and at < memo.end and role == .body) + return words.slots.items[memo.slots + at - memo.start]; + var here = wordCell(&line[at]); + // An underlined or struck-out space is a glyph of its own: it draws its line. + if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot; + if (ruleArms(here.cp) != null) + return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @fromBackingInt(@intCast(@backingInt(role))), .rule = true }) orelse g.atlas.space_slot; + const gpa = g.atlas.glyphs.allocator; + const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; + const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot; + if (!known.found_existing) { + const drawn = g.atlas.glyphForCodepoint(here.cp); + known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph)) + Words.shape_slot + else + cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @fromBackingInt(@intCast(@backingInt(role))), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot; + } + const plain = known.value_ptr.*; + if (!std.meta.eql(plain, Words.shape_slot)) return plain; + + if (words.text.items.len > Words.max_cells) words.clear(); + var start = at; + while (start > 0) { + const before = wordCell(&line[start - 1]); + if (wordBreak(before, here, start - 1, cursor)) break; + start -= 1; + here = before; + } + // The word's text goes on the end of `text`: a new word keeps it there, + // a known one gives it back. + const text_start = words.text.items.len; + var end = start; + while (true) { + words.text.append(gpa, here.cp) catch return g.atlas.space_slot; + end += 1; + if (end == line.len) break; + const next = wordCell(&line[end]); + if (wordBreak(here, next, end - 1, cursor)) break; + here = next; + } + const text = words.text.items[text_start..]; + const decoration = here.decoration; + const hash = std.hash.Wyhash.hash(@as(u5, @bitCast(decoration)), std.mem.sliceAsBytes(text)); + if (words.map.get(hash)) |word| { + if (word.len == text.len and std.meta.eql(word.decoration, decoration) and + std.mem.eql(u32, words.text.items[word.start..][0..word.len], text)) + { + words.text.shrinkRetainingCapacity(text_start); + words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = word.start }; + return words.slots.items[word.start + at - start]; + } + } + + // A new word (a hash collision takes the map entry over). Runs of one + // face are shaped in that face; fallback faces shape like the primary. + const probe_shape = monoNs(); + defer if (frame_probe) |probe| { + probe.zone(.gui_shape, probe_shape); + probe.shaped +|= 1; + }; + const n = text.len; + words.slots.ensureUnusedCapacity(gpa, n) catch { + words.text.shrinkRetainingCapacity(text_start); + return g.atlas.space_slot; + }; + words.shaped.resize(gpa, n) catch { + words.text.shrinkRetainingCapacity(text_start); + return g.atlas.space_slot; + }; + const shaped = words.shaped.items; + var run_start: usize = 0; + var face = g.atlas.glyphForCodepoint(text[0]).face; + while (run_start < n) { + var run_end = run_start + 1; + var next_face = face; + while (run_end < n) : (run_end += 1) { + next_face = g.atlas.glyphForCodepoint(text[run_end]).face; + if (next_face != face) break; + } + g.atlas.shape(face, g.px, g.cell_w, text[run_start..run_end], shaped[run_start..]); + for (shaped[run_start..run_end]) |cell| { + const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = @bitCast(decoration), .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; + const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.atlas.space_slot; + words.slots.appendAssumeCapacity(slot); + } + run_start = run_end; + face = next_face; + } + words.map.put(gpa, hash, .{ .start = @intCast(text_start), .len = @intCast(n), .decoration = decoration }) catch {}; + words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = text_start }; + return words.slots.items[text_start + at - start]; +} + +/// A Gui for the tests that build cells, decor or a scroll without a +/// window: these metrics, every other field its default. What needs SDL, a +/// font or the atlas is undefined (textTestGui adds a font and an atlas). +fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui { + return .{ + .window = undefined, + .present = undefined, + .cells = undefined, + .overlay_vertices = &.{}, + .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined }, + .px = 0, + .tagline_px = 0, + .tagline_percent = 0, + .tagline_width = tagline_width, + .tagline_height = tagline_height, + .cell_w = cell_w, + .cell_h = cell_h, + .ascent = 0, + .tagline_baseline = 0, + }; +} + +/// The atlas slot of `key` (Atlas.cachedGlyph), rasterized on first use at +/// the window's sizes, a grip glyph GUTTER cells wide, its rules and +/// decorations a logical pixel thick (dp): a raster is the frame probe's. +/// Null when the atlas is full. +fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { + if (g.atlas.glyphs.get(key)) |s| return s; + const probe_raster = monoNs(); + const body: Atlas.Size = .{ .px = g.px, .cell_w = g.cell_w, .height = g.cell_h, .baseline = g.ascent }; + const tagline: Atlas.Size = .{ .px = g.tagline_px, .cell_w = g.tagline_width, .height = g.tagline_height, .baseline = g.tagline_baseline }; + const s = g.atlas.cachedGlyph(key, body, tagline, config.GUTTER, @intFromFloat(dp(1))) orelse return null; + if (frame_probe) |probe| { + probe.zone(.gui_raster, probe_raster); + probe.rastered +|= 1; + } + return s; +} + +fn backgroundOpacity(percent: u8) f32 { + std.debug.assert(percent <= 100); + return @as(f32, @floatFromInt(percent)) / 100; +} + +/// PARDES_TEST_LATENCY trace for an external driver, CLOCK_MONOTONIC ns: +/// `R t` when stdin input is read, `F start fence submit` per captured frame +/// (present entry, the GPU fence of that frame, and its submission: submit - +/// start is the frame's CPU cost). Nothing is written without it. +var latency_fd: c_int = -1; +var frame_started_ns: u64 = 0; + +fn monoNs() u64 { + var ts: libc.timespec = undefined; + if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + +fn latencyNote(comptime fmt: []const u8, args: anytype) void { + if (latency_fd < 0) return; + var buf: [64]u8 = undefined; + const line = std.fmt.bufPrint(&buf, fmt, args) catch return; + _ = libc.write(latency_fd, line.ptr, line.len); +} + +/// Writes the frame to latest.ppm in the capture directory, and in a +/// series to frame-.ppm too. +fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { + const frame = try g.present.readFrame(cmd, target, sw, sh); + defer g.present.releaseFrame(frame); + latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, frame.fence_ns, frame.submit_ns }); + + try writeCapturePpm(g, gpa, frame.pixels, sw, sh, "latest", false); + var name: [24]u8 = undefined; + // unreachable below: "frame-" and a u32 fit 24 + if (g.capture_series) try writeCapturePpm(g, gpa, frame.pixels, sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable, true); + g.captured +%= 1; +} + +/// A test window's state for a harness (test/process/window.zig), in the +/// capture directory's `status`: " ". +/// Idle is 1 once the frame last captured is the one that stays: nothing +/// owes a frame, nothing moves, nothing waits on a clock. A harness that +/// sees a step past the one it acted on, idle, has its frame, however slow +/// the machine is. +var test_status_step: u64 = 0; +fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) void { + test_status_step +%= 1; + if (g.capture_dir.len == 0) return; + const idle = presented and !core.needs_frame and !frontendMoving(g) and core.nextWake() == null and + !g.glide.moving() and g.scroll_lag == 0 and g.scroll_delta == 0 and g.scroll_notch == 0; + var line_buf: [64]u8 = undefined; + // What keeps it busy, after: owes a frame, moves, waits, not shown. + const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(frontendMoving(g)), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch unreachable; // seven numbers fit 64 + var tmp_buf: [4096]u8 = undefined; + var final_buf: [4096]u8 = undefined; + const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/status.tmp", .{g.capture_dir}, 0) catch return; + const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/status", .{g.capture_dir}, 0) catch return; + const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return; + _ = libc.write(fd, line.ptr, line.len); + _ = libc.close(fd); + _ = libc.rename(tmp_path, final_path); +} + +/// `.ppm`, RGB; with `alpha`, `.pam` (P7 RGB_ALPHA) instead: a +/// series keeps the alpha a blend writes, which the window's transparency +/// shows and an RGB capture cannot. +fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8, alpha: bool) !void { + // A latency trace times frames, and an 8 MB file write per frame would + // stall the loop it is timing. + if (g.capture_dir.len == 0 or latency_fd >= 0) return; + const bgr = try g.present.bgr(); + + var tmp_buf: [4096]u8 = undefined; + var final_buf: [4096]u8 = undefined; + const ext = if (alpha) "pam" else "ppm"; + const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.{s}.tmp", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong; + const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.{s}", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong; + + const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return error.CaptureWriteFailed; + defer _ = libc.close(fd); + + var header: [96]u8 = undefined; + const hdr = if (alpha) + std.fmt.bufPrint(&header, "P7\nWIDTH {d}\nHEIGHT {d}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", .{ width, height }) catch unreachable // two u32s fit 96 + else + std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 96 + _ = host_io.writeFd(fd, hdr); + + const depth: usize = if (alpha) 4 else 3; + const row_rgb = try gpa.alloc(u8, @as(usize, width) * depth); + defer gpa.free(row_rgb); + for (0..height) |row| { + const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4]; + for (0..width) |x| { + const si = x * 4; + const di = x * depth; + row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0]; + row_rgb[di + 1] = src[si + 1]; + row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2]; + if (alpha) row_rgb[di + 3] = src[si + 3]; + } + _ = host_io.writeFd(fd, row_rgb); + } + if (libc.rename(tmp_path, final_path) != 0) return error.CaptureWriteFailed; +} + +/// One flat, hard-edged rectangle of decor, in window pixels: clipped to the +/// window and dropped when empty, as the triangle overlay drew it. +fn addDecor(g: *Gui, gpa: std.mem.Allocator, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, rgb: [3]u8, alpha: f32, win_w: f32, win_h: f32) !void { + const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, win_w); + const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, win_w); + const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, win_h); + const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, win_h); + if (x1 <= x0 or y1 <= y0) return; + // decor.frag.glsl reads the colour from the ground and the coverage + // from the ink's red. + try g.decor.append(gpa, .{ + .x0 = (x0 / win_w) * 2.0 - 1.0, + .y0 = 1.0 - (y0 / win_h) * 2.0, + .x1 = (x1 / win_w) * 2.0 - 1.0, + .y1 = 1.0 - (y1 / win_h) * 2.0, + .u0 = 0, + .v0 = 0, + .u1 = 0, + .v1 = 0, + .fr = alpha, + .fg = 0, + .fb = 0, + .br = @as(f32, @floatFromInt(rgb[0])) / 255.0, + .bg = @as(f32, @floatFromInt(rgb[1])) / 255.0, + .bb = @as(f32, @floatFromInt(rgb[2])) / 255.0, + }); +} + +/// A body region in window pixels. +fn bodyPixels(region: pardes.Region, layout: CellLayout) [4]f32 { + return .{ + @as(f32, @floatFromInt(region.rect.x)) * layout.w, + @as(f32, @floatFromInt(region.rect.y)) * layout.h, + @as(f32, @floatFromInt(region.rect.x + region.rect.w)) * layout.w, + @as(f32, @floatFromInt(region.rect.y + region.rect.h)) * layout.h, + }; +} + +/// The frame's decor, group by group (docs/render-pipeline.md), all of it +/// read from the regions and the palette: the page's rules and the panes' +/// rails, rules and grip marks with the page, notice rules with the +/// notices, bar cursors with the ink. +fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, groups: *Groups, layout: CellLayout, win_w: f32, win_h: f32, cursors_shown: bool) !void { + g.decor.clearRetainingCapacity(); + const chrome = &surface.chrome; + const regions = surface.regionList(); + for (groups.items[0..groups.len], 0..) |*group, index| { + group.decor_start = @intCast(g.decor.items.len); + defer group.decor_count = @as(u32, @intCast(g.decor.items.len)) - group.decor_start; + if (index == 0) { + // The grips' buttons before any rule: the rules over their rows + // cut them, and the band round them never covers a rule. + try gripDecor(g, gpa, regions, surface.cells, chrome, layout, surface.cols, surface.rows, win_w, win_h); + const top = for (regions) |region| { + if (region.kind == .workspace_tag) break region.rect.h; + } else 0; + // The workspace tag is ruled off from the tags right under it. + const tag_under = for (regions) |region| switch (region.kind) { + .grip, .tag, .column_grip, .column_tag => if (region.rect.y == top) break true, + else => {}, + } else false; + // As wide as the other rules, where the tagline leaves the room. + const height: u32 = @intFromFloat(@max(1, @min(rulePx(chrome), @as(f32, @floatFromInt((g.cell_h -| g.tagline_height) * 2))))); + if (top != 0 and top < surface.rows and tag_under and height != 0) { + const y0: f32 = @floatFromInt(top * g.cell_h - height / 2); + try addDecor(g, gpa, 0, y0, win_w, y0 + @as(f32, @floatFromInt(height)), chrome.topbar_rule, 1, win_w, win_h); + } + // The column bar is ruled off from the panes under it. + for (regions) |bar| { + if (bar.kind != .column_grip) continue; + const y = @as(f32, @floatFromInt(bar.rect.y + bar.rect.h)) * layout.h; + try addDecor(g, gpa, 0, y - rulePx(chrome), win_w, y, chrome.border, 1, win_w, win_h); + break; + } + // A tag on the last row runs on through the pixels under the grid. + const grid_bottom = @as(f32, @floatFromInt(surface.rows)) * layout.h; + const tag_last = for (regions) |region| switch (region.kind) { + .grip, .tag, .column_grip, .column_tag, .workspace_tag => if (region.rect.h != 0 and region.rect.y + region.rect.h == surface.rows) break true, + else => {}, + } else false; + if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); + try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h); + // A single spine runs down each column, through every tag and body. + for (regions) |column| { + if (column.kind != .column) continue; + const x = @as(f32, @floatFromInt(column.rect.x)) * layout.w; + const y0 = @as(f32, @floatFromInt(column.rect.y)) * layout.h; + const grid_y1 = @as(f32, @floatFromInt(surface.rows)) * layout.h; + const y1 = if (win_h - grid_y1 < layout.h) @max(grid_y1, win_h) else grid_y1; + // None at the window's edge: nothing to rule apart there. + if (column.rect.x == 0) continue; + if (y1 > y0) try addDecor(g, gpa, x, y0, x + rulePx(chrome), y1, chrome.border, 1, win_w, win_h); + } + } + // A notice chip is tagline hung over the body's top rows, so it is + // ruled off from the text beneath it the way a tag is: the same + // colour and thickness along its bottom, running to the window's + // edge when it does. + if (index == groups.notices) for (surface.tagLayers()) |*layer| { + if (layer.rows == 0 or layer.kind != .notice) continue; + const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; + const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; + const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; + const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h; + const rule_y = top + layout.h; + try addDecor(g, gpa, x0, rule_y - dp(1), rule_x1, rule_y, chrome.border, 1, win_w, win_h); + }; + if (index == groups.ink and cursors_shown) try cursorDecor(g, gpa, surface, layout, win_w, win_h); + } +} + +/// Each pane's rule between its tag and body, and its scroll rail: a page +/// coloured gutter with a thin track and its thumb, running down through the +/// pixels past the last whole row. +fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { + const page = chrome.page orelse bg_default; + for (regions) |rail| { + if (rail.kind != .rail or rail.rect.h == 0) continue; + const tag = for (regions) |region| { + if (region.kind == .tag and region.owner == rail.owner) break region; + } else continue; + if (@as(u32, tag.rect.x) + tag.rect.w > cols or @as(u32, tag.rect.y) + tag.rect.h > rows or + @as(u32, rail.rect.y) + rail.rect.h > rows) continue; + const x0 = @as(f32, @floatFromInt(rail.rect.x)) * layout.w; + const x1 = @as(f32, @floatFromInt(tag.rect.x + tag.rect.w)) * layout.w; + // Like the band above it, the rule of a pane at the right edge runs + // on through the pixels past the last whole cell. Under a tag on + // top, over one below its body. + const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; + const tag_bottom = tag.rect.y > rail.rect.y; + const rule_y = @as(f32, @floatFromInt(if (tag_bottom) tag.rect.y else tag.rect.y + tag.rect.h)) * layout.h; + try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule orelse mixRgb(chrome.tag_bg, page), 1, win_w, win_h); + // Stacked panes are ruled apart as columns are, where one pane's + // body meets the next one's tag (acme's Border). + { + const pane_top = @min(tag.rect.y, rail.rect.y); + const stacked = for (regions) |other| { + if ((other.kind == .body or other.kind == .tag) and other.owner != rail.owner and other.rect.y + other.rect.h == pane_top and + other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; + } else false; + // Inside the tag band's slack, never over its glyphs: the top + // slack of a tag on top, the bottom slack of the one above when + // tags are at the bottom; a pixel at least. + const y = @as(f32, @floatFromInt(pane_top)) * layout.h; + const spare = g.cell_h -| g.tagline_height; + if (stacked and !tag_bottom) { + const room = taglineBandOffset(pane_top, win_h, g.cell_h, g.tagline_height); + try addDecor(g, gpa, x0, y, rule_x1, y + @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), chrome.border, 1, win_w, win_h); + } else if (stacked and pane_top > 0) { + const room = spare - taglineBandOffset(pane_top - 1, win_h, g.cell_h, g.tagline_height); + try addDecor(g, gpa, x0, y - @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), rule_x1, y, chrome.border, 1, win_w, win_h); + } + } + + const y0 = @as(f32, @floatFromInt(rail.rect.y)) * layout.h; + const body_end = rail.rect.y + rail.rect.h; + const body_y1 = @as(f32, @floatFromInt(body_end)) * layout.h; + const y1 = if (body_end == rows and win_h - body_y1 < layout.h) @max(body_y1, win_h) else body_y1; + // A theme's own track fills its width, the thumb one pixel short + // of it so the track edges it (acme's scrollbar); else a thin rail. + // acme's scrollbar: the track fills the scroll column, under the + // grip's button; the thumb is a pixel short of its right edge, so + // the track edges it. + const column = scrollColumn(g, chrome, rail.rect.x, layout); + try addDecor(g, gpa, x0, y0, x0 + layout.w, y1, page, 1, win_w, win_h); + try addDecor(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, 1, win_w, win_h); + if (rail.thumb_h != 0 and rail.thumb_span > 0) { + // In pixels, not rows, and with the picture while it glides + // or lags behind the core's rows (both in rows of the body). + const lag: f32 = if (g.glide.follow.offset != 0 and g.glide.pane == rail.owner) + g.glide.lagLines() + else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; + const track_px = body_y1 - y0; + const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); + const at = rail.thumb_at + lag * rail.thumb_span / @as(f32, @floatFromInt(rail.rect.h)); + const thumb_y0 = y0 + std.math.clamp(at * track_px, 0, track_px - size); + const thumb_y1 = if (thumb_y0 + size >= body_y1 - 0.5) y1 else thumb_y0 + size; + try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); + } else if (rail.thumb_h != 0) { + const thumb_y0 = @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y)) * layout.h; + const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; + try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); + } + // A query's places' ticks over the track and thumb, where its matches + // are in the file (Places.addTicks); the current one last, on top. + const track_px = body_y1 - y0; + for (0..2) |pass| for (ticks) |tick| { + if (tick.owner != rail.owner or tick.current != (pass == 1)) continue; + const at = @as(f32, @floatFromInt(tick.at)) / @as(f32, @floatFromInt(pardes.panes.Places.tick_scale)); + const h = if (tick.current) dp(3) else dp(2); + const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h); + try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, win_w, win_h); + }; + } +} + +/// Halfway between two colours. +const mixRgb = pardes.colors.mix; + +/// A rule's width: the theme's own, or one pixel. +fn rulePx(chrome: *const pardes.Chrome) f32 { + return dp(@floatFromInt(@max(1, chrome.rule_px))); +} + +/// The display's density (SDL's window display scale: 2 on a 2x screen), +/// by which every size given in logical pixels is drawn, as acme scales its +/// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is +/// measured in them are already the display's pixels and are not scaled. +/// One per process, as its window is. +var display_scale: f32 = 1; + +/// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x); +/// a test window is 1x unless forced, whatever display it lands on, so its +/// captures are the same on any machine. +fn updateDisplayScale(window: *c.SDL_Window) void { + if (std.c.getenv("PARDES_TEST_SCALE")) |forced| { + display_scale = std.fmt.parseFloat(f32, std.mem.span(forced)) catch 1; + } else if (std.c.getenv("PARDES_TEST") != null) { + display_scale = 1; + } else { + const scale = c.SDL_GetWindowDisplayScale(window); + display_scale = if (scale > 0 and std.math.isFinite(scale)) scale else 1; + } + display_scale = std.math.clamp(display_scale, 1, 4); +} + +/// InactiveDim: the unfocused panes' text faded toward its ground by the +/// setting's percent, never below the pair's own contrast or 4.5, whichever +/// is lower. The window's alone, from the regions' focus: renderFrame +/// begins it each frame. ponytail: one window per process, as display_scale. +var dim: Dim = .{}; + +const Dim = struct { + amount: f32 = 0, + /// The pane with the keyboard, from its regions. + focused: u16 = pardes.Region.none, + /// The few ink and paper pairs a frame has, each faded once. + keys: [32]?[6]u8 = @splat(null), + values: [32][3]u8 = undefined, + + fn begin(d: *Dim, percent: u8, regions: []const pardes.Region) void { + d.* = .{ .amount = @as(f32, @floatFromInt(@min(percent, 100))) / 100 }; + for (regions) |region| if (region.active and (region.kind == .grip or region.kind == .tag or region.kind == .body)) { + d.focused = region.owner; + break; + }; + if (d.focused == pardes.Region.none) d.amount = 0; + } + + /// Whether pane `owner`'s text fades this frame. + fn of(d: *const Dim, owner: u16) bool { + return d.amount > 0 and owner != d.focused; + } + + /// A cell instance's ink faded toward its ground. + fn fade(d: *Dim, instance: *CellInstance) void { + const ink = d.faded(byteRgb(.{ instance.fr, instance.fg, instance.fb }), byteRgb(.{ instance.br, instance.bg, instance.bb })); + instance.fr = @as(f32, @floatFromInt(ink[0])) / 255.0; + instance.fg = @as(f32, @floatFromInt(ink[1])) / 255.0; + instance.fb = @as(f32, @floatFromInt(ink[2])) / 255.0; + } + + fn faded(d: *Dim, ink: [3]u8, paper: [3]u8) [3]u8 { + const key = ink ++ paper; + const slot = (@as(usize, ink[0]) *% 31 +% @as(usize, ink[1]) *% 7 +% ink[2] +% @as(usize, paper[0]) *% 13 +% @as(usize, paper[1]) *% 3 +% paper[2]) % d.keys.len; + if (d.keys[slot]) |held| if (std.mem.eql(u8, &held, &key)) return d.values[slot]; + // Contrast falls as the ink nears its paper: the most of `amount` + // that keeps the pair at its own contrast or 4.5, whichever is lower. + const floor = @min(pardes.colors.contrast(ink, paper), 4.5); + var t = d.amount; + if (pardes.colors.contrast(blendLinear(ink, paper, t), paper) < floor) { + var lo: f32 = 0; + var hi: f32 = t; + for (0..8) |_| { + const mid = (lo + hi) / 2; + if (pardes.colors.contrast(blendLinear(ink, paper, mid), paper) >= floor) lo = mid else hi = mid; + } + t = lo; + } + d.keys[slot] = key; + d.values[slot] = blendLinear(ink, paper, t); + return d.values[slot]; + } + + fn byteRgb(rgb: [3]f32) [3]u8 { + var out: [3]u8 = undefined; + for (&out, rgb) |*o, v| o.* = @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255)); + return out; + } +}; + +/// `t` of the way from one colour to the other in linear light, so a +/// coloured ink does not muddy on its way to the paper. +fn blendLinear(from: [3]u8, to: [3]u8, t: f32) [3]u8 { + var out: [3]u8 = undefined; + for (&out, from, to) |*o, a, b| { + const l = pardes.colors.to_linear[a] * (1 - t) + pardes.colors.to_linear[b] * t; + o.* = encoded[@intFromFloat(@round(std.math.clamp(l, 0, 1) * (encoded.len - 1)))]; + } + return out; +} + +/// Linear light back to an sRGB channel, in 4096 steps. +const encoded: [4096]u8 = blk: { + @setEvalBranchQuota(1_000_000); + var table: [4096]u8 = undefined; + for (&table, 0..) |*out, i| { + const l = @as(f64, @floatFromInt(i)) / 4095; + const v = if (l <= 0.0031308) l * 12.92 else 1.055 * std.math.pow(f64, l, 1.0 / 2.4) - 0.055; + out.* = @intFromFloat(@round(v * 255)); + } + break :blk table; +}; + +/// A logical pixel size in the display's pixels: rounded, at least one. +fn dp(logical: f32) f32 { + return @max(1, @round(logical * display_scale)); +} + +/// The two short bars on each row of a grip with no mode glyph there, +/// centered in its anchor. +fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, cells: []const pardes.Cell, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { + if (g.tagline_height < 6 or g.tagline_width < 3) return; + for (regions) |grip| { + if (grip.kind != .grip and grip.kind != .column_grip) continue; + if (grip.rect.h == 0 or grip.rect.y >= rows) continue; + const button = gripButton(g, chrome, grip.rect.x, grip.rect.y, layout); + // Round the button, its first row is the tag's band: nothing of the + // cells under it shows there. + const band = if (grip.active) chrome.tag_focus_bg else chrome.tag_bg; + const left = @as(f32, @floatFromInt(grip.rect.x)) * layout.w; + const right = @as(f32, @floatFromInt(grip.rect.x + grip.rect.w)) * layout.w; + try addDecor(g, gpa, left, button[1], button[0], button[3], band, 1, win_w, win_h); + try addDecor(g, gpa, button[2], button[1], right, button[3], band, 1, win_w, win_h); + if (grip.kind != .grip) continue; + // acme's button ring, two pixels (ButtonBorder) inside the button: + // the focused one's in its own fill. An unfocused dirty one keeps a + // pixel of band inside its ring, so the four states differ in shape + // whatever a theme's colours (a focused dirty one is acme's + // modbutton, filled up to its ring). + { + // The rules drawn over the row (paneDecor, after this) cut into + // it: the ring runs inside them, from rule to rule. + const tag = for (regions) |part| { + if (part.kind == .tag and part.owner == grip.owner) break part; + } else grip; + const tag_bottom = for (regions) |part| { + if (part.kind == .rail and part.owner == grip.owner) break part.rect.y < tag.rect.y; + } else false; + const stacked = !tag_bottom and for (regions) |other| { + if ((other.kind == .body or other.kind == .tag) and other.owner != grip.owner and other.rect.y + other.rect.h == grip.rect.y and + other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; + } else false; + const top_rule: f32 = if (tag_bottom) dp(1) else if (stacked) @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(taglineBandOffset(grip.rect.y, win_h, g.cell_h, g.tagline_height))))) else 0; + const bottom_rule: f32 = if (!tag_bottom and grip.rect.h == 1) dp(1) else 0; + const x0 = button[0]; + const x1 = button[2]; + const y0 = button[1] + top_rule; + const y1 = button[3] - bottom_rule; + const ring = if (grip.active) chrome.grip_focus_ring else chrome.grip_border; + // acme's ButtonBorder: two logical pixels. + const b = dp(2); + try addDecor(g, gpa, x0, y0, x1, y0 + b, ring, 1, win_w, win_h); + try addDecor(g, gpa, x0, y1 - b, x1, y1, ring, 1, win_w, win_h); + try addDecor(g, gpa, x0, y0 + b, x0 + b, y1 - b, ring, 1, win_w, win_h); + try addDecor(g, gpa, x1 - b, y0 + b, x1, y1 - b, ring, 1, win_w, win_h); + if (grip.dirty and !grip.active) { + const gap = b + dp(1); + try addDecor(g, gpa, x0 + b, y0 + b, x1 - b, y0 + gap, band, 1, win_w, win_h); + try addDecor(g, gpa, x0 + b, y1 - gap, x1 - b, y1 - b, band, 1, win_w, win_h); + try addDecor(g, gpa, x0 + b, y0 + gap, x0 + gap, y1 - gap, band, 1, win_w, win_h); + try addDecor(g, gpa, x1 - gap, y0 + gap, x1 - b, y1 - gap, band, 1, win_w, win_h); + } + } + // The marks are the first row's alone, where its cell is blank (no + // mode glyph), centered in the button, in its ink from the region's + // state. + const x = grip.rect.x; + const y = grip.rect.y; + if (x >= cols) continue; + const cell = &cells[@as(usize, y) * cols + x]; + if (cell.default or cell.printableAscii() != ' ') continue; + const rgb = inkOn(gripFill(chrome, grip.active, grip.dirty)); + const center_x = @floor((button[0] + button[2]) / 2); + const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; + const half_w = @max(dp(1), @min(dp(3), @floor((button[2] - button[0] - 2 * dp(3)) / 2))); + // The mode's two bars: a logical pixel thick, a pixel either side of + // the middle. + const bar = dp(1); + try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y - bar - dp(1)), @floor(center_x + half_w), @floor(center_y - dp(1)), rgb, 1, win_w, win_h); + try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y + dp(1)), @floor(center_x + half_w), @floor(center_y + dp(1) + bar), rgb, 1, win_w, win_h); + } +} + +const CursorBox = struct { x0: f32, y0: f32, x1: f32, y1: f32, rgb: [3]u8, bar: bool }; +const max_cursors = 1 + pardes.MAX_PANES + pardes.MAX_TAG_LAYERS; + +/// Where the frame draws the focused caret, its top in grid rows: from its +/// own springs (the quad's, while it moves or while a glide moves the text) +/// or its cell; carried by the text's glide when its line rode it. The probe +/// records it and the glide tests hold its invariants. +fn caretRow(g: *const Gui, surface: *const pardes.Surface, now_ns: u64) ?f32 { + const cursor = surface.cursor orelse return null; + const quad = g.caret.placed and (g.caret.moving() or g.glide.follow.offset != 0); + return if (quad) g.caret.sample(now_ns)[0][1] - caretRide(g, surface) else @floatFromInt(cursor.y); +} + +/// What the caret's ease sees in the frame about to be drawn (Caret.see): +/// the focused cursor's box in cells (its own cell's, or the layer's that +/// draws it), and the focused body's pane, first line and place. +fn seeCaret(g: *Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, now_ns: u64) void { + const box: ?Caret.Box = if (surface.cursor) |cursor| box: { + var boxes: [max_cursors]CursorBox = undefined; + const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; + if (all.len == 0) break :box null; + const cx = (@as(f32, @floatFromInt(cursor.x)) + 0.5) * layout.w; + const cy = (@as(f32, @floatFromInt(cursor.y)) + 0.5) * layout.h; + var best = all[0]; + var nearest = std.math.inf(f32); + for (all) |b| { + const dx = (b.x0 + b.x1) / 2 - cx; + const dy = (b.y0 + b.y1) / 2 - cy; + if (dx * dx + dy * dy < nearest) { + nearest = dx * dx + dy * dy; + best = b; + } + } + break :box .{ .x = best.x0 / layout.w, .y = best.y0 / layout.h, .w = (best.x1 - best.x0) / layout.w, .h = (best.y1 - best.y0) / layout.h }; + } else null; + for (surface.regionList()) |region| if (region.kind == .body and region.active) + return g.caret.see(box, region.owner, region.line, region.rect.x, region.rect.y, now_ns); + g.caret.see(box, pardes.Region.none, 0, 0, 0, now_ns); +} + +/// The caret's ease (G3), the window's own: the focused cursor's quad on +/// critically damped springs at its box's corners, in grid cells, on the +/// window's clock, from the cursor the Surface shows. A jump glides, its +/// leading corners first, bowing a little on a long one; a step eases, and +/// a stream of them (typing, a held key) keeps up; a scroll or a pane's move +/// carries it with its text; a focus change glides from where it was drawn. +/// The quad is drawn only while it moves: at rest the cells draw the cursor. +const Caret = struct { + /// Top left, top right, bottom right, bottom left; x then y. + corners: [4][2]Spring = @splat(@splat(.{})), + target: Box = .{}, + from_centre: [2]f32 = .{ 0, 0 }, + placed: bool = false, + /// When the last step (a move of a cell or less) came. + step_ns: u64 = 0, + /// The focused body as the last frame showed it: its pane, its first + /// line and its top left, to tell a scroll and a pane's move from the + /// caret's own. + seen: struct { owner: u8 = pardes.Region.none, line: i32 = 0, x: u16 = 0, y: u16 = 0 } = .{}, + + /// The default flavour's spring, as fast again as the caret follows + /// input (it settles in 90-150 ms). + const omega: f32 = 34 * 2.4; + /// The trailing corners of a jump, a little behind the leading ones. + const follow: f32 = 0.85; + /// A step's spring, stiffer than a jump's. + const step_pace: f32 = 1.5; + /// A jump longer than this, in cells, bows, by this much of its length. + const arc_from: f32 = 8; + const arc: f32 = 0.04; + /// Steps this close are a stream: each lands. + const stream_ns: u64 = 150 * std.time.ns_per_ms; + + const Box = struct { x: f32 = 0, y: f32 = 0, w: f32 = 0, h: f32 = 0 }; + + /// One axis on a critically damped spring, closed form: a new target + /// keeps the value and its speed; settled, it is its target. + const Spring = struct { + omega: f32 = omega, + target: f32 = 0, + from: f32 = 0, + velocity: f32 = 0, + from_ns: u64 = 0, + settled: bool = true, + + fn at(s: *const Spring, now_ns: u64) [2]f32 { + if (s.settled) return .{ s.target, 0 }; + const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| s.from_ns)) / std.time.ns_per_s); + const x0 = s.from - s.target; + const k = s.velocity + s.omega * x0; + const decay = @exp(-s.omega * t); + return .{ s.target + (x0 + k * t) * decay, (s.velocity - s.omega * t * k) * decay }; + } + + fn value(s: *const Spring, now_ns: u64) f32 { + return s.at(now_ns)[0]; + } + + fn retarget(s: *Spring, target: f32, now_ns: u64, w: f32) void { + if (target == s.target) return; + const state = s.at(now_ns); + s.* = .{ .omega = w, .target = target, .from = state[0], .velocity = state[1], .from_ns = now_ns, .settled = false }; + } + + /// Settles within half a percent of a cell, barely moving; true + /// while it still moves. + fn step(s: *Spring, now_ns: u64) bool { + if (s.settled) return false; + const state = s.at(now_ns); + if (@abs(state[0] - s.target) < 5e-3 and @abs(state[1]) < 5e-2) s.settled = true; + return !s.settled; + } + }; + + fn cornersOf(box: Box) [4][2]f32 { + return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; + } + + fn centre(box: Box) [2]f32 { + return .{ box.x + box.w / 2, box.y + box.h / 2 }; + } + + /// Heads for `box`: eased, or landed at once (`land`: a scroll moved + /// the text under it, not the caret). + fn aim(caret: *Caret, box: Box, now_ns: u64, land_it: bool) void { + if (caret.placed and std.meta.eql(box, caret.target) and !(land_it and caret.moving())) return; + const to = cornersOf(box); + const from_c = if (caret.placed) caret.centreAt(now_ns) else centre(box); + const to_c = centre(box); + const dx = to_c[0] - from_c[0]; + const dy = to_c[1] - from_c[1]; + const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; + // A step is measured mark to mark, not from where an ease under way + // has got to (a held key's steps would read as jumps from there). + const last = centre(caret.target); + const one_step = caret.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; + const streaming = one_step and caret.step_ns != 0 and now_ns -| caret.step_ns < stream_ns; + if (one_step) caret.step_ns = now_ns; + const land = !caret.placed or land_it or streaming; + caret.from_centre = from_c; + caret.target = box; + caret.placed = true; + for (&caret.corners, to) |*corner, point| { + // Leading: the corner ahead of the move, on the side it goes. + const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; + const w = if (jump) omega * (if (ahead > 0) 1 else follow) else omega * step_pace; + for (corner, point) |*axis, v| { + if (land) axis.* = .{ .omega = w, .target = v, .from = v } else axis.retarget(v, now_ns, w); + } + } + } + + fn centreAt(caret: *const Caret, now_ns: u64) [2]f32 { + var sum: [2]f32 = .{ 0, 0 }; + for (caret.corners) |corner| for (&sum, corner) |*s, axis| { + s.* += axis.value(now_ns) / 4; + }; + return sum; + } + + /// The text under it moved by (dx, dy) cells: so does the quad. + fn shift(caret: *Caret, dx: f32, dy: f32) void { + for (&caret.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| { + axis.from += d; + axis.target += d; + }; + caret.from_centre = .{ caret.from_centre[0] + dx, caret.from_centre[1] + dy }; + caret.target.x += dx; + caret.target.y += dy; + } + + /// The quad at `now_ns`, bowed on a long jump. + fn sample(caret: *const Caret, now_ns: u64) [4][2]f32 { + var out: [4][2]f32 = undefined; + for (&out, caret.corners) |*point, corner| for (point, corner) |*v, axis| { + v.* = axis.value(now_ns); + }; + const to_c = centre(caret.target); + const dx = to_c[0] - caret.from_centre[0]; + const dy = to_c[1] - caret.from_centre[1]; + const length = @sqrt(dx * dx + dy * dy); + if (length < arc_from) return out; + const now_c = caret.centreAt(now_ns); + const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1])); + const travelled = std.math.clamp(1 - left / length, 0, 1); + const bow = arc * length * 4 * travelled * (1 - travelled); + for (&out) |*point| { + point[0] += -dy / length * bow; + point[1] += dx / length * bow; + } + return out; + } + + /// Steps the springs to `now_ns`; true while the quad still moves. + fn step(caret: *Caret, now_ns: u64) bool { + var any = false; + for (&caret.corners) |*corner| for (corner) |*axis| { + if (axis.step(now_ns)) any = true; + }; + return any; + } + + /// How far, in cells, the furthest corner still is from its mark. + fn remaining(caret: *const Caret, now_ns: u64) f32 { + var most: f32 = 0; + for (caret.corners) |corner| for (corner) |axis| { + most = @max(most, @abs(axis.value(now_ns) - axis.target)); + }; + return most; + } + + fn moving(caret: *const Caret) bool { + for (caret.corners) |corner| for (corner) |axis| { + if (!axis.settled) return true; + }; + return false; + } + + /// The frame about to be drawn shows the focused cursor at `box` (grid + /// cells; null: none) in pane `owner`'s body, whose first line is + /// `line` and top left (x, y): carried with that body when it moved or + /// scrolled, eased to its box otherwise. + fn see(caret: *Caret, box: ?Box, owner: u8, line: i32, x: u16, y: u16, now_ns: u64) void { + const b = box orelse { + // Nowhere to land: a glide under way stops; the next cursor + // lands where it is. + caret.* = .{}; + return; + }; + var land = false; + const was = caret.seen; + if (was.owner == owner and owner != pardes.Region.none) { + // The pane moved in the layout: its caret moves with it. + caret.shift(@as(f32, @floatFromInt(x)) - @as(f32, @floatFromInt(was.x)), @as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(was.y))); + // Scrolled: the text moved, not the caret; it lands on its + // cell (the glide draws it with the text, caretRide). + land = line != was.line; + } + caret.seen = .{ .owner = owner, .line = line, .x = x, .y = y }; + caret.aim(b, now_ns, land); + _ = caret.step(now_ns); + } +}; + +/// The rows a caret whose line rode the wheel's glide is drawn above its +/// cell: the text's own offset, so it moves with its line as a glyph does +/// (its springs landed on the cell, Caret.see). +fn caretRide(g: *const Gui, surface: *const pardes.Surface) f32 { + const glide = &g.glide; + const cu = surface.cursor orelse return 0; + if (glide.follow.offset != 0) { + if (!glide.caret_rides) return 0; + const x0 = glide.rect.x + config.GUTTER; + if (cu.x < x0 or cu.x >= x0 + glide.bw() or cu.y < glide.body_y or cu.y >= glide.body_y + glide.body_h) return 0; + return glide.follow.offset; + } + // A fine wheel's or a touchpad's fraction (scroll_lag) holds the whole + // body off its cells, the caret's row with the rest, at rest too. + if (g.scroll_lag == 0 or g.scroll_pane == null) return 0; + const r = g.scroll_rect; + if (cu.x < r.x + config.GUTTER or cu.x >= r.x + r.w or cu.y < g.scroll_body_y or cu.y >= g.scroll_body_y + g.scroll_body_h) return 0; + return g.scroll_lag; +} + +/// The bar cursors as decor; a block cursor is its cell's own colours. +fn cursorDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32) !void { + var boxes: [max_cursors]CursorBox = undefined; + // The focused one is drawn with its line where a wheel's fraction holds + // the text off its cells (a block is a cell of the shifted rows). + // The focused box is the one nearest its cell (a body layer's is lifted + // off the grid), as seeCaret finds it. + const ride = caretRide(g, surface) * layout.h; + const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; + var focused: usize = all.len; + if (surface.cursor) |cu| { + const cx = (@as(f32, @floatFromInt(cu.x)) + 0.5) * layout.w; + const cy = (@as(f32, @floatFromInt(cu.y)) + 0.5) * layout.h; + var nearest = std.math.inf(f32); + for (all, 0..) |b, i| { + const d = ((b.x0 + b.x1) / 2 - cx) * ((b.x0 + b.x1) / 2 - cx) + ((b.y0 + b.y1) / 2 - cy) * ((b.y0 + b.y1) / 2 - cy); + if (d < nearest) { + nearest = d; + focused = i; + } + } + } + for (all, 0..) |box, i| if (box.bar) { + const shift = if (i == focused) ride else 0; + try addDecor(g, gpa, box.x0, box.y0 - shift, box.x1, box.y1 - shift, box.rgb, 1, win_w, win_h); + }; +} + +/// The triangle overlay: the cursor's glide, over everything. +fn buildOverlay( + g: *Gui, + which: pardes.config.Runtime.Pet, + trail_on: bool, + surface: *const pardes.Surface, + now_ns: u64, + sw: u32, + sh: u32, +) u32 { + if (g.overlay_vertices.len == 0 or sw == 0 or sh == 0) return 0; + var builder = OverlayBuilder{ .vertices = g.overlay_vertices, .win_w = @floatFromInt(sw), .win_h = @floatFromInt(sh) }; + appendWorkspacePet(g, which, surface, &builder); + appendJumpTrail(g, trail_on, surface, now_ns, &builder); + appendCursorGlide(g, surface, now_ns, &builder); + return @intCast(builder.len); +} + +/// A jump's trail (jump_trail.zig): the cells behind the cursor in its +/// body, on the page's own ground, drawn over toward the text's colour. +fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { + var at: [5]JumpTrail.Cell = undefined; + const lit = g.trail.see(if (surface.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); + if (lit.len == 0) return; + const cursor = surface.cursor.?; + const body = for (surface.regionList()) |region| { + if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and + cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; + } else return; + const page = surface.chrome.page orelse bg_default; + const w: f32 = @floatFromInt(g.cell_w); + const h: f32 = @floatFromInt(g.cell_h); + for (lit) |cell| { + if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; + const under = &surface.cells[@as(usize, @intCast(cell.y)) * surface.cols + @as(usize, @intCast(cell.x))]; + // On the page's own ground alone: never a selection or a match. + const ground: [3]u8 = if (under.default) page else switch (under.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (!std.mem.eql(u8, &ground, &page)) continue; + var color = overlayRgb(surface.chrome.fg orelse fg_default); + color.a = cell.strength; + const x0 = @as(f32, @floatFromInt(cell.x)) * w; + const y0 = @as(f32, @floatFromInt(cell.y)) * h; + builder.addRect(x0, y0, x0 + w, y0 + h, color); + } +} + +/// The workspace tag's pet (the Pet setting, gui/pet.zig): in the blank +/// end of the grid's first row, past the tag's text, in the tag's colours, +/// on the window's own clock. Nothing of it reaches the core. +fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { + const kind: pet.Kind = @fromBackingInt(@backingInt(which)); + if (kind == .off or surface.rows == 0 or surface.cols == 0) { + g.pet_state = .{}; + return; + } + var occupied: usize = 0; + for (surface.cells[0..surface.cols], 0..) |*cell, i| { + if (cellCodepoint(cell) != ' ') occupied = i + 1; + } + const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); + const region = if (occupied >= surface.cols) null else pet.lane( + occupied, + @floatFromInt(g.tagline_width), + builder.win_w, + band_top, + @floatFromInt(g.tagline_height), + ); + // ponytail: it moves when the window draws; a wake of its own for an + // idle window if a still pet ever matters. + const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; + const ink = overlayRgb(surface.chrome.tag_fg); + const eye = overlayRgb(surface.chrome.tag_bg); + // Behind the cursor: the overlay is over the cells, so the pixels a + // cursor covers are left out. + var boxes: [max_cursors]CursorBox = undefined; + const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; + for (0..pet.height) |y| for (0..pet.width) |x| { + const color = pet.pixel(kind, pose, x, y); + if (color == 0) continue; + const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; + const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; + const covered = for (cursors) |box| { + if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; + } else false; + if (covered) continue; + builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); + }; +} + +fn overlayRgb(rgb: [3]u8) OverlayColor { + return .{ + .r = @as(f32, @floatFromInt(rgb[0])) / 255.0, + .g = @as(f32, @floatFromInt(rgb[1])) / 255.0, + .b = @as(f32, @floatFromInt(rgb[2])) / 255.0, + .a = 1, + }; +} + +/// G3: the focused cursor while it glides or blinks, its quad from the +/// window's caret (Caret, grid cells) in its cursor colour; a little less +/// than solid, so the glyphs it passes over stay legible. +fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { + const chrome = &surface.chrome; + if (g.cursor_quad_alpha <= 0.001) return; + const layout = fixedCellLayout(g); + const ride = caretRide(g, surface); + // Never off the grid, however a long jump bows. + var quad = g.caret.sample(now_ns); + for (&quad) |*point| point.* = .{ std.math.clamp(point[0], 0, @as(f32, @floatFromInt(surface.cols))), std.math.clamp(point[1], 0, @as(f32, @floatFromInt(surface.rows))) }; + if (ride != 0) { + // Carried past the body's edge with its line: clipped as the text is. + const mid = quad[0][1] - ride + 0.5; + const top: f32 = @floatFromInt(g.glide.body_y); + if (mid < top or mid > top + @as(f32, @floatFromInt(g.glide.body_h))) return; + } + var px: [4][2]f32 = undefined; + var centre: [2]f32 = .{ 0, 0 }; + for (&px, 0..) |*point, i| { + point.* = .{ quad[i][0] * layout.w, (quad[i][1] - ride) * layout.h }; + centre[0] += point[0] / 4; + centre[1] += point[1] / 4; + } + // Its colour: the cursor the cells would draw nearest the quad. + var boxes: [max_cursors]CursorBox = undefined; + var rgb: [3]u8 = chrome.fg orelse fg_default; + var nearest: f32 = std.math.inf(f32); + for (boxes[0..cursorBoxes(g, surface, layout, builder.win_h, &boxes)]) |box| { + const dx = (box.x0 + box.x1) / 2 - centre[0]; + const dy = (box.y0 + box.y1) / 2 - centre[1]; + if (dx * dx + dy * dy < nearest) { + nearest = dx * dx + dy * dy; + rgb = box.rgb; + } + } + const color: OverlayColor = .{ .r = @as(f32, @floatFromInt(rgb[0])) / 255, .g = @as(f32, @floatFromInt(rgb[1])) / 255, .b = @as(f32, @floatFromInt(rgb[2])) / 255, .a = g.cursor_quad_alpha }; + builder.addTri(px[0][0], px[0][1], px[1][0], px[1][1], px[2][0], px[2][1], color); + builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color); +} + +const OverlayBuilder = struct { + vertices: []OverlayVertex, + len: usize = 0, + win_w: f32, + win_h: f32, + + fn addVertex(b: *OverlayBuilder, px: f32, py: f32, color: OverlayColor) void { + if (b.len >= b.vertices.len) return; + b.vertices[b.len] = .{ + .x = (px / b.win_w) * 2.0 - 1.0, + .y = 1.0 - (py / b.win_h) * 2.0, + .r = color.r, + .g = color.g, + .b = color.b, + .a = color.a, + }; + b.len += 1; + } + + fn addTri(b: *OverlayBuilder, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, color: OverlayColor) void { + if (b.len + 3 > b.vertices.len) return; + b.addVertex(x0, y0, color); + b.addVertex(x1, y1, color); + b.addVertex(x2, y2, color); + } + + fn addRect(b: *OverlayBuilder, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, color: OverlayColor) void { + if (b.len + 6 > b.vertices.len) return; + const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, b.win_w); + const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, b.win_w); + const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, b.win_h); + const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, b.win_h); + if (x1 <= x0 or y1 <= y0) return; + b.addTri(x0, y0, x1, y0, x1, y1, color); + b.addTri(x0, y0, x1, y1, x0, y1, color); + } +}; + +fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { + const raw = env.get(name) orelse return null; + return std.fmt.parseInt(u16, raw, 10) catch null; +} + +fn pixelCell(px: f32, cell: u32) u16 { + const idx = @floor(@max(px, 0) / @as(f32, @floatFromInt(@max(cell, 1)))); + return @intFromFloat(@min(idx, 10_000)); +} + +fn wheelRunFile(gpa: std.mem.Allocator) !*pardes.Pardes { + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + errdefer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..400) |i| try text.print(gpa, "{d:0>4} a line of the file\n", .{i}); + _ = try core.setTestFile(text.items); + for ("200G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + return core; +} + +fn tagLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { + for (layers) |*layer| { + const r = layer.viewport; + if (layer.rows > 0 and row >= r.y and row - r.y < layer.rows and col >= r.x and col - r.x < r.w) return layer; + } + return null; +} + +fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer) !void { + for (0..rows) |row| for (0..cols) |col| { + const scan = bodyLayerIn(body_layers, @intCast(col), @intCast(row)) != null or tagLayerIn(tag_layers, @intCast(col), @intCast(row)) != null; + try std.testing.expectEqual(scan, cover[row * cols + col].layer); + }; +} + +/// A Gui that can shape and rasterize the face in `bytes` at `px`, and +/// nothing else. From here on the fonts allocate from std.testing.allocator +/// (the caller puts font_allocator back), so the test counts what they leak. +fn textTestGui(bytes: []const u8, px: f32) !Gui { + var atlas = try Atlas.init(std.testing.allocator, bytes); + atlas.prime(); + font_allocator = std.testing.allocator; + var cw: c_int = 0; + var ch: c_int = 0; + var ascent: c_int = 0; + atlas.cellMetrics(px, &cw, &ch, &ascent); + const tag = taglineRaster(&atlas, px, @intCast(cw), @intCast(ch), 82); + var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); + g.atlas = atlas; + g.px = px; + g.ascent = ascent; + g.tagline_px = tag.px; + g.tagline_baseline = tag.baseline; + resetGlyphAtlas(&g); + return g; +} + +fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell { + var line: [text.len]pardes.Cell = @splat(.{ .default = false }); + for (&line, text) |*cell, byte| cell.text[0] = byte; + return line; +} + +fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { + var it = g.atlas.glyphs.iterator(); + while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; + return error.NoGlyph; +} + +/// Every cursor on the frame where it is drawn, in window pixels: the grid's +/// where no layer has its cell, and each layer's at that layer's pitch. A bar +/// is an eighth of its cell wide, a block the whole cell. +fn cursorBoxes(g: *const Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, out: *[max_cursors]CursorBox) usize { + const chrome = &surface.chrome; + var n: usize = 0; + if (surface.cursor) |cursor| { + if (cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerIn(surface.bodyLayers(), cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { + const cell = &surface.cells[@as(usize, cursor.y) * surface.cols + cursor.x]; + const role = cellFontRole(cell); + const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; + const height = std.math.clamp(if (role == .tagline) @as(f32, @floatFromInt(g.tagline_height)) else layout.h, 1.0, layout.h); + const x0 = @as(f32, @floatFromInt(cursor.x)) * layout.w; + const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))); + out[n] = .{ .x0 = x0, .y0 = y0, .x1 = x0 + if (cursor.bar) @max(dp(1), width / 8.0) else width, .y1 = y0 + height, .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; + n += 1; + } + } + for (surface.bodyLayers()) |*layer| { + if (layer.rows == 0) continue; + const cursor = layer.cursor orelse continue; + if (cursor.y >= layer.rows or cursor.x >= layer.cols) continue; + const left = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; + const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; + const top = layer.rowTop(cursor.y, layout.h, @floatFromInt(g.tagline_height)); + if (top >= bottom) continue; + const height = layer.rowHeight(cursor.y, layout.h, @floatFromInt(g.tagline_height)); + const role: pardes.FontRole = if (cursor.y < layer.context_rows) .tagline else .body; + const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; + const x = left + @as(f32, @floatFromInt(cursor.x)) * width; + const cell = &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x]; + out[n] = .{ .x0 = x, .y0 = top, .x1 = x + if (cursor.bar) @max(dp(1), width / 8) else width, .y1 = @min(bottom, top + height), .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; + n += 1; + } + for (surface.tagLayers()) |*layer| { + if (layer.rows == 0) continue; + const cursor = layer.cursor orelse continue; + if (cursor.x >= layer.cols or cursor.y >= layer.rows) continue; + const width: f32 = @floatFromInt(g.tagline_width); + const span = layer.caretSpan(cursor.x, layout.w, width, if (cursor.bar) @max(dp(1), width / 8) else width); + const y = layer.viewport.y + cursor.y; + const top = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))); + out[n] = .{ .x0 = span[0], .y0 = top, .x1 = span[1], .y1 = top + @as(f32, @floatFromInt(g.tagline_height)), .rgb = cursorColor(chrome, &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x], .tagline), .bar = cursor.bar }; + n += 1; + } + return n; +} + +fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { + return if (role == .tagline) switch (cell.style.fg) { + .rgb => |rgb| rgb, + else => chrome.tag_fg, + } else chrome.fg orelse fg_default; +} + +test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { + // HarfBuzz's process-wide objects come from the default heap, as in runNative. + var primer = try Atlas.init(std.testing.allocator, font_ttf); + primer.prime(); + primer.deinit(std.testing.allocator); + font_allocator = std.testing.allocator; + defer font_allocator = std.heap.smp_allocator; + + var atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer atlas.deinit(std.testing.allocator); + atlas.reset(32); + const size: Atlas.Size = .{ .px = 27, .cell_w = 32, .height = 48, .baseline = 30 }; + const g_slot = atlas.cachedGlyph(.{ .face = 0, .glyph = atlas.glyphForCodepoint('g').glyph, .role = .body, .decoration = .{ .bold = true } }, size, size, config.GUTTER, 1).?; + try std.testing.expect(Atlas.inkBounds(atlas.atlas_stage[@as(usize, g_slot.v) * atlas_w + g_slot.u ..], atlas_w, 32, 48) != null); + try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph)); + + // A font with ligatures runs the whole HarfBuzz pass. + const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + defer std.testing.allocator.free(bytes); + var maple = try Atlas.init(std.testing.allocator, bytes); + defer maple.deinit(std.testing.allocator); + var cell_w: c_int = 0; + var cell_h: c_int = 0; + var ascent: c_int = 0; + maple.cellMetrics(27, &cell_w, &cell_h, &ascent); + const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; + var shaped: [text.len]c.UIShapedCell = undefined; + maple.shape(0, 27, @intCast(cell_w), &text, &shaped); + try std.testing.expectEqual(@as(u8, 2), shaped[1].span); + try std.testing.expectEqual(@as(u8, 2), shaped[4].span); +} + +test "every font size step moves the cell, and the ends are reachable exactly" { + var atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer atlas.deinit(std.testing.allocator); + var px = font_px_min + font_px_step; + while (px <= font_px_max) : (px += 1.0) { + var cw: c_int = 0; + var ch: c_int = 0; + var asc: c_int = 0; + var pw: c_int = 0; + var ph: c_int = 0; + atlas.cellMetrics(px, &cw, &ch, &asc); + atlas.cellMetrics(px - font_px_step, &pw, &ph, &asc); + try std.testing.expect(cw > pw and ch > ph); + } + try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max)); + try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max)); +} + +test "tagline glyph shrinks into its own cell and stays vertically centered" { + const body_px: f32 = 27.0; + var g = try textTestGui(font_ttf, body_px); + defer font_allocator = std.heap.smp_allocator; + defer g.atlas.deinit(std.testing.allocator); + defer g.words.deinit(std.testing.allocator); + _ = fitTaglineFont(&g, config.gui_tagline_font_percent); + const cell_w: c_int = @intCast(g.cell_w); + const cell_h: c_int = @intCast(g.cell_h); + const tag = taglineRaster(&g.atlas, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); + try std.testing.expect(tag.px < body_px); + try std.testing.expect(tag.width < @as(u32, @intCast(cell_w))); + + // Each at its role's size, as a frame draws it. + const h = g.atlas.glyphForCodepoint('H').glyph; + const body = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .body }).?; + const tagline = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .tagline }).?; + const b = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, body.v) * atlas_w + body.u ..], atlas_w, @intCast(cell_w), @intCast(cell_h)).?; + const t = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, tagline.v) * atlas_w + tagline.u ..], atlas_w, @intCast(tag.width), @intCast(tag.height)).?; + try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x); + try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y); + const body_center_x: isize = @intCast(b.min_x + b.max_x); + const tag_center_x: isize = @intCast(t.min_x + t.max_x); + const body_center_y: isize = @intCast(b.min_y + b.max_y); + const centered_top: isize = @intCast((@as(u32, @intCast(cell_h)) - tag.height) / 2); + const tag_center_y: isize = @as(isize, @intCast(t.min_y + t.max_y)) + centered_top * 2; + const body_slot_center: isize = @intCast(@as(u32, @intCast(cell_w)) - 1); + const tag_slot_center: isize = @intCast(tag.width - 1); + try std.testing.expect(@abs((tag_center_x - tag_slot_center) - (body_center_x - body_slot_center)) <= 2); + try std.testing.expect(@abs(tag_center_y - body_center_y) <= 4); + try std.testing.expect(tag.height < @as(u32, @intCast(cell_h))); +} + +test "tagline percentage changes measured band height without body metrics" { + var atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer atlas.deinit(std.testing.allocator); + var cell_w: c_int = 1; + var cell_h: c_int = 1; + var ascent: c_int = 1; + atlas.cellMetrics(27.0, &cell_w, &cell_h, &ascent); + const small = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 40); + const configured = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 82); + const full = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 100); + try std.testing.expect(small.width < configured.width); + try std.testing.expect(configured.width <= full.width); + try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width); + try std.testing.expect(small.height < configured.height); + try std.testing.expect(configured.height <= full.height); + try std.testing.expect(full.height <= @as(u32, @intCast(cell_h))); +} + +test "installed Nerd Symbols fallback covers Yazi directory icons" { + try std.testing.expectEqualStrings("SymbolsNerdFont-Regular", fonts.fallback_names[2]); + + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const candidate = for (fonts.fallbacks(arena_state.allocator())) |font| { + if (std.mem.eql(u8, font.name, "SymbolsNerdFont-Regular")) break font; + } else return; + + const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); + defer std.testing.allocator.free(bytes); + var atlas = try Atlas.init(std.testing.allocator, bytes); + defer atlas.deinit(std.testing.allocator); + try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); +} + +test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var shell: Shell = undefined; + shell.core = core; + shell.gpa = gpa; + shell.ptys = &ptys; + shell.gens = &gens; + shell.queue = &queue; + defer shell.shutdownPtys(); + const rcs: host_io.Shell.PromptFiles = .{}; + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); + try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + var eof = false; + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + for (batch.slice()) |msg| switch (msg) { + .output => |o| { + try std.testing.expect(!eof); + try bytes.appendSlice(gpa, o.bytes); + }, + .eof => |e| { + try std.testing.expect(e.failure == null); + eof = true; + }, + else => return error.UnexpectedMessage, + }; + if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expect(eof); + try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); + shell.closePty(0); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); +} + +test "GUI PTY Restore joins a real reader waiting for queue space" { + const gpa = std.testing.allocator; + var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + try dump.dumpState(core); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(1, 1); + for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var shell: Shell = undefined; + shell.core = core; + shell.gpa = gpa; + shell.ptys = &ptys; + shell.gens = &gens; + shell.queue = &queue; + defer shell.shutdownPtys(); + const rcs: host_io.Shell.PromptFiles = .{}; + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); + try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); + try host_io.PtyTests.waitBlocked(&queue); + const old_serial = core.panes[0].?.serial; + const replacement = try dump.restore(core, core.dump_out.?, "test"); + shell.stopPtys(); + core.deinit(); + core = replacement; + shell.core = replacement; + // The dump's pane, its serial too; its old shell stopped all the same. + try std.testing.expectEqual(old_serial, core.panes[0].?.serial); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); + queue.cancelReader(1, 1); + queue.acceptReader(0, gens[0]); + queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + try std.testing.expect(queue.pushOutput(0, gens[0], try gpa.dupe(u8, "fresh"))); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); +} + +test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var shell: Shell = undefined; + shell.core = core; + shell.gpa = gpa; + shell.ptys = &ptys; + shell.gens = &gens; + shell.queue = &queue; + defer shell.shutdownPtys(); + const rcs: host_io.Shell.PromptFiles = .{}; + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); + try core.removePane(0, null); + shell.reconcilePtys(); + try std.testing.expect(queue.readers[0] == null); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); + try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); + shell.shutdownPtys(); + try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG)); + try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); +} + +test "GUI PTY file watcher stops and joins without closing its watched descriptor" { + if (!file_watch.supported) return error.SkipZigTest; + const gpa = std.testing.allocator; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + const fd = file_watch.init(true); + if (fd < 0) return error.WatchInitFailed; + defer _ = libc.close(fd); + const stop = try stopPipe(); + defer for (stop) |pipe_fd| { + _ = libc.close(pipe_fd); + }; + const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue }); + _ = host_io.writeFd(stop[1], "x"); + thread.join(); + try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); +} + +test "GUI completion failure survives backlog and leaves the document unchanged" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("abc"); + pane.body.cur_col = 1; + core.lspRequest(core.view().active, .completion, ""); + const id = core.lsp_ask.wait.?.id; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = id }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..output_capacity) |_| queue.push(.{ .output = .{ + .pane = 0, + .gen = 1, + .bytes = try gpa.dupe(u8, "output"), + } }); + queue.push(.{ .lsp = .{ .id = id, .rows = null } }); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var shell: Shell = undefined; + shell.core = core; + shell.queue = &queue; + shell.gpa = gpa; + shell.lsp_allocator = gpa; + shell.gens = &gens; + shell.ptys = &ptys; + shell.drainQueue(); + try std.testing.expect(core.lsp_ask.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); +} + +test "GUI 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 queue: Queue = .{ + .io = std.testing.io, + .gpa = gpa, + .lsp_allocator = failing.allocator(), + }; + defer queue.deinit(); + var tasks: PipeTasks = .{}; + core.lspRequest(core.view().active, .status, ""); + const req: host_io.Lsp.Request = .{ + .id = core.lsp_ask.wait.?.id, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }; + if (failure == 0) { + queue.lsp_id = req.id -% 1; + queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); + queue.startLsp(core, req); + try std.testing.expectEqual(req.id, queue.lsp_id.?); + try std.testing.expectEqual(@as(usize, 0), queue.completion_len); + queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); + try std.testing.expectEqual(@as(usize, 0), queue.completion_len); + } else { + var shell: Shell = undefined; + shell.core = core; + shell.threads_ok = false; + lsp(&shell, req); + } + try std.testing.expect(core.lsp_ask.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; + selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(queue.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), tasks.len); + try std.testing.expectEqual(@as(usize, 0), queue.len); + } +} + +test "high-density window coordinates map once to render pixels" { + const geometry: WindowGeometry = .{ + .window_w = 560, + .window_h = 360, + .pixel_w = 1120, + .pixel_h = 720, + }; + try std.testing.expectEqual(Point{ .x = 700, .y = 240 }, windowPointToPixels(geometry, 350, 120)); +} + +test "the GUI's stdin keys reach a terminal pane as the tty's do: F5, Insert and the keypad's Up" { + 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 in: Input = .{ .core = core }; + var parser: vaxis.Parser = .{}; + var bytes: []const u8 = "\x1b[15~\x1b[2~\x1b[57419u"; + while (bytes.len > 0) { + const result = try parser.parse(bytes, gpa); + bytes = bytes[result.n..]; + if (result.event) |event| switch (event) { + .key_press => |key| postKey(&in, key, key.text orelse ""), + 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("\x1b[15~\x1b[2~\x1b[A", written.written()); +} + +test "the window's function and editing keys reach a terminal 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 in: Input = .{ .core = core }; + var written: std.Io.Writer.Allocating = .init(gpa); + defer written.deinit(); + const Case = struct { modes: []const u8, sym: c.SDL_Keycode, mod: c.SDL_Keymod = 0, sent: []const u8 }; + const cases = [_]Case{ + .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[A" }, + .{ .modes = "", .sym = c.SDLK_HOME, .sent = "\x1b[H" }, + .{ .modes = "", .sym = c.SDLK_F1, .sent = "\x1bOP" }, + .{ .modes = "", .sym = c.SDLK_F5, .sent = "\x1b[15~" }, + .{ .modes = "", .sym = c.SDLK_F12, .mod = c.SDL_KMOD_LSHIFT, .sent = "\x1b[24;2~" }, + .{ .modes = "", .sym = c.SDLK_INSERT, .sent = "\x1b[2~" }, + // DECCKM: less, vim, htop. + .{ .modes = "\x1b[?1h", .sym = c.SDLK_UP, .sent = "\x1bOA" }, + .{ .modes = "", .sym = c.SDLK_END, .sent = "\x1bOF" }, + .{ .modes = "", .sym = c.SDLK_LEFT, .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[1;5D" }, + // codex's kitty flags (>7u): Ctrl-C and Alt-a are unambiguous. + // (A bare Escape at a shell prompt is pardes's way out of raw input.) + .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, + .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, + // With event types asked for (2), an arrow says it is a press, as + // the emulator's encoder says it. + .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, + }; + for (cases) |case| { + core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); + while (core.nextEffect()) |_| {} + keyDown(&in, case.sym, case.mod); + 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 "tagline pointer mapping retains physical grips and carries logical text coordinates" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); + core.update(.{ .command = "Newcol" }); + core.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 12 }; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + _ = try core.render(arena.allocator()); + + const r = core.view().rects[core.view().active]; + const body_w: f32 = 10; + const body_h: f32 = 20; + const tag_w: f32 = 8; + const tag_y = r.y; + const x = @as(f32, @floatFromInt(r.x + pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; + + const tag = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); + try std.testing.expectEqual(pixelCell(x, 10), tag.col); + try std.testing.expectEqual(tag_y, tag.row); + try std.testing.expectEqual(@as(u16, 3), tag.tag_hit.?.col); + try std.testing.expectEqual(pardes.TagKind.pane, tag.tag_hit.?.kind); + const grip = gridCellAtDimensions(core, @as(f32, @floatFromInt(r.x + config.GUTTER)) * body_w - 0.1, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); + try std.testing.expect(grip.tag_hit == null); + try std.testing.expectEqual(r.x + config.GUTTER - 1, grip.col); + + const body_y = tag_y + core.panes[core.view().active].?.tag_rows; // a long tag wraps + const body = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(body_y)) + 0.5) * body_h, body_w, body_h, tag_w); + try std.testing.expectEqual(pixelCell(x, 10), body.col); + try std.testing.expectEqual(body_y, body.row); + try std.testing.expect(body.tag_hit == null); + + // The workspace tag's text starts TAG_TEXT_INSET cells in, as a pane's. + const x_top = @as(f32, @floatFromInt(pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; + const topbar = gridCellAtDimensions(core, x_top, 0.5 * body_h, body_w, body_h, tag_w); + try std.testing.expectEqual(pixelCell(x_top, 10), topbar.col); + try std.testing.expectEqual(@as(u16, 3), topbar.tag_hit.?.col); + try std.testing.expectEqual(pardes.TagKind.workspace, topbar.tag_hit.?.kind); +} + +test "a click at the window's corner lands in the corner cell" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + var g = testGui(10, 20, 6, 12); + const geometry: WindowGeometry = .{ .window_w = 400, .window_h = 240, .pixel_w = 800, .pixel_h = 480 }; + const last = mouseCellWithGeometry(&g, core, 399.9, 239.9, geometry); + try std.testing.expectEqual(@as(u16, 79), last.col); + try std.testing.expectEqual(@as(u16, 23), last.row); + const first = mouseCellWithGeometry(&g, core, 0, 0, geometry); + try std.testing.expectEqual(@as(u16, 0), first.col); + try std.testing.expectEqual(@as(u16, 0), first.row); +} + +test "a blink holds while typing, eases at its edges and stops when idle" { + const ms = std.time.ns_per_ms; + try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); + const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); + try std.testing.expectEqual(@as(f32, 0), out.alpha); + const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); + try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); + try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); + try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); +} + +test "background opacity acknowledges success and rolls back unsupported surfaces" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + var applied: u8 = 100; + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 70")); + try std.testing.expect(core.settings.window_opacity_pending); + finishWindowOpacity(core, &applied, null); + try std.testing.expectEqual(@as(u8, 70), applied); + try std.testing.expect(!core.settings.window_opacity_pending); + + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); + finishWindowOpacity(core, &applied, "background transparency requires an alpha-capable SDL window"); + try std.testing.expectEqual(@as(u8, 70), applied); + try std.testing.expectEqual(applied, core.settings.window_opacity); + try std.testing.expect(!core.settings.window_opacity_pending); + const pane = core.panes[0].?; + try std.testing.expectEqualStrings("WindowOpacity: background transparency requires an alpha-capable SDL window", pane.msg[0..pane.msg_len]); + + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); + try std.testing.expect(core.settings.window_opacity_pending); + finishWindowOpacity(core, &applied, null); + try std.testing.expectEqual(@as(u8, 40), applied); + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 100")); + finishWindowOpacity(core, &applied, null); + try std.testing.expectEqual(@as(u8, 100), applied); +} + +test "the clipboard pasted into a terminal reaches its pty as xterm pastes: bracketed when asked, no ESC[201~ smuggled through" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer core.deinit(); + var shell: Shell = undefined; + shell.core = core; + var sent: std.ArrayList(u8) = .empty; + defer sent.deinit(gpa); + const take = struct { + fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + while (core_.nextEffect()) |effect| { + if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); + } + return out.items; + } + }.f; + _ = try take(core, &sent); + // The clipboard is SDL's own with no display to hold one. + _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "dummy"); + defer _ = c.SDL_ResetHint(c.SDL_HINT_VIDEO_DRIVER); + if (!c.SDL_InitSubSystem(c.SDL_INIT_VIDEO)) return error.SkipZigTest; + defer c.SDL_QuitSubSystem(c.SDL_INIT_VIDEO); + putClipboard(gpa, "ls\x1b[201~; rm -rf ~\nx"); + readClipboard(&shell); + try std.testing.expectEqualStrings("ls [201~; rm -rf ~\rx", try take(core, &sent)); + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); + _ = try take(core, &sent); + readClipboard(&shell); + try std.testing.expectEqualStrings("\x1b[200~ls [201~; rm -rf ~\nx\x1b[201~", try take(core, &sent)); +} + +test "fractional wheel delta moves the picture by the same fraction" { + const delta = accumulateWheelDelta(0, -0.125); + const s = applyScrollDelta(0, delta); + const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; + try std.testing.expectEqual(@as(f32, 0.125), delta); + try std.testing.expectEqual(@as(f32, 0.125), picture); + try std.testing.expectEqual(@as(i32, 1), s.rows); + try std.testing.expectEqual(@as(f32, -0.875), s.lag); +} + +test "repeated fractional deltas cross exactly one core row" { + var core_row: i32 = 0; + var lag: f32 = 0; + var crossed: u32 = 0; + for (0..8) |_| { + const s = applyScrollDelta(lag, 0.125); + core_row += s.rows; + crossed += @intCast(@abs(s.rows)); + lag = s.lag; + } + try std.testing.expectEqual(@as(u32, 1), crossed); + try std.testing.expectEqual(@as(i32, 1), core_row); + try std.testing.expectEqual(@as(f32, 0), lag); +} + +test "wheel magnitude is preserved without quantization" { + const delta = accumulateWheelDelta(0, -2.75); + const s = applyScrollDelta(0, delta); + const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; + try std.testing.expectEqual(@as(f32, 2.75), delta); + try std.testing.expectEqual(@as(f32, 2.75), picture); + try std.testing.expectEqual(@as(i32, 3), s.rows); + try std.testing.expectEqual(@as(f32, -0.25), s.lag); + try std.testing.expectEqual(@as(f32, 0), accumulateWheelDelta(0, std.math.inf(f32))); + + const bounded = boundScrollDelta(0, 3.0e38, 24); + const safe = applyScrollDelta(0, bounded); + try std.testing.expectEqual(@as(f32, 24), bounded); + try std.testing.expectEqual(@as(i32, 24), safe.rows); +} + +test "fractional scroll reversals preserve signed distance" { + var core_row: i32 = 0; + const forward = applyScrollDelta(0, 0.375); + core_row += forward.rows; + try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(core_row)) + forward.lag); + + const reverse = applyScrollDelta(forward.lag, -0.125); + core_row += reverse.rows; + try std.testing.expectEqual(@as(i32, -1), reverse.rows); + try std.testing.expectEqual(@as(f32, 0.25), @as(f32, @floatFromInt(core_row)) + reverse.lag); + try std.testing.expect(reverse.lag >= 0 and reverse.lag < 1); +} + +test "a wheel's notch is whole lines, a touchpad's fraction is not" { + try std.testing.expectEqual(@as(?i32, 1), notchOf(-1, -1)); + try std.testing.expectEqual(@as(?i32, -3), notchOf(3, 3)); + try std.testing.expectEqual(@as(?i32, null), notchOf(-0.25, 0)); + try std.testing.expectEqual(@as(?i32, null), notchOf(-1.5, -1)); + try std.testing.expectEqual(@as(?i32, null), notchOf(std.math.nan(f32), 1)); +} + +test "a click over codex in a terminal reaches its pty with its modifiers; Shift swaps B1 to pardes and B2 to the program" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer core.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try core.render(frame.allocator()); + var in: Input = .{ .core = core }; + var sent: std.ArrayList(u8) = .empty; + defer sent.deinit(gpa); + const take = struct { + fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + while (core_.nextEffect()) |effect| { + if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); + } + return out.items; + } + }.f; + _ = try take(core, &sent); + const pane = core.panes[0].?; + const r = core.view().rects[0]; + const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; + const next: MouseCell = .{ .col = mc.col + 1, .row = mc.row }; + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); + _ = try take(core, &sent); + in.post(.{ .mouse = pointerMouse(.none, .motion, mc, .{}) }); + try std.testing.expectEqualStrings("\x1b[<35;6;4M", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .ctrl = true }) }); + try std.testing.expectEqualStrings("\x1b[<16;6;4M", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.left, .drag, next, .{}) }); + try std.testing.expectEqualStrings("\x1b[<32;7;4M", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.left, .release, next, .{}) }); + try std.testing.expectEqualStrings("\x1b[<0;7;4m", try take(core, &sent)); + // Shift-B1 is pardes's select; B2 is pardes's execute and Shift-B2 + // the program's, reported without the Shift. + in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .shift = true }) }); + in.post(.{ .mouse = pointerMouse(.left, .release, mc, .{ .shift = true }) }); + try std.testing.expectEqualStrings("", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{}) }); + in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{}) }); + try std.testing.expectEqualStrings("", try take(core, &sent)); + in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{ .shift = true }) }); + in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{ .shift = true }) }); + try std.testing.expectEqualStrings("\x1b[<1;6;4M\x1b[<1;6;4m", try take(core, &sent)); +} + +test "a wheel over codex in a terminal reaches its pty as the mouse reports it asked for" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); + defer core.deinit(); + var frame: std.heap.ArenaAllocator = .init(gpa); + defer frame.deinit(); + _ = try core.render(frame.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + var in: Input = .{ .core = core }; + var sent: std.ArrayList(u8) = .empty; + defer sent.deinit(gpa); + const Sent = struct { + fn take(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + while (core_.nextEffect()) |effect| { + if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); + } + return out.items; + } + }; + _ = try Sent.take(core, &sent); + const pane = core.panes[0].?; + const r = core.view().rects[0]; + const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; + // What codex 0.159's chat sets on start. + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h\x1b[>7u\x1b[?1004h\x1b[?1049h\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); + _ = try Sent.take(core, &sent); + // A notch up, then a fast turn of three down: each its report, none + // left behind for a glide. + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); + try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); + wheelAt(&g, &in, .{ .y = -3, .integer_y = -3 }, mc); + try std.testing.expectEqualStrings(std.mem.asBytes(&@as([3][10]u8, @splat("\x1b[<65;6;4M".*))), try Sent.take(core, &sent)); + try std.testing.expectEqual(@as(i32, 0), g.scroll_notch); + try std.testing.expect(g.scroll_pane == null); + // A touchpad's fractions add up to a turn. + wheelAt(&g, &in, .{ .y = 0.5 }, mc); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + wheelAt(&g, &in, .{ .y = 0.5 }, mc); + try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); + // Alt is meta, 8; Shift keeps the turn pardes's own, a glide. + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .alt = true } }, mc); + try std.testing.expectEqualStrings("\x1b[<72;6;4M", try Sent.take(core, &sent)); + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .shift = true } }, mc); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); + stepGlide(&g, core); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + resetScroll(&g); + // Its sign-in screen: mouse off, alternate scroll on, so arrow keys. + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1007h" } }); + _ = try Sent.take(core, &sent); + wheelAt(&g, &in, .{ .y = -1, .integer_y = -1 }, mc); + try std.testing.expectEqualStrings("\x1b[B", try Sent.take(core, &sent)); + // Back on the main screen a shell's wheel is ours: a notch to glide, + // nothing to the pty. + core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l" } }); + _ = try Sent.take(core, &sent); + wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); + try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); + try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); +} + +test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + // Lines of two rows each at this width, numbered so no two rows match. + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..60) |i| { + try text.print(gpa, "{d:0>4} ", .{i}); + try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); + try text.append(gpa, '\n'); + } + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ms = std.time.ns_per_ms; + var now: u64 = std.time.ns_per_s; + core.advance(now); + var s = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + const r = core.view().rects[core.view().active]; + g.scroll_pane = core.view().active; + g.scroll_col = r.x + 10; + g.scroll_row = r.y + r.h - 2; + const body_y = core.bodyTop(core.panes[core.view().active].?, r); + const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); + defer gpa.free(row_before); + // The window has drawn the view once (Glide.frame finds a view that moved). + g.now_ns = now; + glideFrame(&g, gpa, s); + // One notch down: the core is a line on at once. + g.scroll_notch = 1; + const scrolled = core.panes[core.view().active].?.scroll(); + stepGlide(&g, core); + try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); + _ = arena.reset(.retain_capacity); + s = try core.render(arena.allocator()); + glideFrame(&g, gpa, s); + // The window's own motion: it draws its frames while it moves. + try std.testing.expect(frontendMoving(&g)); + // Its two rows: the picture two rows behind, the rows that left kept, + // nearest first. + try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); + try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); + try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); + // Frame by frame it comes back, never past, and settles. + var frames: usize = 0; + while (g.glide.moving()) : (frames += 1) { + now += 7 * ms; + core.advance(now); + stepGlide(&g, core); + g.now_ns = now; + glideFrame(&g, gpa, s); + try std.testing.expect(g.glide.follow.offset <= 1e-4); + if (frames > 200) return error.NeverSettled; + } + try std.testing.expect(frames > 5); + try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); + try std.testing.expect(!frontendMoving(&g)); +} + +test "a fractional wheel turn that brings the picture back onto the core's row is drawn: the window never rests on a frame half a row off" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + // A high-resolution wheel's half notches (SDL's y, up positive), a + // frame each: the first scrolls the core a line and leaves the picture + // half a row behind it; the second takes the picture onto it. + for (0..2) |_| { + try wr.frame(gpa, &.{-0.5}); + try std.testing.expectEqual(wr.picture(), wr.drawn); + } + try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); +} + +test "a wheel turned down then up never draws the picture moving against the turn" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + // Two half notches down (the picture back on the core's row), then + // quarter notches up, a frame each and frames between: each frame's + // picture is where the last left it or on the way the wheel turns, + // never back against it. + for ([_]struct { f32, usize }{ .{ -0.5, 2 }, .{ 0.25, 4 } }) |phase| { + const turn, const turns = phase; + for (0..turns + 4) |k| { + const was = wr.drawn; + try wr.frame(gpa, if (k < turns) &.{turn} else &.{}); + const moved = wr.drawn - was; + try std.testing.expect(moved * -turn >= -1e-4); + } + } +} + +test "a fine wheel's turns that stop at a fraction leave the text on a whole row, and a turn mid-settle is not lost" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + const line = struct { + fn of(p: *pardes.Pardes) i64 { + return @intCast(p.panes[p.view().active].?.scroll()); + } + }.of; + const first = line(core); + // Three quarter notches down, a frame each: the core a line on, the + // picture a quarter row behind it. Then nothing: it eases onto the + // core's row (never back against the turns) and rests there, drawn. + for (0..3) |_| try wr.frame(gpa, &.{-0.25}); + try std.testing.expect(wr.g.scroll_lag != 0); + var frames: usize = 0; + while (wr.g.scroll_lag != 0) : (frames += 1) { + const was = wr.drawn; + try wr.frame(gpa, &.{}); + try std.testing.expect(wr.drawn >= was); + try std.testing.expect(frames < 20); + } + try std.testing.expectEqual(first + 1, line(core)); + try std.testing.expectEqual(wr.picture(), wr.drawn); + try std.testing.expectEqual(@as(f32, @floatFromInt(first + 1)), wr.drawn); + // Again, and a quarter notch more arrives mid-settle: it counts, and + // the settle ends on the row after it. + for (0..3) |_| try wr.frame(gpa, &.{-0.25}); + for (0..4) |_| try wr.frame(gpa, &.{}); + try std.testing.expect(wr.g.scroll_lag != 0); + try wr.frame(gpa, &.{-0.25}); + for (0..20) |_| try wr.frame(gpa, &.{}); + try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); + try std.testing.expectEqual(first + 3, line(core)); + try std.testing.expectEqual(@as(f32, @floatFromInt(first + 3)), wr.drawn); +} + +test "a bar cursor is drawn on its line while a wheel's fraction holds the text off its row, as a block is" { + const gpa = std.testing.allocator; + const core = try wheelRunFile(gpa); + defer core.deinit(); + core.settings.cursor_blink = false; + core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + var wr = try WheelRun.init(gpa, core); + defer wr.deinit(gpa); + defer wr.g.decor.deinit(gpa); + // Half a notch down: the core a line on, the text drawn half a row + // below its cells until the settle. + try wr.frame(gpa, &.{-0.5}); + try std.testing.expectEqual(@as(f32, -0.5), wr.g.scroll_lag); + _ = wr.arena.reset(.retain_capacity); + const s = try core.render(wr.arena.allocator()); + const cu = s.cursor.?; + try std.testing.expect(cu.bar); + const layout = fixedCellLayout(&wr.g); + const win_w: f32 = @floatFromInt(@as(u32, s.cols) * wr.g.cell_w); + const win_h: f32 = @floatFromInt(@as(u32, s.rows) * wr.g.cell_h); + wr.g.decor.clearRetainingCapacity(); + try cursorDecor(&wr.g, gpa, s, layout, win_w, win_h); + try std.testing.expectEqual(@as(usize, 1), wr.g.decor.items.len); + // Its top where its line's top is drawn (emitScrollRows: the row less + // the lag), not on its cell. + const top = (1 - wr.g.decor.items[0].y0) * win_h / 2; + try std.testing.expectApproxEqAbs((@as(f32, @floatFromInt(cu.y)) - wr.g.scroll_lag) * layout.h, top, 0.01); +} + +test "a wheel's caret rides with its line, the text's own glide, never a spring of its own" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); + _ = try core.setTestFile(text.items); + core.settings.cursor_blink = false; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var now: u64 = std.time.ns_per_s; + core.advance(now); + for ("10G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + _ = try core.render(arena.allocator()); + now += std.time.ns_per_s; + core.advance(now); + _ = arena.reset(.retain_capacity); + var s = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + const r = core.view().rects[core.view().active]; + g.scroll_pane = core.view().active; + g.scroll_col = r.x + 10; + g.scroll_row = r.y + r.h - 2; + stepGlide(&g, core); + // The window has drawn the view once (Glide.frame finds a view that moved). + g.now_ns = now; + glideFrame(&g, gpa, s); + const before: f32 = @floatFromInt(s.cursor.?.y); + g.scroll_notch = 1; + stepGlide(&g, core); + var frames: usize = 0; + while (true) : (frames += 1) { + now += 7 * std.time.ns_per_ms; + core.advance(now); + _ = arena.reset(.retain_capacity); + s = try core.render(arena.allocator()); + g.now_ns = now; + glideFrame(&g, gpa, s); + seeCaret(&g, s, fixedCellLayout(&g), 480, now); + if (frames == 0) { + try std.testing.expect(g.glide.caret_rides); + // Where its line is drawn: on the row it was on, the cell a row up. + try std.testing.expectApproxEqAbs(before, caretRow(&g, s, now).?, 1e-3); + } + // Always exactly with its line, the cell less the text's offset. + try std.testing.expectApproxEqAbs(@as(f32, @floatFromInt(s.cursor.?.y)) - g.glide.follow.offset, caretRow(&g, s, now).?, 1e-3); + if (!g.glide.moving()) break; + stepGlide(&g, core); + if (frames > 200) return error.NeverSettled; + } + try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); +} + +test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + // Numbered lines no two alike, short enough never to wrap. + for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + core.advance(std.time.ns_per_s); + _ = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + const body_h: f32 = @floatFromInt(core.view().rects[core.view().active].h - core.panes[core.view().active].?.tag_rows); + const ctrl = struct { + fn key(cp: u21) pardes.Key { + return .{ .cp = cp, .ctrl = true }; + } + }; + const script = [_]GlideRun.Step{ + .{ .frame = 2, .key = ctrl.key('d') }, + .{ .frame = 40, .key = ctrl.key('f') }, + .{ .frame = 80, .key = .{ .cp = 'g', .text = "g" } }, + .{ .frame = 80, .key = .{ .cp = 'e', .text = "e" } }, + .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, + .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, + // Faster than they settle: each adds to the glide under way. + .{ .frame = 160, .key = ctrl.key('d') }, + .{ .frame = 165, .key = ctrl.key('d') }, + .{ .frame = 170, .key = ctrl.key('d') }, + .{ .frame = 175, .key = ctrl.key('d') }, + }; + var seq: GlideRun = .{}; + try seq.play(&g, core, gpa, &arena, &script, 240); + try seq.checkCaret(); + // Every one moves the picture on the frame it is drawn in, and the + // picture lags by what the core moved (a far jump, by one body). + var longest: usize = 0; + var shortest: usize = std.math.maxInt(usize); + for ([_]usize{ 2, 40, 80, 120 }) |at| { + const moved: f32 = @floatFromInt(@abs(seq.lines[at] - seq.lines[at - 1])); + try std.testing.expect(moved >= 1); + const lag = @abs(seq.offsets[at]); + try std.testing.expect(lag > 0.5 * @min(moved, body_h)); + try std.testing.expect(lag <= @min(moved, body_h) + 1e-3); + // Settles on the same law whatever the distance: a few frames for + // a half page, not many more for a jump of 3000 lines. + const frames = seq.settle(at); + longest = @max(longest, frames); + shortest = @min(shortest, frames); + try std.testing.expect(frames >= 8 and frames <= 24); + } + try std.testing.expect(longest - shortest <= 5); + // Readable: never more than a quarter of a body a frame once it moves. + for (1..seq.frames) |k| { + if (seq.lines[k] != seq.lines[k - 1]) continue; + try std.testing.expect(@abs(seq.offsets[k] - seq.offsets[k - 1]) <= body_h / 4 + 1e-3); + } + // The seq of half pages: one glide, never at rest between them, and + // done as soon after the last as one half page alone takes. + for (160..180) |k| try std.testing.expect(seq.offsets[k] != 0); + try std.testing.expect(seq.settle(175) <= seq.settle(2) + 4); +} + +test "a held key moves the view at the stream's own rate, never a bounce a line, and settles once it stops" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + core.advance(std.time.ns_per_s); + _ = try core.render(arena.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.glide.deinit(gpa); + // j held from the top: a repeat every second frame, the view following + // a line a repeat once the caret is at its last rows. + var script: [48]GlideRun.Step = undefined; + for (&script, 0..) |*step, i| step.* = .{ .frame = 20 + 2 * i, .key = .{ .cp = 'j', .text = "j" } }; + var seq: GlideRun = .{}; + try seq.play(&g, core, gpa, &arena, &script, 200); + // Inside the stream the picture moves every frame by about the same + // step: an input's rows over its spacing, not a spring's ease to each. + var least: f32 = std.math.inf(f32); + var most: f32 = 0; + for (90..110) |k| { + const step = (@as(f32, @floatFromInt(seq.lines[k])) + seq.offsets[k]) - (@as(f32, @floatFromInt(seq.lines[k - 1])) + seq.offsets[k - 1]); + least = @min(least, step); + most = @max(most, step); + } + try std.testing.expect(seq.lines[89] > 0 and least > 0.4 and most < 0.6); + // The caret stays on its row, the text moving under it: not a pixel's + // wobble (the glide's fractional lag never reaches it). + for (90..110) |k| try std.testing.expectEqual(seq.carets[89], seq.carets[k]); + // It comes to rest once the keys stop, never past its mark. + for (110..200) |k| try std.testing.expect(seq.offsets[k] <= 0); + try std.testing.expectEqual(@as(f32, 0), seq.offsets[199]); + // Ctrl-d held, then PageDown held: the caret keeps its row the whole + // way, the pages moving under it. + var pages: [40]GlideRun.Step = undefined; + for (&pages, 0..) |*step, i| step.* = .{ .frame = 10 + 2 * i, .key = if (i < 20) .{ .cp = 'd', .ctrl = true } else .{ .cp = pardes.Key.page_down } }; + var held: GlideRun = .{}; + try held.play(&g, core, gpa, &arena, &pages, 100); + try held.checkCaret(); + try seq.checkCaret(); + // (The first of each may move it, one ease: from the last row to where + // a half page keeps it, and from there to a page's.) + for (30..50) |k| try std.testing.expectEqual(held.carets[30], held.carets[k]); + for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); +} + +test "a scroll's shifted rows start under the context rows, and its scissor below their band" { + var surface: pardes.Surface = .{}; + var g = testGui(10, 20, 6, 12); + g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; + g.scroll_body_y = 1; + g.scroll_body_h = 19; + const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; + // On the grid, three body-high rows are held, and nothing moves up. + const grid = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(u16, 3), grid.rows); + try std.testing.expectEqual(@as(f32, 0), grid.lift); + const clip = scrollScissor(&g, layout, 400, 400); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); + try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); + // In a body layer they are tagline-high: the rows under them move up + // by what each is shorter, to where the layer draws them. + surface.body_layers[0].rows = 30; + surface.body_layers[0].context_rows = 3; + const layered = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); + // None held: the whole body moves. + surface.body_layers[0].rows = 0; + try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); + try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); +} + +test "concealed terminal text emits no ink on its ground" { + var g = testGui(10, 20, 6, 12); + var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; + cell.text[0] = 'X'; + const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); + try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot); + try std.testing.expectEqual(bg_default, resolved.bg); +} + +test "a block cursor's cell is drawn reversed: the cell's ink its ground, its ground its ink" { + var g = testGui(10, 20, 6, 12); + // A blank, so no glyph is looked up in this atlas-less Gui. + const cell: pardes.Cell = .{ + .text = .{ ' ', ' ', ' ', ' ', ' ', ' ', ' ' }, + .len = 1, + .default = false, + .style = .{ .fg = .{ .rgb = .{ 10, 20, 30 } }, .bg = .{ .rgb = .{ 200, 210, 220 } } }, + }; + const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); + const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, bg_default); + try std.testing.expectEqual([3]u8{ 10, 20, 30 }, plain.fg); + try std.testing.expectEqual(plain.fg, cursor.bg); + try std.testing.expectEqual(plain.bg, cursor.fg); +} + +test "the layer cover is the per-cell layer scan, over a core's layouts and random layers" { + // A gui-shaped core: its tagline is narrower and shorter than the body, + // so tags and notices are layers. + const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 97, .rows = 31 }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 97, .rows = 31, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 7, .tagline_h = 13 } } }); + for (1..4) |id| _ = try core.newShell(id, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + pardes.layout.insert(core, 1, 1, 2); + pardes.layout.insert(core, 0, 1, 3); + var cover: [97 * 31]Cover = undefined; + var notices = false; + for (0..32) |step| { + if (step & 3 == 0) try std.testing.expect(core.executeBuiltinLine(2, "Collapse")); + core.view().prefix = if (step & 4 != 0) .leader else .none; + if (step & 8 != 0) { + try std.testing.expect(core.executeBuiltinLine(0, "Msg a message chip over the body")); + try std.testing.expect(core.executeBuiltinLine(3, "Msg another")); + } + const s = try core.render(core.scratch.allocator()); + try std.testing.expectEqual(@as(usize, cover.len), @as(usize, s.cols) * s.rows); + @memset(&cover, .{ .layer = true, .floating = true, .grip = true, .focus = true }); // what an earlier frame left + coverFrame(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); + try expectCoverIsScan(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers()); + // A grip's cells know their way to its glyph, and the focused + // pane's tag rows are the focused ones. + for (s.regionList()) |region| { + if (region.kind != .grip) continue; + for (0..region.rect.w) |offset| { + const cell = cover[@as(usize, region.rect.y) * s.cols + region.rect.x + offset]; + try std.testing.expect(cell.grip); + try std.testing.expectEqual(offset, cell.grip_offset); + try std.testing.expectEqual(region.owner == core.view().active, cell.focus); + } + } + for (s.tagLayers()) |layer| notices = notices or (layer.rows != 0 and layer.kind == .notice); + } + try std.testing.expect(notices); + + // Random layers: overlapping, empty, past the grid's right and bottom + // edges, and at the top of u16, where x + w overflows it. + const gen = struct { + fn coordinate(random: std.Random, limit: u16) u16 { + if (random.uintLessThan(u8, 12) == 0) return std.math.maxInt(u16) - random.uintLessThan(u16, 3); + return random.uintAtMost(u16, limit + 3); + } + fn rect(random: std.Random, cols: u16, rows: u16) pardes.Rect { + return .{ .x = coordinate(random, cols), .y = coordinate(random, rows), .w = coordinate(random, cols), .h = coordinate(random, rows / 2) }; + } + }; + var prng = std.Random.DefaultPrng.init(0x6c61796572); + const random = prng.random(); + var body: [pardes.MAX_PANES]pardes.Layer = undefined; + var tag: [pardes.MAX_TAG_LAYERS]pardes.Layer = undefined; + var grid: [64 * 40]Cover = undefined; + for (0..3000) |_| { + const cols = random.intRangeAtMost(u16, 1, 64); + const rows = random.intRangeAtMost(u16, 1, 40); + const empty = random.intRangeAtMost(u8, 2, 5); // about one layer in `empty` is empty + for (&body) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; + for (&tag) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; + const bodies = body[0..random.uintAtMost(usize, body.len)]; + const tags = tag[0..random.uintAtMost(usize, tag.len)]; + const cells = grid[0 .. @as(usize, cols) * rows]; + @memset(cells, .{ .layer = random.boolean() }); + coverFrame(cells, cols, rows, bodies, tags, &.{}); + try expectCoverIsScan(cells, cols, rows, bodies, tags); + } +} + +test "every pixel of a grip column is band, button or ring, and the button sits over the scrollbar" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([60][5]u8, @splat("text\n".*)))); + pane.tag.own = try gpa.dupe(u8, "second\nthird"); + core.newScratchBelow(0); + for ([_]struct { w: u32, h: u32, tag: u32 }{ .{ .w = 10, .h = 20, .tag = 12 }, .{ .w = 17, .h = 35, .tag = 30 }, .{ .w = 9, .h = 19, .tag = 15 }, .{ .w = 12, .h = 24, .tag = 24 } }) |m| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { + core.view().active = focus; + pane.file.?.revision = pane.file.?.saved_revision + @intFromBool(dirty); + core.sync(); + const s = try core.render(core.scratch.allocator()); + var g = testGui(m.w, m.h, m.w, m.tag); + defer g.decor.deinit(gpa); + const layout = fixedCellLayout(&g); + const win_w: f32 = @floatFromInt(60 * m.w); + const win_h: f32 = @floatFromInt(20 * m.h); + const cover = try gpa.alloc(Cover, @as(usize, s.cols) * s.rows); + defer gpa.free(cover); + coverFrame(cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, layout, win_w, win_h, true); + const grip = s.region(.grip, 0).?; + // The grip column's pixels, band first, then its cells, then decor. + const x_px: u32 = grip.rect.x * m.w; + const w_px: u32 = config.GUTTER * m.w; + const y_px: u32 = grip.rect.y * m.h; + const h_px: u32 = grip.rect.h * m.h; + const pixels = try gpa.alloc(?[3]f32, w_px * h_px); + defer gpa.free(pixels); + @memset(pixels, null); + const paint = struct { + fn quad(into: []?[3]f32, x0n: f32, y0n: f32, x1n: f32, y1n: f32, rgb: [3]f32, ww: f32, wh: f32, ox: u32, oy: u32, pw: u32, ph: u32) void { + const px0: i64 = @intFromFloat(@round((x0n + 1) / 2 * ww)); + const px1: i64 = @intFromFloat(@round((x1n + 1) / 2 * ww)); + const py0: i64 = @intFromFloat(@round((1 - y0n) / 2 * wh)); + const py1: i64 = @intFromFloat(@round((1 - y1n) / 2 * wh)); + var y = @max(py0, oy); + while (y < @min(py1, oy + ph)) : (y += 1) { + var x = @max(px0, ox); + while (x < @min(px1, ox + pw)) : (x += 1) into[@intCast((y - oy) * pw + (x - ox))] = rgb; + } + } + }; + var instances: [4]CellInstance = undefined; + for (0..grip.rect.h) |line| for (0..config.GUTTER) |dx| { + const col: u16 = grip.rect.x + @as(u16, @intCast(dx)); + const row: u16 = grip.rect.y + @as(u16, @intCast(line)); + const at = @as(usize, row) * s.cols; + var next: u32 = 0; + emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, bg_default); + for (instances[0..next]) |i| paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); + }; + for (g.decor.items) |i| if (i.fr >= 1 and i.clip_x1 < i.clip_x0) paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); + const rgb = struct { + fn of(v: [3]u8) [3]f32 { + return .{ @as(f32, @floatFromInt(v[0])) / 255, @as(f32, @floatFromInt(v[1])) / 255, @as(f32, @floatFromInt(v[2])) / 255 }; + } + }.of; + const chrome = &s.chrome; + const band = if (focus == 0) chrome.tag_focus_bg else chrome.tag_bg; + // Band, fills, rings, the rules between stacked panes and under the + // tag, and the mode marks' ink (the grip's first cell's). + const ink = inkOn(gripFill(chrome, grip.active, grip.dirty)); + const allowed = [_][3]f32{ rgb(band), rgb(core.chromeTheme().box), rgb(pardes.draw.boxDirty(core)), rgb(chrome.grip_border), rgb(chrome.grip_focus_ring), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)) }; + for (pixels, 0..) |pixel, n| { + const got = pixel orelse return error.TestUnpaintedGripPixel; + const known = for (allowed) |a| { + if (std.meta.eql(a, got)) break true; + } else false; + // Under the first row there is no button: band and rules only. + if (n / w_px >= m.h and n / w_px < h_px - 1 and !std.meta.eql(got, rgb(band)) and !std.meta.eql(got, rgb(chrome.border))) + return error.TestButtonUnderFirstRow; + if (!known) std.debug.print("sliver {any} at {d},{d} of {d}x{d} (metrics {d}x{d}/{d}, focus {d}, dirty {}) page {any}\n", .{ got, n % w_px, n / w_px, w_px, h_px, m.w, m.h, m.tag, focus, dirty, s.chrome.page }); + try std.testing.expect(known); + } + // The rule under the tag runs unbroken across the grip column. + for (pixels[(h_px - 1) * w_px ..][0..w_px]) |pixel| + try std.testing.expectEqual(rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)), pixel.?); + // The button's edges are the scrollbar's. + const button = gripButton(&g, chrome, grip.rect.x, grip.rect.y, layout); + const column = scrollColumn(&g, chrome, s.region(.rail, 0).?.rect.x, layout); + try std.testing.expectEqual(column[0], button[0]); + try std.testing.expectEqual(column[1], button[2]); + }; + pane.file.?.revision = pane.file.?.saved_revision; +} + +test "small tagline fonts leave no background gutters between adjacent tags" { + const chrome: pardes.Chrome = .{}; + var g = testGui(10, 20, 8, 16); + const cell: pardes.Cell = .{ .default = false, .style = .{ .font_role = .tagline } }; + var instances: [6]CellInstance = undefined; + var next: u32 = 0; + for (0..3) |row| { + // Column 1: past the anchor's inset edge at the column's left. + emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, bg_default); + const base = instances[row * 2]; + const ink = instances[row * 2 + 1]; + try std.testing.expectApproxEqAbs(@as(f32, 20.0 / 480.0 * 2), base.y0 - base.y1, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 16.0 / 480.0 * 2), ink.y0 - ink.y1, 0.0001); + try std.testing.expect(ink.y0 <= base.y0 and ink.y1 >= base.y1); + try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), ink.x1 - ink.x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 10) / atlas_w, ink.u1 - ink.u0, 0.0001); + if (row > 0) try std.testing.expectApproxEqAbs(instances[(row - 1) * 2].y1, base.y0, 0.0001); + } + // Column 0 is an anchor's edge: its ink is inset by the band's margin + // (2 px here) and its underlay still covers the whole cell. + next = 0; + emitSurfaceCell(&g, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, bg_default); + try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), instances[0].x1 - instances[0].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 8.0 / 800.0 * 2), instances[1].x1 - instances[1].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 8) / atlas_w, instances[1].u1 - instances[1].u0, 0.0001); +} + +test "block cursor alone overrides transparent cell background" { + var g = testGui(10, 20, 6, 12); + const cell: pardes.Cell = .{}; + var instances: [2]CellInstance = undefined; + for ([_]bool{ false, true }, 0..) |cursor, i| { + emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, bg_default); + try std.testing.expectEqual(cursor, instances[i].effect & opaque_bg_bit != 0); + } +} + +test "insert cursor overlays without replacing the character beneath it" { + const cell: pardes.Cell = .{ + .text = .{ 'x', ' ', ' ', ' ', ' ', ' ', ' ' }, + .len = 1, + .default = false, + }; + try std.testing.expectEqual(@as(u32, 'x'), cellCodepoint(&cell)); + + // A bar at a tag cell: tagline-tall, centered in its row, in the + // cell's ink, drawn as decor over it. + var cells: [25]pardes.Cell = @splat(.{}); + cells[3 * 5 + 2] = .{ .default = false, .style = .{ .fg = .{ .rgb = .{ 32, 48, 64 } }, .font_role = .tagline } }; + const surface: pardes.Surface = .{ .cols = 5, .rows = 5, .cells = &cells, .cursor = .{ .x = 2, .y = 3, .bar = true } }; + var g = testGui(10, 20, 8, 8); + defer g.decor.deinit(std.testing.allocator); + try cursorDecor(&g, std.testing.allocator, &surface, fixedCellLayout(&g), 100, 100); + try std.testing.expectEqual(@as(usize, 1), g.decor.items.len); + const bar = g.decor.items[0]; + try std.testing.expectApproxEqAbs(@as(f32, -0.32), bar.y0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, -0.48), bar.y1, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 32.0 / 255.0), bar.br, 0.0001); + try std.testing.expectEqual(@as(f32, 1), bar.fr); +} + +test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { + const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + defer std.testing.allocator.free(bytes); + var g = try textTestGui(bytes, 27); + defer font_allocator = std.heap.smp_allocator; + defer g.atlas.deinit(std.testing.allocator); + defer g.words.deinit(std.testing.allocator); + + const line = textTestLine("a->b"); + var slots: [4]Slot = undefined; + for (&slots, 0..) |*slot, i| slot.* = cellSlot(&g, &line, i, null, .body); + // `->` is one glyph strip two cells wide: each cell samples its own half. + try std.testing.expectEqual(slots[1].v, slots[2].v); + try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u); + var strips: usize = 0; + var it = g.atlas.glyphs.iterator(); + while (it.next()) |entry| if (entry.key_ptr.span == 2) { + strips += 1; + try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead); + try std.testing.expectEqual(slots[1], entry.value_ptr.*); + }; + try std.testing.expectEqual(@as(usize, 1), strips); + // The arrow runs through the seam: both halves carry ink at it. + const seam = g.atlas.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; + var left_ink: usize = 0; + var right_ink: usize = 0; + for (0..g.cell_h) |y| { + left_ink += seam[y * atlas_w + slots[2].u - 1]; + right_ink += seam[y * atlas_w + slots[2].u]; + } + try std.testing.expect(left_ink > 0 and right_ink > 0); + // `a` and `b` are their plain glyphs. + try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('a').glyph, .role = .body }).?, slots[0]); + try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('b').glyph, .role = .body }).?, slots[3]); + + // A second line with the same word reuses the shaped slots. + const again = textTestLine("a->b"); + const text_len = g.words.text.items.len; + for (0..4) |i| try std.testing.expectEqual(slots[i], cellSlot(&g, &again, i, null, .body)); + try std.testing.expectEqual(text_len, g.words.text.items.len); + + // The cursor on either half shows plain `-` and `>`. + const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('-').glyph, .role = .body }).?; + const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('>').glyph, .role = .body }).?; + for ([_]usize{ 1, 2 }) |cursor| { + try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body)); + try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body)); + } + // A tagline is never shaped. + try std.testing.expectEqual(g.atlas.glyphForCodepoint('-').glyph, (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); +} + +test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { + var g = try textTestGui(font_ttf, 18); + defer font_allocator = std.heap.smp_allocator; + defer g.atlas.deinit(std.testing.allocator); + defer g.words.deinit(std.testing.allocator); + // Each glyph as it is drawn unshaped, in an atlas of its own. + var plain = try textTestGui(font_ttf, 18); + defer plain.atlas.deinit(std.testing.allocator); + defer plain.words.deinit(std.testing.allocator); + const text = "a->b != c => d <= e |> www == :: 0x1F"; + var line = textTestLine(text); + line[3].style.bold = true; // a style change inside a word + for (line, 0..) |cell, i| { + if (text[i] == ' ') continue; + const slot = cellSlot(&g, &line, i, null, .body); + const key = try glyphKeyAt(&g, slot); + try std.testing.expectEqual(g.atlas.glyphForCodepoint(text[i]).glyph, key.glyph); + try std.testing.expectEqual(@as(u4, 1), key.span); + const expected = cachedGlyph(&plain, .{ .face = 0, .glyph = key.glyph, .role = .body, .decoration = .{ .bold = cell.style.bold } }).?; + for (0..g.cell_h) |y| + try std.testing.expectEqualSlices(u8, plain.atlas.atlas_stage[(expected.v + y) * atlas_w + expected.u ..][0..g.cell_w], g.atlas.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); + } +} + +test "pane indicator cached ink centers bearings styles and sizes" { + var g = testGui(10, 20, 6, 12); + g.atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer g.atlas.deinit(std.testing.allocator); + for ([_]f32{ 13, 27, 40 }) |px| { + g.px = px; + var cw: c_int = 0; + var ch: c_int = 0; + g.atlas.cellMetrics(px, &cw, &ch, &g.ascent); + g.cell_w = @intCast(cw); + g.cell_h = @intCast(ch); + for ([_]u8{ 40, 82, 100 }) |percent| { + const tag = taglineRaster(&g.atlas, px, g.cell_w, g.cell_h, percent); + g.tagline_width = tag.width; + g.tagline_height = tag.height; + g.tagline_px = tag.px; + g.tagline_baseline = tag.baseline; + resetGlyphAtlas(&g); + try std.testing.expectEqual(@as(usize, 0), g.atlas.glyphs.count()); + for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { + const key: GlyphKey = .{ .face = 0, .glyph = g.atlas.glyphForCodepoint(cp).glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; + const slot = cachedGlyph(&g, key).?; + const bounds = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; + const center_x: isize = @intCast(bounds.min_x + bounds.max_x); + const center_y: isize = @intCast(bounds.min_y + bounds.max_y); + try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1); + try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1); + const count = g.atlas.glyphs.count(); + const pen = g.atlas.pen_x; + try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); + try std.testing.expectEqual(count, g.atlas.glyphs.count()); + try std.testing.expectEqual(pen, g.atlas.pen_x); + }; + } + } + resetGlyphAtlas(&g); + g.atlas.pen_y = atlas_h; + try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('^').glyph, .role = .tagline, .centered = true })); +} + +test "pane indicator halves are safe on an exhausted atlas" { + var cells: [12]pardes.Cell = @splat(.{ .default = false, .style = .{ .font_role = .tagline } }); + cells[0].text[0] = '$'; + // A grip two cells wide at the top left. + const grip = [_]pardes.Region{.{ .kind = .grip, .serial = 1, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}; + var cover: [12]Cover = undefined; + coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); + try std.testing.expect(cover[0].grip and cover[1].grip and !cover[2].grip); + // A column's grip is a button too, cut the same way (it has no glyph). + coverFrame(&cover, 6, 2, &.{}, &.{}, &.{.{ .kind = .column_grip, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}); + try std.testing.expect(cover[0].grip); + coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); + const chrome: pardes.Chrome = .{}; + + var g = testGui(10, 20, 8, 16); + g.atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer g.atlas.deinit(std.testing.allocator); + g.px = 20; + g.tagline_px = 16; + g.atlas.pen_y = atlas_h; + defer g.words.deinit(std.testing.allocator); + var instances: [4]CellInstance = undefined; + var next: u32 = 0; + for (0..2) |col| { + emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); + try std.testing.expectEqual(@as(f32, 0), instances[col * 2 + 1].u0); + } + try std.testing.expectEqual(@as(u32, 4), next); +} + +test "a concealed cell's underline draws nothing of its own" { + const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; + try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); +} + +test "overlapping background layers keep one uniform opacity" { + const blend = Cells.backgroundLayerBlend(); + try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); + try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor); + for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| { + var alpha = opacity; + for ([_]f32{ 1, 0.5, 0.88, 0, 1 }) |coverage| { + alpha = opacity * coverage + alpha * (1 - coverage); + try std.testing.expectApproxEqAbs(opacity, alpha, 0.00001); + } + } +} + +test "background opacity retains exact endpoints and percentage precision" { + try std.testing.expectEqual(@as(f32, 0), backgroundOpacity(0)); + try std.testing.expectEqual(@as(f32, 0.7), backgroundOpacity(70)); + try std.testing.expectEqual(@as(f32, 1), backgroundOpacity(100)); + for (0..100) |percent| { + try std.testing.expect(backgroundOpacity(@intCast(percent)) < backgroundOpacity(@intCast(percent + 1))); + } +} + +test "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + core.sync(); + const s = try core.render(core.scratch.allocator()); + defer dim = .{}; + dim.begin(60, s.regionList()); + try std.testing.expect(dim.focused != pardes.Region.none); + var cover: [80 * 24]Cover = undefined; + coverFrame(&cover, 80, 24, &.{}, &.{}, s.regionList()); + var seen: [2]bool = .{ false, false }; + for (s.regionList()) |region| if (region.kind == .body or region.kind == .tag) { + const unfocused = region.owner != dim.focused; + try std.testing.expectEqual(unfocused, cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); + seen[@intFromBool(unfocused)] = true; + } else if (region.kind == .grip) try std.testing.expect(!cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); + try std.testing.expect(seen[0] and seen[1]); + // Toward the ground, a pair already near its floor no further. + var instance: CellInstance = std.mem.zeroes(CellInstance); + instance.fr = 0.9; + instance.fg = 0.9; + instance.fb = 0.9; + dim.fade(&instance); + try std.testing.expect(instance.fr < 0.9 and instance.fr > 0); + try std.testing.expect(pardes.colors.contrast(Dim.byteRgb(.{ instance.fr, instance.fg, instance.fb }), .{ 0, 0, 0 }) >= 4.5 - 1e-3); + // Off, nothing fades. + dim.begin(0, s.regionList()); + try std.testing.expect(!dim.of(0) and !dim.of(1)); +} + +test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px black rules and 12px track" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); + for (0..40) |_| core.update(.tick); + core.sync(); + const s = try core.render(core.scratch.allocator()); + try std.testing.expectEqual(@as(u8, 2), s.chrome.rule_px); + // acme's 12px, at GripWidth's 150% default. + try std.testing.expectEqual(@as(u8, 18), s.chrome.rail_px); + var g = testGui(16, 20, 10, 12); + defer g.decor.deinit(gpa); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 480, true); + const px = struct { + fn w(item: CellInstance) f32 { + return (item.x1 - item.x0) / 2 * 1280; + } + }; + var spines: usize = 0; + var tracks: usize = 0; + for (g.decor.items) |item| { + const black = item.br == 0 and item.bg == 0 and item.bb == 0; + // No rule at the window's left edge; one 2px spine where columns meet. + if (black and @abs(px.w(item) - 2) < 0.01 and item.y1 < -0.9) { + try std.testing.expect(item.x0 > -1); + spines += 1; + } + const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); + if (@abs(item.br - @as(f32, 0x99) / 255) < 1e-3 and @abs(item.bb - @as(f32, 0x4c) / 255) < 1e-3 and @abs(px.w(item) - (column[1] - column[0])) < 0.01) tracks += 1; + } + try std.testing.expectEqual(@as(usize, 1), spines); + try std.testing.expect(tracks >= 2); +} + +test "the scrollbar thumb moves by the pixel and follows a glide" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + const thumb = struct { + // The thumb's top, in window pixels. + fn top(gui: *Gui, p: *pardes.Pardes) !f32 { + gui.decor.clearRetainingCapacity(); + p.sync(); + const s = try p.render(p.scratch.allocator()); + var groups: Groups = .{}; + try buildDecor(gui, std.testing.allocator, s, &groups, fixedCellLayout(gui), 800, 480, true); + const ink = s.chrome.scroll_thumb; + for (gui.decor.items) |item| if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and + @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and + @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) return (1 - item.y0) / 2 * 480; + return error.TestExpectedThumb; + } + }; + pane.file.?.scroll = 10; + const at10 = try thumb.top(&g, core); + pane.file.?.scroll = 11; + const at11 = try thumb.top(&g, core); + // A line of a thousand moves it a fraction of a row, not 0 or 20 px. + try std.testing.expect(at11 > at10 and at11 - at10 < 1); + g.glide.pane = core.view().active; + g.glide.follow.offset = -1; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); + // A wrapped line: the picture moved two rows for the one line, and the + // thumb lags the line, not two. + g.glide.lines_moved = 1; + g.glide.rows_moved = 2; + g.glide.follow.offset = -2; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); +} + +test "the scrollbar thumb lies in its scroll column, a pixel short of the column's right edge, so the track edges it" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + core.sync(); + const s = try core.render(core.scratch.allocator()); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); + const ink = s.chrome.scroll_thumb; + const thumb = for (g.decor.items) |item| { + if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and + @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and + @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) break item; + } else return error.TestExpectedThumb; + // The pane is the window's first: its scroll column is at cell 0. + const column = scrollColumn(&g, &s.chrome, 0, fixedCellLayout(&g)); + try std.testing.expectApproxEqAbs(column[0], (thumb.x0 + 1) / 2 * 800, 1e-3); + try std.testing.expectApproxEqAbs(column[1] - 1, (thumb.x1 + 1) / 2 * 800, 1e-3); +} + +test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + core.newScratchBelow(0); + core.sync(); + const s = try core.render(core.scratch.allocator()); + const lower = for (s.regionList()) |region| { + if (region.kind == .tag and region.rect.y > 2) break region; + } else return error.TestExpectedStackedTag; + for ([_]u32{ 12, 20 }) |tagline_h| { + var g = testGui(10, 20, 6, tagline_h); + defer g.decor.deinit(gpa); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); + const top = @as(f32, @floatFromInt(lower.rect.y)) * 20; + const slack: f32 = @floatFromInt(@max(1, pardes.Layer.taglineBandOffset(lower.rect.y, 480, 20, tagline_h))); + var found = false; + for (g.decor.items) |item| { + const y0 = (1 - item.y0) / 2 * 480; + const y1 = (1 - item.y1) / 2 * 480; + if (@abs(y0 - top) > 0.01 or @abs(item.br - @as(f32, @floatFromInt(s.chrome.border[0])) / 255) > 1e-3) continue; + found = true; + try std.testing.expect(y1 - y0 <= slack + 0.01); + } + try std.testing.expect(found); + } +} + +test "an empty column is ruled on both sides, as between two filled ones" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + // Newcol from the left pane: an empty column between the two filled ones. + pardes.layout.newColumn(core, 0); + core.sync(); + try std.testing.expectEqual(@as(usize, 3), core.view().ncol); + try std.testing.expectEqual(@as(usize, 0), core.view().cols[1].n); + const s = try core.render(core.scratch.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + const layout = fixedCellLayout(&g); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); + const border = [3]f32{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 }; + // Its left edge and its right edge (the next column's left): each a + // rule `rule_px` wide in the border colour, down to the window's foot. + for ([_]usize{ 1, 2 }) |column| { + const px: f32 = @floatFromInt(@as(u32, core.view().col_x[column]) * 10); + const rule = for (g.decor.items) |item| { + if (@abs(item.x0 - (px / 800 * 2 - 1)) < 1e-4 and @abs(item.x1 - ((px + @as(f32, @floatFromInt(s.chrome.rule_px))) / 800 * 2 - 1)) < 1e-4 and + std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &border)) break item; + } else return error.TestExpectedColumnRule; + try std.testing.expectEqual(@as(f32, -1), rule.y1); + } +} + +test "at a 2x display every logical pixel is two: rules, the tag rule, the grip's ring, the rail's edge" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); + for (0..40) |_| core.update(.tick); + core.sync(); + const s = try core.render(core.scratch.allocator()); + for ([_]f32{ 1, 2 }) |scale| { + display_scale = scale; + defer display_scale = 1; + var g = testGui(16, 32, 12, 24); + defer g.decor.deinit(gpa); + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 768, true); + const w = struct { + fn of(item: CellInstance) f32 { + return (item.x1 - item.x0) / 2 * 1280; + } + fn h(item: CellInstance) f32 { + return (item.y0 - item.y1) / 2 * 768; + } + }; + var spine: ?f32 = null; + var tag_rule: ?f32 = null; + var ring: ?f32 = null; + for (g.decor.items) |item| { + const rgb: [3]u8 = .{ @intFromFloat(@round(item.br * 255)), @intFromFloat(@round(item.bg * 255)), @intFromFloat(@round(item.bb * 255)) }; + // The spine between the columns: black, tall. + if (std.mem.eql(u8, &rgb, &.{ 0, 0, 0 }) and w.h(item) > 300) spine = @round(w.of(item)); + // The tag rule: #8888cc, wide and thin. + if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.of(item) > 200) tag_rule = @round(w.h(item)); + // The ring's left side: #8888cc, a tag row tall. + if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.h(item) > 10 and w.of(item) < 8) ring = @round(w.of(item)); + } + try std.testing.expectEqual(@as(?f32, 2 * scale), spine); + try std.testing.expectEqual(@as(?f32, 1 * scale), tag_rule); + try std.testing.expectEqual(@as(?f32, 2 * scale), ring); + // The rail starts after the rule, a logical 2 in, and keeps a + // logical 3 clear of the text when the cell is narrow. + const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); + try std.testing.expectEqual(40 * 16 + 2 * scale, column[0]); + g.cell_w = 12; + defer g.cell_w = 16; + const narrow = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); + try std.testing.expectEqual(@as(f32, 40 * 12 + 2 * scale), narrow[0]); + try std.testing.expectEqual(@as(f32, 40 * 12) + 12 * @as(f32, @floatFromInt(config.GUTTER)) - 3 * scale, narrow[1]); + g.cell_w = 8; + // A bar cursor is an eighth of its cell, never under a logical pixel + // (an 8 px cell: one pixel, two at 2x). + const saved = s.cursor; + defer s.cursor = saved; + s.cursor = .{ .x = 60, .y = 10, .bar = true }; + var boxes: [max_cursors]CursorBox = undefined; + const n = cursorBoxes(&g, s, fixedCellLayout(&g), 768, &boxes); + const bar = for (boxes[0..n]) |box| { + if (box.bar and box.x0 == 60 * 8) break box; + } else return error.NoBarCursor; + try std.testing.expectEqual(scale, bar.x1 - bar.x0); + } +} + +test "decor is read from the regions" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + _ = try core.newShell(1, ""); + try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); + core.sync(); + const s = try core.render(core.scratch.allocator()); + var g = testGui(10, 20, 6, 12); + defer g.decor.deinit(gpa); + const layout = fixedCellLayout(&g); + const ndc = struct { + fn x(px: f32) f32 { + return px / 800 * 2 - 1; + } + }; + var groups: Groups = .{}; + try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); + // A spine one pixel wide at each column's left edge, down from under the + // workspace tag; a rail two pixels wide at each pane's. + for (core.view().col_x[0..core.view().ncol]) |x| { + const left = ndc.x(@as(f32, @floatFromInt(x)) * 10); + // Two pixels (rule_px), and none at the window's own edge. + const spine = for (g.decor.items) |item| { + if (item.x0 == left and @abs(item.x1 - ndc.x(@as(f32, @floatFromInt(x)) * 10 + 2)) < 0.0001 and + @abs(item.y0 - (1 - 20.0 / 480.0 * 2)) < 0.0001 and std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &.{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 })) break item; + } else null; + try std.testing.expectEqual(x == 0, spine == null); + if (spine) |rule| { + try std.testing.expectApproxEqAbs(@as(f32, 1 - 20.0 / 480.0 * 2), rule.y0, 0.0001); + try std.testing.expectEqual(@as(f32, -1), rule.y1); + } + // The scrollbar fills the scroll column right of the rule. + const column = scrollColumn(&g, &s.chrome, x, layout); + const rail = for (g.decor.items) |item| { + if (@abs(item.x0 - ndc.x(column[0])) < 0.0001 and @abs(item.x1 - ndc.x(column[1])) < 0.0001 and + @abs(item.br - @as(f32, @floatFromInt(s.chrome.scroll_track[0])) / 255) < 0.0001) break item; + } else return error.TestExpectedRail; + _ = rail; + } + try std.testing.expectEqual(@as(u32, 0), groups.items[groups.notices].decor_count); +} + +test "a body tells its first line" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); + defer core.deinit(); + const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); + pane.scrollBy(8); + core.sync(); + const s = try core.render(core.scratch.allocator()); + const body = for (s.regionList()) |region| { + if (region.kind == .body) break region; + } else return error.NoBody; + try std.testing.expectEqual(@as(i32, 8), body.line); +} + +test "a caret eases a cell at a time, keeps up with typing, and glides a jump, landing exactly" { + const ms = std.time.ns_per_ms; + var caret: Caret = .{}; + caret.aim(.{ .x = 3, .y = 4, .w = 1, .h = 1 }, 0, false); + // The first mark lands at once. + try std.testing.expect(!caret.moving()); + // A step eases, a stream of them keeps up. + caret.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, 1000 * ms, false); + try std.testing.expect(caret.moving()); + caret.aim(.{ .x = 5, .y = 4, .w = 1, .h = 1 }, 1050 * ms, false); + try std.testing.expect(!caret.moving()); + // A jump glides, the leading corner ahead, and lands exactly. + caret.aim(.{ .x = 30, .y = 10, .w = 1, .h = 1 }, 2000 * ms, false); + try std.testing.expect(caret.moving()); + const mid = caret.sample(2040 * ms); + try std.testing.expect(mid[1][0] > mid[0][0] - 1 and mid[0][0] > 5 and mid[0][0] < 30); + var t: u64 = 2040 * ms; + while (caret.step(t)) t += 16 * ms; + try std.testing.expect(t < 2400 * ms); + try std.testing.expectEqual([2]f32{ 30, 10 }, caret.sample(t)[0]); + // A scroll lands it with its text. + caret.see(.{ .x = 30, .y = 8, .w = 1, .h = 1 }, 0, 10, 2, 1, t); + caret.see(.{ .x = 30, .y = 6, .w = 1, .h = 1 }, 0, 12, 2, 1, t + 16 * ms); + try std.testing.expect(!caret.moving()); +} + +test "a jump's trail is drawn behind the cursor in its body, and gone by 120 ms" { + var cells: [80 * 4]pardes.Cell = @splat(.{}); + var surface: pardes.Surface = .{ .cols = 80, .rows = 4, .cells = &cells }; + surface.regions[0] = .{ .kind = .body, .rect = .{ .x = 2, .y = 0, .w = 78, .h = 4 } }; + surface.nregions = 1; + var g = testGui(10, 20, 8, 16); + var vertices: [5 * 6]OverlayVertex = undefined; + var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 80 }; + const ms = std.time.ns_per_ms; + surface.cursor = .{ .x = 4, .y = 1 }; + appendJumpTrail(&g, true, &surface, 1000 * ms, &builder); + try std.testing.expectEqual(@as(usize, 0), builder.len); + surface.cursor = .{ .x = 14, .y = 1 }; + appendJumpTrail(&g, true, &surface, 1016 * ms, &builder); + try std.testing.expect(builder.len >= 3 * 6 and builder.len <= 5 * 6); + // On the cursor's row, behind it, never its own cell. + for (vertices[0..builder.len]) |v| { + const x = (v.x + 1) * 400; + const y = (1 - v.y) * 40; + try std.testing.expect(y >= 20 - 0.01 and y <= 40 + 0.01); + try std.testing.expect(x >= 50 - 0.01 and x <= 140 + 0.01); + } + try std.testing.expect(g.trail.active); + builder.len = 0; + appendJumpTrail(&g, true, &surface, 1150 * ms, &builder); + try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expect(!g.trail.active); +} + +test "a pet stays past the workspace tag's text, and off it is gone" { + std.testing.refAllDecls(pet); + var cells: [80]pardes.Cell = @splat(.{}); + const surface: pardes.Surface = .{ .cols = 80, .rows = 1, .cells = &cells }; + for ("Workspace Commands", 0..) |ch, i| { + cells[i].text[0] = ch; + cells[i].len = 1; + cells[i].default = false; + } + var g = testGui(10, 20, 8, 16); + var vertices: [pet.max_vertices]OverlayVertex = undefined; + var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 480 }; + appendWorkspacePet(&g, .cat, &surface, &builder); + try std.testing.expect(builder.len > 0); + for (vertices[0..builder.len]) |v| { + const x = (v.x + 1) * 400; + const y = (1 - v.y) * 240; + try std.testing.expect(x >= 20 * 8 - 0.01); + try std.testing.expect(y >= 0 and y < 20); + } + builder.len = 0; + appendWorkspacePet(&g, .off, &surface, &builder); + try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expectEqual(@as(?u64, null), g.pet_state.tick); +} + +test "compact body layer rendering fills recovered rows and clips the final glyph" { + var g = testGui(10, 20, 6, 12); + var cells: [24]pardes.Cell = @splat(.{}); + var layer: pardes.Layer = .{ + .viewport = .{ .x = 3, .y = 2, .w = 2, .h = 5 }, + .cols = 2, + .rows = 12, + .context_rows = 4, + .cells = &cells, + }; + layer.setContextLines(&.{ 0, 4, 5, 6 }); + var instances: [32]CellInstance = undefined; + var next: u32 = 0; + emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); + // Four compact header rows (48px), then three body rows: two complete + // and a third clipped to the remaining12px of the100px viewport. + try std.testing.expectEqual(@as(u32, 20), next); + try std.testing.expectApproxEqAbs(@as(f32, 0.49), instances[3].y0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 0.48), instances[3].y1, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 80.0 / 255.0), instances[3].br, 0.0001); + try std.testing.expectApproxEqAbs(instances[3].br, instances[13].br, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 0.6), instances[0].y0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 0.12), instances[14].y0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, -0.4), instances[19].y1, 0.0001); + try std.testing.expectApproxEqAbs(instances[19].v0 + @as(f32, 12) / atlas_h, instances[19].v1, 0.0001); + // A drag preview reserves the last physical column without changing cells. + layer.viewport.w = 1; + next = 0; + emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); + for (instances[0..next]) |instance| try std.testing.expect(instance.x1 <= -0.6 + 0.0001); +} + +test "compact tag layers fill available width and clip at their physical edge" { + var g = testGui(10, 20, 6, 12); + var cells: [6]pardes.Cell = @splat(.{}); + const layer: pardes.Layer = .{ .kind = .pane, .id = 0, .serial = 7, .viewport = .{ .x = 2, .y = 3, .w = 3, .h = 1 }, .cols = 6, .rows = 1, .cells = &cells, .bg = .{ 20, 30, 40 } }; + var instances: [8]CellInstance = undefined; + var next: u32 = 0; + emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); + // Five six-pixel cells fit in the three body-column viewport. + try std.testing.expectEqual(@as(u32, 6), next); + try std.testing.expectApproxEqAbs(@as(f32, -0.6), instances[1].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 0), instances[5].x1, 0.0001); + g.tagline_width = 8; + next = 0; + emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); + try std.testing.expectEqual(@as(u32, 5), next); + try std.testing.expectApproxEqAbs(@as(f32, 0), instances[4].x1, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 6) / atlas_w, instances[4].u1 - instances[4].u0, 0.0001); +} + +test "trackpad rotation never types search keys into an insert-mode file or raw terminal" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); + defer core.deinit(); + _ = try core.setTestFile("unchanged\n"); + var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; + defer client.deinit(); + var in: Input = .{ .core = core, .client = &client }; + var g: Gui = undefined; + g.trackpad = .{}; + var ev: c.UITrackpadEvent = std.mem.zeroes(c.UITrackpadEvent); + ev.kind = c.UI_TRACKPAD_ROTATE; + ev.a = 20; + const pane = core.panes[core.view().active].?; + pane.body.mode = .insert; + dispatchTrackpad(&g, &in, &ev); + pane.body.mode = .tty; + dispatchTrackpad(&g, &in, &ev); + try std.testing.expectEqual(@as(usize, 0), client.pending.items.len); + ev.kind = c.UI_TRACKPAD_HISTORY; + ev.a = -1; + dispatchTrackpad(&g, &in, &ev); + ev.a = 1; + dispatchTrackpad(&g, &in, &ev); + try std.testing.expectEqual(@as(usize, 2), client.pending.items.len); + try std.testing.expectEqualStrings("Back", client.pending.items[0].command); + try std.testing.expectEqualStrings("Forward", client.pending.items[1].command); +} + +test "a detached GUI authority follows terminal directory changes with no window" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "child"); + var start_buf: [4096]u8 = undefined; + const start = start_buf[0..try tmp.dir.realPath(io, &start_buf)]; + var cwd_buf: [4096]u8 = undefined; + const expected = cwd_buf[0..try tmp.dir.realPathFile(io, "child", &cwd_buf)]; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.shell_spoke = true; + _ = core.settings.shell.effective.set("/bin/sh"); + var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + const rcs: host_io.Shell.PromptFiles = .{}; + var pipes: PipeTasks = .{}; + var watches: file_watch.Table = @splat(null); + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches }; + defer shell.shutdownPtys(); + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); + const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000; + var actual: [4096]u8 = undefined; + while (std.Io.Clock.awake.now(io).toMilliseconds() < until) { + if (host_io.shellCwd(child.pid, &actual)) |cwd| if (std.mem.eql(u8, cwd, expected)) break; + try io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expectEqualStrings(expected, host_io.shellCwd(child.pid, &actual) orelse return error.MissingCwd); + pollFrame(&shell); + try std.testing.expectEqualStrings(expected, core.panes[0].?.cwd.owned); +} + +test "detached trackpad scrolling keeps fractions local and queues whole rows for replication" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); + defer core.deinit(); + _ = try core.setTestFile("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\nsixteen\nseventeen\neighteen\nnineteen\ntwenty\n"); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try core.render(arena.allocator()); + var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; + defer client.deinit(); + var in: Input = .{ .core = core, .client = &client }; + const id = core.view().active; + const r = core.view().rects[id]; + var g: Gui = undefined; + g.scroll_pane = id; + g.scroll_delta = 0.375; + g.scroll_lag = 0; + g.scroll_idle = 0; + g.scroll_notch = 0; + g.scroll_edge = &.{}; + g.scroll_edge_len = 0; + g.glide = .{}; + g.scroll_col = r.x + config.GUTTER + 2; + g.scroll_row = core.bodyTop(core.panes[id].?, r) + 2; + defer gpa.free(g.scroll_edge); + const before = core.panes[id].?.scroll(); + try std.testing.expect(scrollRows(&g, &in, gpa)); + try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); + // The next row is fetched early; its inverse raster offset keeps the + // exact fraction under the finger until that row is fully shown. + try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(client.pending.items.len)) + g.scroll_lag); + try std.testing.expectEqual(before, core.panes[id].?.scroll()); + core.update(client.pending.items[0]); + client.pending.clearRetainingCapacity(); + g.scroll_delta = 0.75; + try std.testing.expect(scrollRows(&g, &in, gpa)); + try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); + try std.testing.expectEqual(before + 1, core.panes[id].?.scroll()); + try std.testing.expect(client.pending.items[0].mouse.shift); + core.update(client.pending.items[0]); + try std.testing.expectEqual(@as(f32, 1.125), @as(f32, @floatFromInt(core.panes[id].?.scroll() - before)) + g.scroll_lag); +} + +/// Render addon scenes to textures on this device, before the page's pass. +/// The fallback cells remain visible if decoding or pipeline creation fails. +fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, surface: *const pardes.Surface) void { + for (surface.gpu_frames, 0..) |maybe, id| { + const scratch: GpuScene.abi.Image = @fromBackingInt(@intCast(pardes.MAX_PANES + id + 1)); + const frame = maybe orelse { + if (g.addon_gpu) |*gpu| { + gpu.forget(@fromBackingInt(@intCast(id + 1))); + gpu.forget(scratch); + } + g.addon_hash[id] = 0; + g.addon_serial[id] = 0; + g.addon_failed[id] = 0; + continue; + }; + const hash = std.hash.Wyhash.hash(frame.serial, frame.bytes); + if (g.addon_failed[id] == hash) continue; + if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.cells.device); + const gpu = &g.addon_gpu.?; + const target: GpuScene.abi.Image = @fromBackingInt(@intCast(id + 1)); + if (g.addon_hash[id] != hash or g.addon_serial[id] != frame.serial) { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var scene = GpuScene.decodeFrame(arena.allocator(), frame.bytes) catch |err| { + log.warn("addon GPU scene: {t}", .{err}); + g.addon_failed[id] = hash; + continue; + }; + scene.pass.image = if (scene.post != null) scratch else target; + gpu.record(cmd, scene.pass) catch |err| { + log.warn("addon GPU render: {t}", .{err}); + g.addon_failed[id] = hash; + continue; + }; + if (scene.post) |post| { + gpu.postProcess(cmd, scratch, target, post) catch |err| { + log.warn("addon GPU postprocess: {t}", .{err}); + g.addon_failed[id] = hash; + continue; + }; + } else gpu.forget(scratch); + g.addon_hash[id] = hash; + g.addon_serial[id] = frame.serial; + } + const out = gpu.output(target) orelse continue; + g.cells.makeAddonPipeline() catch continue; + g.prepared_images.append(gpa, .{ + .premultiplied = true, + .texture = out.texture, + .place = .{ .pane = @intCast(id), .raster = .{ .ptr = undefined, .w = out.width, .h = out.height, .stride = out.width * 4 }, .src = .{ .x = 0, .y = 0, .w = out.width, .h = out.height }, .dst = frame.dst, .key = hash }, + }) catch {}; + } + if (g.addon_gpu) |*gpu| gpu.endFrame(); +} + +test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes to the recorded stage and slots" { + // The glyph atlas the frames sample, byte for byte and on any machine: + // FreeType and HarfBuzz are the build's, the faces the repo's (the + // embedded Adwaita Mono, assets/MapleMono-NF for ligatures and Nerd + // icons). CJK has no face of the repo's and no fallback of pardes's + // list: the frame corpus draws its .notdef. Recorded before the GPU + // move (.scratch/sketch/briefs/gpu-s0.md); a change here is a change + // to every frame. + const want = [2][2]u64{ .{ 0xa03053f14e2c5472, 0x9029886b638b07d5 }, .{ 0xcbaa53a0103aaff5, 0x7563d69768f7d867 } }; + const maple = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + defer std.testing.allocator.free(maple); + defer display_scale = 1; + var got: [2][2]u64 = undefined; + for ([_]f32{ 27, 54 }, [_]f32{ 1, 2 }, &got) |px, scale, *hashes| { + display_scale = scale; + var stage_hash = std.hash.Wyhash.init(0); + var slots_hash = std.hash.Wyhash.init(0); + // 0: Adwaita Mono, Maple its fallback; 1: Maple, whose ligatures shape. + for ([_][]const u8{ font_ttf, maple }) |primary| { + var g = try textTestGui(primary, px); + defer font_allocator = std.heap.smp_allocator; + defer g.atlas.deinit(std.testing.allocator); + defer g.words.deinit(std.testing.allocator); + try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false)); + try std.testing.expect(fitTaglineFont(&g, 80)); + const decorations = [_]Atlas.Decoration{ + .{}, + .{ .bold = true }, + .{ .underline = .single }, + .{ .underline = .double }, + .{ .underline = .curly }, + .{ .underline = .dotted }, + .{ .underline = .dashed }, + .{ .strikethrough = true }, + }; + for (0x21..0x7f) |cp| { + const drawn = g.atlas.glyphForCodepoint(@intCast(cp)); + for (decorations) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body, .decoration = decoration }) orelse return error.AtlasFull; + for (decorations[0..2]) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = decoration }) orelse return error.AtlasFull; + } + const space = g.atlas.glyphForCodepoint(' '); + _ = cachedGlyph(&g, .{ .face = space.face, .glyph = space.glyph, .role = .body, .decoration = .{ .underline = .single } }) orelse return error.AtlasFull; + for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]Atlas.Role{ .body, .tagline }) |role| { + _ = cachedGlyph(&g, .{ .face = 0, .glyph = cp, .role = role, .rule = true }) orelse return error.AtlasFull; + }; + for ([_]u32{ '$', '^', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { + const drawn = g.atlas.glyphForCodepoint(cp); + _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }) orelse return error.AtlasFull; + }; + // Nerd icons (Yazi's folder, a file, powerline's arrow): Maple's, + // the primary's or the fallback's. + for ([_]u32{ 0xe5ff, 0xf07b, 0xe0b0 }) |cp| { + const drawn = g.atlas.glyphForCodepoint(cp); + try std.testing.expect(drawn.glyph != 0); + _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body }) orelse return error.AtlasFull; + } + // Ligature strips, shaped by the words' cache as a frame shapes them. + const line = textTestLine("a->b => != <= >= == === !== |> <| :: ++ -- www office"); + for (0..line.len) |i| _ = cellSlot(&g, &line, i, null, .body); + stage_hash.update(g.atlas.atlas_stage); + const Entry = struct { key: u64, u: u32, v: u32 }; + var entries: std.ArrayList(Entry) = .empty; + defer entries.deinit(std.testing.allocator); + var it = g.atlas.glyphs.iterator(); + while (it.next()) |e| try entries.append(std.testing.allocator, .{ .key = @bitCast(e.key_ptr.*), .u = e.value_ptr.u, .v = e.value_ptr.v }); + std.mem.sort(Entry, entries.items, {}, struct { + fn less(_: void, x: Entry, y: Entry) bool { + return x.key < y.key; + } + }.less); + for (entries.items) |e| slots_hash.update(std.mem.asBytes(&e)); + } + hashes.* = .{ stage_hash.final(), slots_hash.final() }; + } + if (!std.meta.eql(want, got)) std.debug.print("atlas hashes: .{{ .{{ 0x{x}, 0x{x} }}, .{{ 0x{x}, 0x{x} }} }}\n", .{ got[0][0], got[0][1], got[1][0], got[1][1] }); + try std.testing.expectEqual(want, got); +} diff --git a/dev/gui/macos_trackpad.h b/dev/gui/macos_trackpad.h new file mode 100644 index 00000000..f5266084 --- /dev/null +++ b/dev/gui/macos_trackpad.h @@ -0,0 +1,21 @@ +#ifndef PARDES_MACOS_TRACKPAD_H +#define PARDES_MACOS_TRACKPAD_H +#include + +enum { UI_TRACKPAD_FINGERS = 1, UI_TRACKPAD_PRESSURE, UI_TRACKPAD_ROTATE, + UI_TRACKPAD_PINCH, UI_TRACKPAD_SCROLL, UI_TRACKPAD_HISTORY }; +/* Same prefix as SDL_UserEvent; the rest lives inside SDL_Event's storage. */ +typedef struct { + Uint32 type, reserved; + Uint64 timestamp; + SDL_WindowID windowID; + int kind; + float x, y, a, b; + Uint32 phase; + int fingers; +} UITrackpadEvent; + +Uint32 ui_macos_trackpad_event_type(void); +void ui_macos_trackpad_attach(SDL_Window *window); +void ui_macos_trackpad_haptic(void); +#endif diff --git a/dev/gui/macos_trackpad.m b/dev/gui/macos_trackpad.m new file mode 100644 index 00000000..64806b9e --- /dev/null +++ b/dev/gui/macos_trackpad.m @@ -0,0 +1,176 @@ +/* AppKit input missing from SDL's public event stream. The SDL view keeps its + * drawing, keyboard and mouse responder chain; only trackpad methods change. */ +#import +#import +#include "macos_trackpad.h" +#include +#include + +static char window_key; +static char swipe_key, axis_key, suppress_momentum_key; +static Uint32 gesture_type; +static Class trackpad_class; +_Static_assert(sizeof(UITrackpadEvent) <= sizeof(SDL_Event), "trackpad event fits SDL"); + +Uint32 ui_macos_trackpad_event_type(void) { return gesture_type; } + +void ui_macos_trackpad_haptic(void) +{ + [[NSHapticFeedbackManager defaultPerformer] + performFeedbackPattern:NSHapticFeedbackPatternAlignment + performanceTime:NSHapticFeedbackPerformanceTimeNow]; +} + +static void send_gesture(NSView *view, NSEvent *event, int kind, float a, float b, int fingers) +{ + SDL_Window *window = (SDL_Window *)[objc_getAssociatedObject(view, &window_key) pointerValue]; + if (!window) return; + NSPoint point = [view convertPoint:event.locationInWindow fromView:nil]; + SDL_Event packet = {0}; + UITrackpadEvent decoded = {0}; + UITrackpadEvent *out = &decoded; + out->type = gesture_type; + out->timestamp = SDL_GetTicksNS(); + out->windowID = SDL_GetWindowID(window); + out->kind = kind; + out->x = point.x; + out->y = view.isFlipped ? point.y : NSHeight(view.bounds) - point.y; + out->a = a; + out->b = b; + out->fingers = fingers; + /* Stable decoded phases, independent of NSEventPhase's bit values. */ + if (kind == UI_TRACKPAD_ROTATE || kind == UI_TRACKPAD_PINCH || kind == UI_TRACKPAD_SCROLL) + out->phase = event.phase == NSEventPhaseBegan ? 1 : + event.phase == NSEventPhaseEnded ? 2 : + event.phase == NSEventPhaseCancelled ? 3 : 0; + memcpy(&packet, &decoded, sizeof(decoded)); + SDL_PushEvent(&packet); +} + +static void touches(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_FINGERS, 0, 0, + (int)[event touchesMatchingPhase:NSTouchPhaseTouching inView:nil].count); + /* Do not also emit SDL's absolute finger coordinates: those describe the + * trackpad surface, not a position inside this window. Scroll comes from + * scrollWheel:, including the system's momentum events. */ +} + +static void pressure(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_PRESSURE, event.stage, 0, 0); +} + +static void rotate(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_ROTATE, event.rotation, 0, 0); +} + +static void magnify(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_PINCH, 1 + event.magnification, 0, 0); +} + +static void swipe(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + /* NSEvent swipe deltaX: negative is right/back, positive left/forward. */ + if (event.deltaX != 0) + send_gesture(view, event, UI_TRACKPAD_HISTORY, event.deltaX, 0, 0); +} + +static void scroll(NSView *view, SEL selector, NSEvent *event) +{ + if (event.hasPreciseScrollingDeltas) { + if (event.phase == NSEventPhaseBegan) { + objc_setAssociatedObject(view, &axis_key, @0, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(view, &suppress_momentum_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + if ([objc_getAssociatedObject(view, &swipe_key) boolValue]) return; + if ([objc_getAssociatedObject(view, &suppress_momentum_key) boolValue]) return; + NSInteger axis = [objc_getAssociatedObject(view, &axis_key) integerValue]; + CGFloat x = fabs(event.scrollingDeltaX), y = fabs(event.scrollingDeltaY); + if (!axis && x + y >= 3) { + if (x > y * 1.5) axis = 1; + else if (y > x * 1.5) axis = 2; + objc_setAssociatedObject(view, &axis_key, @(axis), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + if (axis == 1 && (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseChanged) && + !(event.modifierFlags & (NSEventModifierFlagShift | NSEventModifierFlagOption)) && + [NSEvent isSwipeTrackingFromScrollEventsEnabled]) { + // AppKit supplies Safari-style completion/cancellation and honours + // the user's Swipe Between Pages preference. No guessed velocity. + objc_setAssociatedObject(view, &swipe_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + __weak NSView *weak_view = view; + __block BOOL cancelled = NO; + __block BOOL previewed = NO; + [event trackSwipeEventWithOptions:NSEventSwipeTrackingLockDirection | NSEventSwipeTrackingClampGestureAmount + dampenAmountThresholdMin:-1 max:1 + usingHandler:^(CGFloat amount, NSEventPhase phase, BOOL complete, BOOL *stop) { + NSView *target = weak_view; + if (!target) { *stop = YES; return; } + if (phase == NSEventPhaseCancelled) cancelled = YES; + // An early notch says the swipe is approaching the + // shorter commit distance, while the fingers still move. + if (!cancelled && !complete && !previewed && fabs(amount) >= 0.12) { + previewed = YES; + ui_macos_trackpad_haptic(); + } + const BOOL commit = !cancelled && phase != NSEventPhaseNone && fabs(amount) >= 0.25; + if (!commit && !cancelled && phase != NSEventPhaseEnded && !complete) return; + objc_setAssociatedObject(target, &swipe_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(target, &suppress_momentum_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + // Commit during the physical swipe. AppKit's later + // animation to +/-1 must not set our trigger distance. + *stop = YES; + if (commit) + send_gesture(target, event, UI_TRACKPAD_HISTORY, amount > 0 ? 1 : -1, 0, 0); + }]; + return; + } + send_gesture(view, event, UI_TRACKPAD_SCROLL, + event.scrollingDeltaX, event.scrollingDeltaY, 0); + } else { + /* An ordinary mouse wheel retains SDL's discrete-notch handling. */ + [[view nextResponder] scrollWheel:event]; + } + (void)selector; +} + +void ui_macos_trackpad_attach(SDL_Window *window) +{ + NSWindow *native = (__bridge NSWindow *)SDL_GetPointerProperty( + SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); + NSView *view = native.contentView; + if (!view) return; + if (!gesture_type) { + /* SDL_EVENT_USER is already the shell's queue wake. */ + Uint32 first = SDL_RegisterEvents(2); + if (!first) return; + gesture_type = first + 1; + } + if (!trackpad_class) { + trackpad_class = objc_allocateClassPair(object_getClass(view), "PardesSDLTrackpadView", 0); + if (!trackpad_class) return; + SEL touch_selectors[] = { @selector(touchesBeganWithEvent:), @selector(touchesMovedWithEvent:), + @selector(touchesEndedWithEvent:), @selector(touchesCancelledWithEvent:) }; + for (unsigned i = 0; i < 4; ++i) + class_addMethod(trackpad_class, touch_selectors[i], (IMP)touches, "v@:@"); + class_addMethod(trackpad_class, @selector(pressureChangeWithEvent:), (IMP)pressure, "v@:@"); + class_addMethod(trackpad_class, @selector(rotateWithEvent:), (IMP)rotate, "v@:@"); + class_addMethod(trackpad_class, @selector(magnifyWithEvent:), (IMP)magnify, "v@:@"); + class_addMethod(trackpad_class, @selector(swipeWithEvent:), (IMP)swipe, "v@:@"); + class_addMethod(trackpad_class, @selector(scrollWheel:), (IMP)scroll, "v@:@"); + objc_registerClassPair(trackpad_class); + } + objc_setAssociatedObject(view, &window_key, [NSValue valueWithPointer:window], OBJC_ASSOCIATION_RETAIN_NONATOMIC); + object_setClass(view, trackpad_class); + view.allowedTouchTypes = NSTouchTypeMaskIndirect; + view.wantsRestingTouches = YES; + view.pressureConfiguration = [[NSPressureConfiguration alloc] + initWithPressureBehavior:NSPressureBehaviorPrimaryDeepClick]; +} diff --git a/dev/gui/pet.zig b/dev/gui/pet.zig new file mode 100644 index 00000000..7a13ca91 --- /dev/null +++ b/dev/gui/pet.zig @@ -0,0 +1,215 @@ +//! Original code-native pixel companions. Pure, bounded geometry and a 10 Hz +//! animation clock: no textures, allocation, input handling or editor state. +const std = @import("std"); + +pub const Kind = enum { off, cat, frog }; +pub const width = 12; +pub const height = 9; +pub const max_vertices = width * height * 6; +pub const Lane = struct { left: f32, right: f32, top: f32, scale: f32 }; +pub const Pose = struct { x: f32, y: f32, scale: f32, left: bool, walking: bool, frame: u8 }; +/// The frog's hop: sits two ticks, takes off, peaks for two, comes down, lands. +const hop_ticks = 8; + +/// Only the trailing blank part of the global tag is eligible. The caller +/// supplies its last occupied cell, including any wide-grapheme continuation. +pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32) ?Lane { + if (cell_w <= 0 or band_h < height + 2) return null; + const scale = @min(3, @floor((band_h - 2) / height)); + const left = @as(f32, @floatFromInt(occupied + 2)) * cell_w; + const right = screen_w - 2 * cell_w - width * scale; + if (right - left < 4 * scale) return null; + return .{ .left = left, .right = right, .top = top + band_h - height * scale - 1, .scale = scale }; +} + +pub const State = struct { + kind: Kind = .off, + tick: ?u64 = null, + x: f32 = 0, + target: f32 = 0, + left: bool = false, + idle: u8 = 12, + frame: u8 = 0, + rng: std.Random.DefaultPrng = undefined, + + /// No lane (the tag's text has filled it) hides the pet but keeps + /// where it was and what it was doing. + pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { + const region = area orelse return null; + if (kind == .off) { + s.* = .{}; + return null; + } + const tick = now_ms / 100; + if (s.kind != kind or s.tick == null) { + s.* = .{ .kind = kind, .tick = tick, .x = region.left, .target = region.left, .rng = .init(now_ms) }; + } + s.x = std.math.clamp(s.x, region.left, region.right); + s.target = std.math.clamp(s.target, region.left, region.right); + // Coming back from suspension never launches the pet across the tag. + const steps = @min(tick -| s.tick.?, 2); + s.tick = tick; + for (0..steps) |_| { + s.frame +%= 1; + if (s.idle > 0) { + s.idle -= 1; + if (s.idle == 0) { + // Wander to a random spot of the lane; one too close + // would be a shuffle in place, so take the far end. + s.target = region.left + s.rng.random().float(f32) * (region.right - region.left); + if (@abs(s.target - s.x) < 8 * region.scale) + s.target = if (s.x - region.left > region.right - s.x) region.left else region.right; + s.left = s.target < s.x; + s.frame = 255; // the walk starts at frame 0 + } + continue; + } + // The cat walks steadily; the frog travels only while airborne. + const phase = s.frame % hop_ticks; + if (kind == .cat or (phase >= 2 and phase < 6)) { + const step = (if (kind == .cat) @as(f32, 1.8) else 2.6) * region.scale; + s.x = if (s.left) @max(s.target, s.x - step) else @min(s.target, s.x + step); + } + if (s.x == s.target and (kind == .cat or phase == hop_ticks - 1)) + s.idle = s.rng.random().intRangeAtMost(u8, 20, 60); + } + return .{ .x = @floor(s.x), .y = region.top, .scale = region.scale, .left = s.left, .walking = s.idle == 0, .frame = s.frame }; + } +}; + +const cat = [_][]const u8{ + " # # ", + " #####", + " ##o##", + " # ######", + " # ######## ", + " ######### ", + " ######## ", + " ## ## ", + " # # ", +}; +const frog = [_][]const u8{ + " ", + " ", + " ", + " ## ", + " #o## ", + " #########", + " ######### ", + " ##### ## ", + "###### ### ", +}; +const frog_leap = [_][]const u8{ + " ## ", + " #o## ", + " #######", + " ######## ", + " ####### ", + " ### ## ", + "## # ", + "# ", + " ", +}; + +/// 0 transparent, 1 theme ink, 2 eye cutout. Walk legs and idle blinks are +/// generated in this fixed 12x9 tile; neither can spill into an adjacent row. +pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { + if (x_in >= width or y >= height or kind == .off) return 0; + const x = if (pose.left) width - 1 - x_in else x_in; + const alternate = (pose.frame / 2) % 2 == 1; + // An idle companion still looks alive during its first pause: a slow + // two-pixel tail-tip flick, or the frog's throat gently inflating. These + // remain inside the tile and mirror with the rest of the animal. + const breathing = (pose.frame / 4) % 2 == 1; + if (!pose.walking and breathing) { + if (kind == .cat and y == 3 and x <= 1) + return @intFromBool(x == 0); + if (kind == .frog and ((y == 6 and x == 11) or (y == 7 and x == 10))) return 1; + } + if (kind == .cat and pose.walking and alternate and y >= 7) + return @intFromBool((y == 7 and (x == 3 or x == 7)) or (y == 8 and (x == 2 or x == 8))); + // A hopping frog leaps two rows low at take-off and one on the way down. + const phase = pose.frame % hop_ticks; + const leaping = kind == .frog and pose.walking and phase >= 2 and phase < 6; + const sink: usize = if (!leaping) 0 else if (phase == 2) 2 else if (phase == 5) 1 else 0; + if (y < sink) return 0; + const ch = (if (kind == .cat) cat else if (leaping) frog_leap else frog)[y - sink][x]; + return switch (ch) { + '#' => 1, + 'o' => if (!pose.walking and pose.frame % 30 >= 27) 1 else 2, + else => 0, + }; +} + +test "pet stays in trailing workspace blanks, and a lost lane hides it without a reset" { + try std.testing.expect(lane(20, 8, 200, 0, 16) == null); + try std.testing.expect(lane(3, 8, 200, 0, 10) == null); + const region = lane(3, 8, 200, 2, 20).?; + try std.testing.expect(region.left >= 5 * 8); + var state: State = .{}; + var moved = false; + var reversed = false; + for (0..2000) |i| { + const pose = state.sample(.cat, i * 100, region).?; + try std.testing.expect(pose.x >= region.left and pose.x + width * pose.scale <= 200 - 16); + try std.testing.expect(pose.y >= 2 and pose.y + height * pose.scale < 22); + moved = moved or pose.walking; + reversed = reversed or pose.left; + } + try std.testing.expect(moved and reversed); + const kept = state; + try std.testing.expect(state.sample(.cat, 300000, null) == null); + try std.testing.expectEqual(kept.x, state.x); + try std.testing.expectEqual(kept.tick, state.tick); + try std.testing.expect(state.sample(.off, 300100, region) == null); +} + +test "pet clock is fixed rate and sprites bounded in both directions" { + const region = lane(1, 8, 400, 0, 16).?; + var state: State = .{}; + const start = state.sample(.frog, 1000, region).?; + try std.testing.expectEqualDeep(start, state.sample(.frog, 1099, region).?); + for ([_]Kind{ .cat, .frog }) |kind| for ([_]bool{ false, true }) |left| { + const pose: Pose = .{ .x = 0, .y = 0, .scale = 1, .left = left, .walking = true, .frame = 3 }; + var count: usize = 0; + for (0..height) |y| for (0..width) |x| { + count += @intFromBool(pixel(kind, pose, x, y) != 0); + }; + try std.testing.expect(count > 20 and count <= width * height); + try std.testing.expectEqual(@as(u2, 0), pixel(kind, pose, width, height)); + }; +} + +test "pet rests at random spots and the frog travels only in the air" { + const region = lane(1, 8, 800, 0, 16).?; + var state: State = .{}; + var last = state.sample(.frog, 0, region).?; + var rested_midway = false; + for (1..3000) |i| { + const pose = state.sample(.frog, i * 100, region).?; + const phase = pose.frame % hop_ticks; + if (pose.x != last.x) try std.testing.expect(pose.walking and phase >= 2 and phase < 6); + rested_midway = rested_midway or (last.walking and !pose.walking and pose.x > region.left and pose.x < @floor(region.right)); + last = pose; + } + try std.testing.expect(rested_midway); +} + +test "pet initial idle visibly animates without walking or leaving its tile" { + const region = lane(1, 8, 400, 0, 16).?; + for ([_]Kind{ .cat, .frog }) |kind| { + var state: State = .{}; + const initial = state.sample(kind, 0, region).?; + var later = initial; + for (1..5) |tick| later = state.sample(kind, tick * 100, region).?; + try std.testing.expect(!initial.walking and !later.walking); + try std.testing.expectEqual(initial.x, later.x); + try std.testing.expectEqual(initial.y, later.y); + var changes: usize = 0; + for (0..height) |y| for (0..width) |x| { + changes += @intFromBool(pixel(kind, initial, x, y) != pixel(kind, later, x, y)); + }; + try std.testing.expectEqual(@as(usize, 2), changes); + try std.testing.expectEqual(@as(u2, 0), pixel(kind, later, width, height)); + } +} diff --git a/dev/host_io.zig b/dev/host_io.zig new file mode 100644 index 00000000..d8b8bbb3 --- /dev/null +++ b/dev/host_io.zig @@ -0,0 +1,4007 @@ +const builtin = @import("builtin"); +const std = @import("std"); +const posix = std.posix; +/// libc: ptys, fork and exec, signals; and the leaf file calls (/proc, PATH, the prompt rc files), which run with no io: in a forked child, a signal handler, or for callers holding none. +const libc = std.c; +const pardes = @import("core"); +const selection_pipe = @import("core").selection_pipe; +const ninep_io = @import("runtime").ninep_io; +const filesystem = @import("core").filesystem; +const file_watch = @import("file_watch.zig"); +const replica = @import("core").replica; +const daemon = @import("runtime").daemon; +const panes = @import("core").panes; + +pub const Host = struct { + ctx: ?*anyopaque = null, + vtable: *const VTable = &.{}, + + pub const VTable = struct { + wait_input: ?*const fn (ctx: ?*anyopaque, timeout_ms: u32) void = null, + /// The shell's monotonic clock in ns: the only time the core sees. + /// Without one, core animation moves only by `.tick` events. + now: ?*const fn (ctx: ?*anyopaque) u64 = null, + present: ?*const fn (ctx: ?*anyopaque, surface: *const pardes.Surface) void = null, + post_present: ?*const fn (ctx: ?*anyopaque) void = null, + poll_frame: ?*const fn (ctx: ?*anyopaque) void = null, + /// Whether anyone sees a frame drawn now. A detached session with no + /// client attached draws none (a /screen read draws its own), and + /// the frame owed is drawn when one attaches. Absent: always. + watched: ?*const fn (ctx: ?*anyopaque) bool = null, + /// Detach: the terminal or window let go, the session left running + /// for the daemon to attach again (daemon.zig). + detach: ?*const fn (ctx: ?*anyopaque) void = null, + /// Adopt: the shells a dead session left, asked of the daemon. + adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + /// Upgrade: this process exec'd as the pardes installed since, at + /// the step's end (upgrade.zig); `pane` hears why if it cannot be. + upgrade: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + /// Whether a newer pardes is installed at the path this process + /// started from, to be said once (upgrade.zig): asked at a focus-in. + newer_build: ?*const fn (ctx: ?*anyopaque) bool = null, + spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null, + pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null, + pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null, + pty_signal: ?*const fn (ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void = null, + close_pty: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + tty_taken: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, + /// The name of the program holding the tty, when it is not the + /// shell (host_io.foregroundName), in `buf`. + fg_name: ?*const fn (ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 = null, + /// Answered at once, not queued as an effect: Kill asks while the + /// job it saw running is still the one in the tty (host_io.killJob). + kill_job: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, + write_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void = null, + write_dump: ?*const fn (ctx: ?*anyopaque, bytes: []const u8) void = null, + watch_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void = null, + watch_theme: ?*const fn (ctx: ?*anyopaque, generation: u32, on: bool) void = null, + dump_themes: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null, + read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null, + open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null, + /// A plumbing rule's program (Effect.start): every host's is + /// startDetached. Null once it runs, else why not. + start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null, + lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, + pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, + /// Start the streaming search of this generation on a worker + /// (pardes.Stream.start); absent, it runs on the loop. + search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null, + /// Carry the dump of handover `seq` to another window on a worker + /// (Handover.start), which answers through the inbox's `handed`. + hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null, + /// Run job `token` of the pane in slot `pane` (whose serial is + /// `serial`) on a worker (`KindJob`), answering with the `job` event; + /// absent, it runs on the loop. + job: ?*const fn (ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void = null, + }; +}; + +/// A kind's job (Effect.job), taken off its pane: its input, its kind's +/// `job_run` and generation; run on a worker (or here), its answer the +/// core's `job` event. Its library is held until it lands (Addon.holdJob). +/// A draw (api.draw, `draw`) is one of this process's alone: never an +/// event, its answer kept for the pane's next paint (Kind.landDraw). +pub const KindJob = struct { + gpa: std.mem.Allocator, + pane: u8, + serial: u32, + token: u32, + gen: u32, + ops: *const pardes.Kind.Ops, + in: []u8, + /// What the job allocates (`pa_out`), freed with it; `out` the last. + arena: std.heap.ArenaAllocator, + out: []u8 = &.{}, + id: u32 = 0, + /// A draw's: the core it was asked in. + draw: ?*const pardes.Pardes = null, + + pub fn take(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) ?*KindJob { + const pn = p.panes[pane] orelse return null; + const slot = pn.addon orelse return null; + const ops = slot.ops orelse return null; + if (pn.serial != serial or ops.job_run == null) return null; + const at = for (&slot.jobs) |*j| { + if (j.*) |job| if (job.token == token) break j; + } else return null; + const j = slot.gpa.create(KindJob) catch return null; + j.* = .{ .gpa = slot.gpa, .pane = pane, .serial = serial, .token = token, .gen = slot.gen, .ops = ops, .in = at.*.?.in, .arena = .init(slot.gpa) }; + at.* = null; + pardes.Addon.holdJob(ops, true); + return j; + } + + pub fn run(j: *KindJob) void { + const Out = struct { + fn alloc(out: [*c]pardes.Kind.c.pa_out, n: usize) callconv(.c) ?*anyopaque { + const job: *KindJob = @ptrCast(@alignCast(out.*.ctx)); + job.out = job.arena.allocator().alignedAlloc(u8, .@"16", n) catch &.{}; + return if (job.out.len == n) job.out.ptr else null; + } + }; + var out: pardes.Kind.c.pa_out = .{ .alloc = Out.alloc, .ctx = j }; + const n = j.ops.job_run.?(j.in.ptr, @intCast(j.in.len), &out); + j.out = j.out[0..@min(n, j.out.len)]; + } + + /// Its answer to the core, and it gone. + pub fn land(j: *KindJob, p: *pardes.Pardes) void { + if (j.draw != null) return pardes.Kind.landDraw(p, j); + p.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); + j.drop(); + } + + pub fn drop(j: *KindJob) void { + pardes.Addon.holdJob(j.ops, false); + j.gpa.free(j.in); + j.arena.deinit(); + j.gpa.destroy(j); + } + + /// On a worker of `io`, posting itself to `sink` done: a host's `job`. + pub fn start(io: std.Io, p: *pardes.Pardes, tasks: *selection_pipe.Tasks, pane: u8, serial: u32, token: u32, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) void { + const j = take(p, pane, serial, token) orelse return; + if (!go(io, tasks, j, ctx, sink)) here(j, p); + } + + /// `j` on a worker of `io`, posting itself to `sink` done; false when + /// none could take it. + pub fn go(io: std.Io, tasks: *selection_pipe.Tasks, j: *KindJob, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) bool { + next_id +%= 1; + j.id = next_id | 0x8000_0000; + const work = struct { + fn work(job: *KindJob, c: ?*anyopaque, s: *const fn (?*anyopaque, *KindJob) void) void { + job.run(); + s(c, job); + } + }.work; + if (tasks.full()) return false; + const future = io.concurrent(work, .{ j, ctx, sink }) catch return false; + _ = tasks.add(.{ .id = j.id, .future = future }); + return true; + } + + var next_id: u32 = 0; + + fn here(j: *KindJob, p: *pardes.Pardes) void { + j.run(); + j.land(p); + } + + /// No workers (a test, the fallback): it runs on the loop, at once. + pub fn runHere(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) void { + here(take(p, pane, serial, token) orelse return, p); + } +}; + +/// PARDES_TEST_CLOCK makes a shell's `Host.now` answer a virtual clock +/// instead of `std.Io.Clock.awake`, moved only when a timed wait runs out -- +/// straight to the core's next wake -- so the snapshot harness sees the same +/// frames whatever the machine's load. +pub fn testClock() ?u64 { + return if (libc.getenv("PARDES_TEST_CLOCK")) |v| (if (std.mem.span(v).len != 0) 0 else null) else null; +} + +/// The kitty images and syntax subsystems a frontend's session draws with, +/// on `allocs` (pardes.memory.init), and what kinds keep past a call (their +/// heap, `pa_api.heap`: the pdf addon's documents and pages). `stopWorkers` +/// is its defer. +pub fn startWorkers(allocs: pardes.memory.Allocators) void { + pardes.Term.start(allocs.image); + pardes.Kind.heap = allocs.addon; + pardes.syntax.start(allocs.tree_sitter); +} + +pub fn stopWorkers() void { + pardes.Term.stop(); + pardes.syntax.stop(); +} + +/// A Restore's new core, from the dump at `path` (core.takeRestore), or +/// null once why it is not is said. ponytail: a Restore replaces the core +/// its clients replicate; they are let go, and attach again. The old +/// core's panes and theme are no longer watched; the frontend lets go of +/// its ptys and pipes and swaps the new core in. ponytail: a restored +/// session is one view, the live one's (the tty's terminal, the window's +/// window): the others are let go, as a detach of each. +pub fn restoreCore(gpa: std.mem.Allocator, core: *pardes.Pardes, path: []const u8, peers: *replica.Peers, inotify_fd: c_int, watches: *file_watch.Table) ?*pardes.Pardes { + peers.dropAll(core); + const bytes = pardes.dump.restoreBytes(core, gpa, path) catch |err| { + core.reportError(core.view().active, "Restore", err); + return null; + }; + defer gpa.free(bytes); + const nc = pardes.dump.restore(core, bytes, path) catch |err| { + core.reportError(core.view().active, "Restore", err); + return null; + }; + file_watch.unwatchAll(inotify_fd, watches); + _ = file_watch.applyThemeEffect(core, gpa, inotify_fd, watches, 0, false); + return nc; +} + +/// A shell of a dead session the daemon handed this one (Adopt), and the +/// terminal pane made for it once there is one. +pub const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 }; + +/// The shells of dead sessions handed this one (Adopt), each waiting for +/// the spawn of the terminal pane made for it (`take`). +pub const Adoptions = struct { + list: [pardes.MAX_PANES]Adoption = undefined, + len: usize = 0, + /// Taken in since the last Adopt. + taken: usize = 0, + + /// Adopt: the daemon is asked for the shells of sessions that died + /// holding them; each comes back to `adoptShell`. + pub fn ask(a: *Adoptions, core: *pardes.Pardes, pane: u8) void { + if (!daemon.kept()) return core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); + a.taken = 0; + daemon.adopt(); + } + + /// One shell of a dead session (`pid` 0: the last of them was told): + /// a terminal pane made for it, as the Term word makes one, whose spawn + /// takes this pty instead of forking a shell (`take`). + pub fn adoptShell(a: *Adoptions, core: *pardes.Pardes, pid: libc.pid_t, fd: c_int) void { + if (pid == 0) { + var buf: pardes.Kind.Buf(96) = .{}; + return core.setMessage(core.view().active, if (a.taken == 0) "Adopt: no shell of a session that died is waiting" else buf.print("Adopt: {d} shell{s} taken in; what they showed is gone", .{ a.taken, if (a.taken == 1) "" else "s" })); + } + if (a.len < a.list.len) { + a.list[a.len] = .{ .pid = pid, .fd = fd, .pane = null }; + a.len += 1; + if (core.adoptShell()) |id| { + a.list[a.len - 1].pane = id; + a.taken += 1; + return; + } + a.len -= 1; + } + // No room for it: its master goes, and the shell with this session. + _ = libc.close(fd); + var buf: pardes.Kind.Buf(96) = .{}; + core.setMessage(core.view().active, buf.print("Adopt: no room for shell {d}; it ends with this session", .{pid})); + } + + /// The adopted shell pane `pane`'s spawn takes, off the list. + pub fn take(a: *Adoptions, pane: u8) ?Adoption { + for (a.list[0..a.len], 0..) |it, i| if (it.pane == pane) { + std.mem.copyForwards(Adoption, a.list[i .. a.len - 1], a.list[i + 1 .. a.len]); + a.len -= 1; + return it; + }; + return null; + } +}; + +pub const Fallback = struct { + pub const dump_path = "pardes.dump"; + + gpa: std.mem.Allocator, + files: std.StringHashMapUnmanaged([]u8) = .empty, + clipboard: std.ArrayListUnmanaged(u8) = .empty, + link: std.ArrayListUnmanaged(u8) = .empty, + /// The programs plumbing rules started, as Effect.start packs them, + /// one a line. + started: std.ArrayListUnmanaged(u8) = .empty, + spawned: [pardes.MAX_PANES]bool = @splat(false), + watched: [pardes.MAX_PANES]bool = @splat(false), + + pub fn deinit(f: *Fallback) void { + var it = f.files.iterator(); + while (it.next()) |entry| { + f.gpa.free(entry.key_ptr.*); + f.gpa.free(entry.value_ptr.*); + } + f.files.deinit(f.gpa); + f.clipboard.deinit(f.gpa); + f.link.deinit(f.gpa); + f.started.deinit(f.gpa); + } + + pub fn writeFile(f: *Fallback, path: []const u8, bytes: []const u8) bool { + const copy = f.gpa.dupe(u8, bytes) catch return false; + if (f.files.getEntry(path)) |entry| { + f.gpa.free(entry.value_ptr.*); + entry.value_ptr.* = copy; + return true; + } + const key = f.gpa.dupe(u8, path) catch { + f.gpa.free(copy); + return false; + }; + f.files.put(f.gpa, key, copy) catch { + f.gpa.free(key); + f.gpa.free(copy); + return false; + }; + return true; + } + + pub fn get(f: *const Fallback, path: []const u8) ?[]const u8 { + if (f.files.get(path)) |written| return written; + return filesystem.sourceBytes(path); + } + + pub fn setClipboard(f: *Fallback, text: []const u8) void { + f.clipboard.clearRetainingCapacity(); + f.clipboard.appendSlice(f.gpa, text) catch {}; + } + + pub fn setLink(f: *Fallback, url: []const u8) void { + f.link.clearRetainingCapacity(); + f.link.appendSlice(f.gpa, url) catch {}; + } + + pub fn start(f: *Fallback, line: []const u8) ?[]const u8 { + f.started.appendSlice(f.gpa, line) catch return "out of memory"; + f.started.append(f.gpa, '\n') catch return "out of memory"; + return null; + } +}; + +/// What a pixel host's loop takes from its workers, in order: each pane's +/// pty output (a reader waits while `output_capacity` is full, so output is +/// never dropped or reordered), its end of file, the language client's +/// answers and status and the `|` jobs' answers (those kept apart, so a +/// full output queue never holds them up), and file-watch news. Output and +/// end of file of a reader that was canceled or replaced, and an answer to +/// a language query since superseded, are dropped here. +pub const Inbox = struct { + pub const Msg = union(enum) { + output: struct { pane: u8, gen: u32, bytes: []u8 }, + eof: struct { pane: u8, gen: u32, failure: ?anyerror = null }, + lsp: struct { id: u32, rows: ?[]u8 }, + lsp_status: []u8, + pipe: selection_pipe.Response, + /// A streaming search's rows (pardes.Stream), of whatever generation: + /// the core drops a stale one. + search: pardes.Stream.Batch, + /// How a handover went (Handover.zig): `words` is where it went, or + /// why it did not; gpa-owned. + handed: struct { seq: u32, ok: bool, words: []u8 }, + /// A kind's job done on a worker (KindJob), never dropped. + kind_job: *KindJob, + files_changed, + fs_ready, + /// The daemon asks for the window again (`pardes-gui --attach`). + window, + /// A shell a dead session left, its pty's master (Adopt); pid 0 is + /// the last of them told. + adopted: struct { pid: libc.pid_t, fd: c_int }, + + pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void { + switch (m) { + .output => |o| gpa.free(o.bytes), + .lsp => |l| if (l.rows) |rows| lsp_allocator.free(rows), + .lsp_status => |t| lsp_allocator.free(t), + .pipe => |response_value| { + var response = response_value; + response.deinit(gpa); + }, + .search => |b| b.deinit(gpa), + .handed => |h| gpa.free(h.words), + .kind_job => |j| j.drop(), + .adopted => |a| if (a.fd >= 0) { + _ = libc.close(a.fd); + }, + .eof, .files_changed, .fs_ready, .window => {}, + } + } + }; + + pub const capacity = 512; + pub const output_capacity = capacity - pardes.MAX_PANES; + + pub const Batch = struct { + items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined, + len: usize = 0, + + pub fn slice(batch: *Batch) []Msg { + return batch.items[0..batch.len]; + } + }; + + gpa: std.mem.Allocator, + lsp_allocator: std.mem.Allocator, + /// The query in flight; the UI thread's alone (spawnLsp, teardown). + lsp_task: ?Lsp.Task = null, + /// Wakes the host's loop after a push from another thread: an SDL + /// event, a macOS runtime callback. Null: nobody to wake (tests). + wake_fn: ?*const fn (?*anyopaque) void = null, + wake_ctx: ?*anyopaque = null, + /// The process's Io: its terminal readers wait for space on `space`. + io: std.Io, + mutex: std.Io.Mutex = .init, + space: std.Io.Condition = .init, + items: [capacity]Msg = undefined, + head: usize = 0, + len: usize = 0, + closed: bool = false, + files_changed: bool = false, + readers: [pardes.MAX_PANES]?u32 = @splat(null), + waiting: usize = 0, + lsp_id: ?u32 = null, + completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined, + completion_len: usize = 0, + + pub fn lock(q: *Inbox) void { + q.mutex.lockUncancelable(q.io); + } + + pub fn unlock(q: *Inbox) void { + q.mutex.unlock(q.io); + } + + pub fn wake(q: *Inbox) void { + if (q.wake_fn) |f| f(q.wake_ctx); + } + + pub fn acceptReader(q: *Inbox, pane: u8, gen: u32) void { + q.lock(); + defer q.unlock(); + std.debug.assert(q.readers[pane] == null); + q.readers[pane] = gen; + } + + pub fn cancelReader(q: *Inbox, pane: u8, gen: u32) void { + q.lock(); + defer q.unlock(); + if (q.readers[pane] != gen) return; + q.readers[pane] = null; + var i: usize = 0; + while (i < q.len) { + const msg = q.items[(q.head + i) % q.items.len]; + const matches = switch (msg) { + .output => |o| o.pane == pane and o.gen == gen, + .eof => |e| e.pane == pane and e.gen == gen, + else => false, + }; + if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; + } + q.space.broadcast(q.io); + } + + pub fn pushOutput(q: *Inbox, pane: u8, gen: u32, bytes: []u8) bool { + q.lock(); + while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) { + q.waiting += 1; + q.space.waitUncancelable(q.io, &q.mutex); + q.waiting -= 1; + } + if (q.closed or q.readers[pane] != gen) { + q.unlock(); + q.gpa.free(bytes); + return false; + } + q.items[(q.head + q.len) % q.items.len] = .{ .output = .{ .pane = pane, .gen = gen, .bytes = bytes } }; + q.len += 1; + q.unlock(); + q.wake(); + return true; + } + + fn removeAt(q: *Inbox, offset: usize) Msg { + const removed = q.items[(q.head + offset) % q.items.len]; + var i = offset; + while (i + 1 < q.len) : (i += 1) + q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len]; + q.len -= 1; + return removed; + } + + pub fn discardLsp(q: *Inbox) void { + for (q.completions[0..q.completion_len], 0..) |msg, i| if (msg == .lsp) { + msg.deinit(q.gpa, q.lsp_allocator); + q.completion_len -= 1; + std.mem.copyForwards(Msg, q.completions[i..q.completion_len], q.completions[i + 1 .. q.completion_len + 1]); + return; + }; + } + + pub fn push(q: *Inbox, m: Msg) void { + if (m == .output) { + _ = q.pushOutput(m.output.pane, m.output.gen, m.output.bytes); + return; + } + q.lock(); + if (q.closed) { + q.unlock(); + m.deinit(q.gpa, q.lsp_allocator); + return; + } + switch (m) { + .files_changed => q.files_changed = true, + .lsp, .pipe, .kind_job => { + if (m == .lsp) { + if (q.lsp_id != m.lsp.id) { + q.unlock(); + m.deinit(q.gpa, q.lsp_allocator); + return; + } + q.discardLsp(); + } + std.debug.assert(q.completion_len < q.completions.len); + q.completions[q.completion_len] = m; + q.completion_len += 1; + }, + else => { + if (m == .eof) { + if (q.readers[m.eof.pane] != m.eof.gen) { + q.unlock(); + return; + } + std.debug.assert(q.len < q.items.len); + } else if (q.len >= output_capacity) { + q.unlock(); + m.deinit(q.gpa, q.lsp_allocator); + return; + } + q.items[(q.head + q.len) % q.items.len] = m; + q.len += 1; + }, + } + q.unlock(); + q.wake(); + } + + pub fn take(q: *Inbox) Batch { + var batch: Batch = .{}; + q.takeInto(&batch); + return batch; + } + + /// `take` into a batch the caller keeps: an idle wakeup copies nothing + /// (the batch is some 20 KB, and was built and returned by value each + /// time). + pub fn takeInto(q: *Inbox, batch: *Batch) void { + batch.len = 0; + q.lock(); + defer q.unlock(); + if (q.len == 0 and !q.files_changed and q.completion_len == 0) return; + while (q.len > 0) { + batch.items[batch.len] = q.items[q.head]; + batch.len += 1; + q.head = (q.head + 1) % q.items.len; + q.len -= 1; + } + q.head = 0; + if (q.files_changed) { + batch.items[batch.len] = .files_changed; + batch.len += 1; + q.files_changed = false; + } + @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]); + batch.len += q.completion_len; + q.completion_len = 0; + q.space.broadcast(q.io); + } + + pub fn discardCompletions(q: *Inbox) void { + q.lock(); + defer q.unlock(); + q.lsp_id = null; + for (q.completions[0..q.completion_len]) |msg| msg.deinit(q.gpa, q.lsp_allocator); + q.completion_len = 0; + } + + pub fn close(q: *Inbox) void { + q.lock(); + q.closed = true; + q.files_changed = false; + q.readers = @splat(null); + q.space.broadcast(q.io); + q.unlock(); + q.discardCompletions(); + q.lock(); + defer q.unlock(); + while (q.len > 0) { + const m = q.items[q.head]; + m.deinit(q.gpa, q.lsp_allocator); + q.head = (q.head + 1) % q.items.len; + q.len -= 1; + } + q.head = 0; + } + + pub fn deinit(q: *Inbox) void { + q.close(); + std.debug.assert(q.waiting == 0); + } + + /// A pane's reader: its pty's output pushed as it comes, then its end + /// of file; canceled (closePty), it pushes nothing more. + pub fn startReader(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) !std.Io.Future(void) { + q.acceptReader(pane, gen); + errdefer q.cancelReader(pane, gen); + return q.io.concurrent(readPty, .{ q, pty, pane, gen }); + } + + fn readPty(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) void { + var buf: [0x10000]u8 = undefined; + var failure: ?anyerror = null; + while (true) { + const n = pty.readStreaming(q.io, &.{&buf}) catch |err| switch (err) { + // A pty whose child has gone answers EIO: its end of file. + error.EndOfStream, error.InputOutput => break, + error.Canceled => return, + else => { + failure = err; + break; + }, + }; + if (n == 0) continue; + const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| { + failure = err; + break; + }; + if (!q.pushOutput(pane, gen, bytes)) return; + } + q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } }); + } + + /// Starts `e`, its answer let in and every older one's turned away. + pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void { + q.lock(); + q.lsp_id = e.id; + q.discardLsp(); + q.unlock(); + // The old query's waits are cancelation points: its join is short, and + // what it still delivers carries an id the queue now rejects. + Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows); + } + + fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); + q.push(.{ .lsp = .{ .id = id, .rows = rows } }); + } + + /// The language client's status line (lsp.setStatusSink). + pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); + const copy = q.lsp_allocator.dupe(u8, text) catch return; + q.push(.{ .lsp_status = copy }); + } + + /// A `|` job's answer (selection_pipe.start's sink). + pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.push(.{ .kind_job = j }); + } + + pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.push(.{ .pipe = response }); + } + + /// A handover's end (Handover.Job.post). + pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + const copy = q.gpa.dupe(u8, words) catch return; + q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } }); + } + + /// A streaming search's batch (pardes.Stream.start's sink). Never + /// dropped for want of room, as output is not: the worker waits for + /// room, a wait its cancel ends (false: it stops). + pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.lock(); + while (!q.closed and q.len >= output_capacity) { + q.waiting += 1; + q.space.wait(q.io, &q.mutex) catch { + q.waiting -= 1; + q.unlock(); + batch.deinit(q.gpa); + return false; + }; + q.waiting -= 1; + } + if (q.closed) { + q.unlock(); + batch.deinit(q.gpa); + return false; + } + q.items[(q.head + q.len) % q.items.len] = .{ .search = batch }; + q.len += 1; + q.unlock(); + q.wake(); + return true; + } + + /// A watched child exited (setExitWake): wake the loop, which takes it. + pub fn wakeForExit(ctx: ?*anyopaque) void { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.wake(); + } +}; + +pub const Lsp = struct { + pub const Request = struct { + id: u32, + kind: pardes.lsp.Kind, + pane: u8, + offset: u32, + arg: []const u8, + }; + + pub const Task = struct { + id: u32, + future: std.Io.Future(void), + }; + + /// One language query, owned by the worker that runs it. + pub const Job = struct { + callstack_depth: u8 = pardes.lsp.callstack_default_depth, + dirty: bool = false, + id: u32, + kind: pardes.lsp.Kind, + offset: u32, + path: []u8, + source: [:0]u8, + arg: []u8, + root: []u8, + /// The other open files, for a query that can reach them. + others: []pardes.lsp.Doc = &.{}, + + pub fn free(job: *Job, gpa: std.mem.Allocator) void { + gpa.free(job.path); + gpa.free(job.source); + gpa.free(job.arg); + gpa.free(job.root); + for (job.others) |doc| { + gpa.free(doc.path); + gpa.free(doc.source); + } + gpa.free(job.others); + gpa.destroy(job); + } + }; + + // Copy before starting a worker; the editor may replace any source slice afterward. + pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job { + if (req.pane >= core.panes.len) return error.NoPane; + const pane = core.panes[req.pane] orelse return error.NoPane; + const file = pane.file; + const job = try gpa.create(Job); + errdefer gpa.destroy(job); + const declared_path = if (file) |f| f.path else ""; + const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); + errdefer gpa.free(path); + const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0); + errdefer gpa.free(source); + const arg = try gpa.dupe(u8, req.arg); + errdefer gpa.free(arg); + const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice(); + const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); + errdefer gpa.free(root); + job.* = .{ + .callstack_depth = core.settings.callstack_depth, + .dirty = pardes.tagline.dirty(pane), + .id = req.id, + .kind = req.kind, + .offset = req.offset, + .path = path, + .source = source, + .arg = arg, + .root = root, + }; + // ponytail: a copy of every open file per such query; a server + // already told of one is sent nothing more (syncDoc). + // Lspwhy too: the query it explains may be one of those, and its + // trace shows each file synced first. + if (pardes.lsp.reachesOtherFiles(req.kind) or req.kind == .explain) { + var others: std.ArrayList(pardes.lsp.Doc) = .empty; + errdefer { + for (others.items) |doc| { + gpa.free(doc.path); + gpa.free(doc.source); + } + others.deinit(gpa); + } + var copied: usize = 0; + for (core.panes, 0..) |slot, i| { + const other = slot orelse continue; + if (i == req.pane) continue; + const f = other.file orelse continue; + if (f.output != null) continue; + if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; + copied += f.content.len; + const local = filesystem.localPath(f.path) orelse continue; + const other_path = try gpa.dupe(u8, local); + const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { + gpa.free(other_path); + return err; + }; + try others.append(gpa, .{ .path = other_path, .source = other_source }); + } + job.others = try others.toOwnedSlice(gpa); + } + return job; + } + + // Null is failure; the receiver frees non-null rows with the job's allocator. + pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; + + /// Start `req` on a worker that hands its rows to `deliver`, the query + /// in `task` canceled first. One that cannot start is answered (no rows) + /// and reported here. + pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?Task, req: Request, ctx: ?*anyopaque, deliver: Deliver) void { + if (task.*) |*old| { + old.future.cancel(io); + task.* = null; + } + const job = snapshot(gpa, core, req) catch |err| { + core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return core.reportError(req.pane, "lsp", err); + }; + const future = io.concurrent(work, .{ io, gpa, job, ctx, deliver }) catch |err| { + job.free(gpa); + core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); + return core.reportError(req.pane, "lsp", err); + }; + task.* = .{ .id = req.id, .future = future }; + } + + pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { + defer job.free(gpa); + // The query's memory is the fixed region memory.zig reserved at + // startup: a hard bound, reused by each query in turn. + const region = pardes.memory.takeLspQuery() orelse { + deliver(ctx, job.id, null); + return; + }; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer pardes.memory.giveLspQuery(arena.end_index); + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + pardes.lsp.query(io, arena.allocator(), .{ + .kind = job.kind, + .path = job.path, + .source = job.source, + .offset = job.offset, + .arg = job.arg, + .root = job.root, + .others = job.others, + .callstack_depth = job.callstack_depth, + .dirty = job.dirty, + .budget = &arena, + }, &out.writer) catch { + deliver(ctx, job.id, null); + return; + }; + const rows = out.toOwnedSlice() catch { + deliver(ctx, job.id, null); + return; + }; + deliver(ctx, job.id, rows); + } + + test "a snapshot owns every byte the backend will read" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + + core.settings.callstack_depth = 16; + var needle: [6]u8 = "needle".*; + const job = try snapshot(gpa, core, .{ + .id = 7, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = &needle, + }); + defer job.free(gpa); + + core.settings.callstack_depth = 2; + try std.testing.expectEqual(@as(u8, 16), job.callstack_depth); + try std.testing.expectEqual(@as(u32, 7), job.id); + try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind); + try std.testing.expectEqualStrings("needle", job.arg); + try std.testing.expect(job.arg.ptr != &needle); + try std.testing.expectEqualStrings("", job.path); + try std.testing.expectEqual(@as(usize, 0), job.source.len); + try std.testing.expectEqual(@as(u8, 0), job.source[0]); + const pane = core.panes[core.view().active].?; + try std.testing.expectEqualStrings(pane.cwdSlice(), job.root); + if (job.root.len > 0) try std.testing.expect(job.root.ptr != pane.cwdSlice().ptr); + } + + test "LSP snapshot frees every partially copied field on allocation failure" { + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + _ = try core.setTestFile("const copied = true;\n"); + const Snapshot = struct { + fn check(gpa: std.mem.Allocator, p: *const pardes.Pardes) !void { + const job = try snapshot(gpa, p, .{ + .id = 7, + .kind = .hover, + .pane = @intCast(p.view().active), + .offset = 6, + .arg = "query", + }); + defer job.free(gpa); + try std.testing.expectEqualStrings("const copied = true;\n", job.source); + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Snapshot.check, .{core}); + } + + test "LSP snapshots translate explicit OS paths once and retain virtual names" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("const value = true;\n"); + for ([_]struct { path: []const u8, native: []const u8 }{ + .{ .path = "/n/os/project/file.zig", .native = "/project/file.zig" }, + .{ .path = "/n/os/n/os/project/file.zig", .native = "/n/os/project/file.zig" }, + .{ .path = "/virtual/src/file.zig", .native = "/virtual/src/file.zig" }, + }) |case| { + const replacement = try gpa.dupe(u8, case.path); + gpa.free(pane.file.?.path); + pane.file.?.path = replacement; + const job = try snapshot(gpa, core, .{ .id = 1, .kind = .hover, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); + defer job.free(gpa); + try std.testing.expectEqualStrings(case.native, job.path); + try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(case.native).?, job.root); + try std.testing.expectEqualStrings(case.path, pane.file.?.path); + } + } + + test "a pane that is gone yields no job rather than a null deref" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + + // The effect is drained after the core has moved on, so the pane it names + // may already have been deleted. Every shell open-coded this check. + const empty = for (core.panes, 0..) |slot, id| { + if (slot == null) break @as(u8, @intCast(id)); + } else return error.NoEmptyPane; + try std.testing.expectError(error.NoPane, snapshot(gpa, core, .{ + .id = 1, + .kind = .definition, + .pane = empty, + .offset = 0, + .arg = "", + })); + } + + test "work consumes the job and hands its rows to the sink" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + + const Sink = struct { + var seen_id: u32 = 0; + var seen_rows: ?[]u8 = null; + fn take(_: ?*anyopaque, id: u32, rows: ?[]u8) void { + seen_id = id; + seen_rows = rows; + } + }; + Sink.seen_id = 0; + Sink.seen_rows = null; + + const job = try snapshot(gpa, core, .{ + .id = 42, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }); + work(std.testing.io, gpa, job, null, Sink.take); + + // `status` is the one kind that answers with no file and no cursor, which + // is what makes it assertable here without a language server on the box. + try std.testing.expectEqual(@as(u32, 42), Sink.seen_id); + const rows = Sink.seen_rows orelse return error.SinkNeverCalled; + defer gpa.free(rows); + } + + test "LSP edit query failure leaves text and undo untouched before a successful retry" { + if (!pardes.lsp.supports.contains(.format)) return; + const Sink = struct { + core: *pardes.Pardes, + gpa: std.mem.Allocator, + calls: usize = 0, + failed: bool = false, + + fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const self: *@This() = @ptrCast(@alignCast(ctx.?)); + defer if (rows) |text| self.gpa.free(text); + self.calls += 1; + self.failed = rows == null; + self.core.update(.{ .lsp_resp = .{ .id = id, .rows = rows } }); + } + }; + const gpa = std.testing.allocator; + for ([_]pardes.lsp.Kind{ .format, .rename }) |kind| { + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("const value=1;\n"); + const path = try gpa.dupe(u8, "/file.zig"); + gpa.free(pane.file.?.path); + pane.file.?.path = path; + pane.body.cur_col = 6; + const revision = pane.file.?.revision; + const undo_len = pane.file.?.history.journal.done; + var failing = std.testing.FailingAllocator.init(gpa, .{}); + var sink: Sink = .{ .core = core, .gpa = failing.allocator() }; + for ([_]bool{ true, false }) |fail| { + failing.fail_index = std.math.maxInt(usize); + core.lspRequest(core.view().active, kind, "renamed"); + const job = try snapshot(failing.allocator(), core, .{ + .id = core.lsp_ask.wait.?.id, + .kind = kind, + .pane = @intCast(core.view().active), + .offset = 6, + .arg = "renamed", + }); + if (fail) failing.fail_index = failing.alloc_index; + work(std.testing.io, failing.allocator(), job, &sink, Sink.take); + try std.testing.expectEqual(fail, sink.failed); + try std.testing.expect(core.lsp_ask.wait == null); + if (fail) { + try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content); + try std.testing.expectEqual(revision, pane.file.?.revision); + try std.testing.expectEqual(undo_len, pane.file.?.history.journal.done); + } else { + try std.testing.expectEqualStrings(if (kind == .format) "const value = 1;\n" else "const renamed=1;\n", pane.file.?.content); + try std.testing.expectEqual(undo_len + 1, pane.file.?.history.journal.done); + } + } + try std.testing.expectEqual(@as(usize, 2), sink.calls); + } + } + + test "LSP work delivers failure when transferring result ownership cannot allocate" { + if (!pardes.lsp.supports.contains(.status)) return; + const TransferAllocator = struct { + failed: bool = false, + fail_copy: bool = false, + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.fail_copy) { + self.failed = true; + return null; + } + return std.testing.allocator.rawAlloc(len, alignment, ra); + } + fn resize(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { + return std.testing.allocator.rawResize(bytes, alignment, len, ra); + } + fn remap(ctx: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (len < bytes.len) { + self.fail_copy = true; + return null; + } + return std.testing.allocator.rawRemap(bytes, alignment, len, ra); + } + fn free(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, ra: usize) void { + std.testing.allocator.rawFree(bytes, alignment, ra); + } + }; + const Sink = struct { + calls: usize = 0, + id: u32 = 0, + rows: ?[]u8 = null, + fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { + const self: *@This() = @ptrCast(@alignCast(ctx.?)); + self.calls += 1; + self.id = id; + self.rows = rows; + } + }; + var allocator: TransferAllocator = .{}; + const gpa: std.mem.Allocator = .{ .ptr = &allocator, .vtable = &.{ + .alloc = TransferAllocator.alloc, + .resize = TransferAllocator.resize, + .remap = TransferAllocator.remap, + .free = TransferAllocator.free, + } }; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); + var sink: Sink = .{}; + work(std.testing.io, gpa, job, &sink, Sink.take); + if (sink.rows) |rows| gpa.free(rows); + try std.testing.expect(allocator.failed); + try std.testing.expectEqual(@as(usize, 1), sink.calls); + try std.testing.expectEqual(@as(u32, 37), sink.id); + try std.testing.expect(sink.rows == null); + } +}; + +pub const Shell = struct { + const X_OK: c_int = 1; + + extern "c" fn mkstemp(template: [*:0]u8) c_int; + extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + + const path_capacity = 4096; + const max_path_files = 64; + + // Repair only the system-only PATH inherited from a macOS GUI launch. + fn adoptSystemPath() void { + if (comptime builtin.os.tag != .macos) return; + var buf: [path_capacity]u8 = undefined; + var len: usize = 0; + collectSystemPath("/etc/paths", "/etc/paths.d", &buf, &len); + if (len == 0) return; + const system = buf[0..len]; + + const current: []const u8 = if (libc.getenv("PATH")) |p| std.mem.span(p) else ""; + if (!allEntriesWithin(current, system)) return; + if (std.mem.eql(u8, current, system)) return; + + var out: [path_capacity:0]u8 = undefined; + if (len >= out.len) return; + @memcpy(out[0..len], system); + out[len] = 0; + _ = setenv("PATH", out[0..len :0].ptr, 1); + } + + // Run in the parent before forking; children borrow the completed prompt files. + pub fn prepare() PromptFiles { + adoptSystemPath(); + if (comptime builtin.os.tag.isDarwin()) + _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1); + sweepDeadRcs(); + const rcs = PromptFiles.init(); + // A private file goes at a fatal signal too, not only at Exit. + for ([_]?[:0]const u8{ if (rcs.bash_owned) rcs.bashPath() else null, if (rcs.fish_owned) rcs.fishPath() else null }, 0..) |owned, i| { + const path = owned orelse continue; + @memcpy(fatal_rcs[i][0..path.len], path); + fatal_rcs[i][path.len] = 0; + fatal_rc_len[i] = path.len; + } + ninep_io.fatal_cleanup = unlinkOwnedRcs; + return rcs; + } + + /// This process's private prompt files, where a fatal signal's handler + /// can reach them (unlinkOwnedRcs). + var fatal_rcs: [2][rc_path_capacity:0]u8 = undefined; + var fatal_rc_len: [2]usize = .{ 0, 0 }; + + /// Removes this process's private prompt files. Async-signal-safe (two + /// unlinks): SIGTERM and SIGHUP call it before the signal's death. + pub fn unlinkOwnedRcs() void { + for (&fatal_rc_len, 0..) |*len, i| { + const n = len.*; + if (n == 0) continue; + len.* = 0; + _ = libc.unlink(fatal_rcs[i][0..n :0].ptr); + } + } + + /// Removes /tmp's `pardes-osc133---XXXXXX` files whose pid + /// is gone (kill(pid, 0) answers ESRCH): what a killed or crashed + /// editor left. A live pid's, one of another user's, or a name of + /// another shape is left alone. + fn sweepDeadRcs() void { + const dir = std.c.opendir("/tmp") orelse return; + defer _ = std.c.closedir(dir); + var dead: [64][64]u8 = undefined; + var dead_len: [64]usize = undefined; + var n: usize = 0; + while (std.c.readdir(dir)) |ent| { + const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); + const pid = rcPid(name) orelse continue; + // This pid's are this process's, but in an upgraded one: those + // were its old image's (upgrade.zig), and its own come after. + if (pid == std.c.getpid() and @import("runtime").upgrade.resumed == null) continue; + if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; + if (name.len >= 64 or n == dead.len) continue; + @memcpy(dead[n][0..name.len], name); + dead_len[n] = name.len; + n += 1; + } + for (dead[0..n], dead_len[0..n]) |*entry, len| { + var path_buf: [80:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "/tmp/{s}", .{entry[0..len]}, 0) catch continue; + const facts = ninep_io.statNoFollow(path) orelse continue; + if (facts.mode & 0o170000 != 0o100000 or facts.uid != libc.getuid()) continue; + _ = libc.unlink(path.ptr); + } + } + + /// The pid in `pardes-osc133---XXXXXX`, or null. + fn rcPid(name: []const u8) ?std.c.pid_t { + const head = "pardes-osc133-"; + if (!std.mem.startsWith(u8, name, head)) return null; + var fields = std.mem.splitScalar(u8, name[head.len..], '-'); + _ = fields.next() orelse return null; // the shell + const digits = fields.next() orelse return null; + const rest = fields.next() orelse return null; + if (fields.next() != null or rest.len != 6 or digits.len == 0 or digits.len > 10) return null; + for (digits) |c| if (!std.ascii.isDigit(c)) return null; + const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null; + return if (pid > 0) pid else null; + } + + fn collectSystemPath(paths_file: [:0]const u8, paths_dir: []const u8, buf: []u8, len: *usize) void { + var file_buf: [path_capacity]u8 = undefined; + if (readSmall(paths_file, &file_buf)) |body| appendLines(buf, len, body); + + const io = std.Io.Threaded.global_single_threaded.io(); + var dir = std.Io.Dir.cwd().openDir(io, paths_dir, .{ .iterate = true }) catch return; + defer dir.close(io); + + var names: [max_path_files][256]u8 = undefined; + var name_lens: [max_path_files]usize = undefined; + var count: usize = 0; + var it = dir.iterate(); + while (count < names.len) { + const entry = (it.next(io) catch break) orelse break; + if (entry.kind == .directory) continue; + if (entry.name.len == 0 or entry.name.len > names[count].len) continue; + @memcpy(names[count][0..entry.name.len], entry.name); + name_lens[count] = entry.name.len; + count += 1; + } + var order: [max_path_files]usize = undefined; + for (0..count) |i| order[i] = i; + std.mem.sort(usize, order[0..count], Names{ .names = &names, .lens = &name_lens }, Names.lessThan); + + var path_buf: [512]u8 = undefined; + for (order[0..count]) |i| { + const name = names[i][0..name_lens[i]]; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ paths_dir, name }, 0) catch continue; + if (readSmall(path, &file_buf)) |body| appendLines(buf, len, body); + } + } + + const Names = struct { + names: *const [max_path_files][256]u8, + lens: *const [max_path_files]usize, + + fn lessThan(self: Names, a: usize, b: usize) bool { + return std.mem.order(u8, self.names[a][0..self.lens[a]], self.names[b][0..self.lens[b]]) == .lt; + } + }; + + fn appendLines(buf: []u8, len: *usize, body: []const u8) void { + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |raw| appendEntry(buf, len, std.mem.trim(u8, raw, " \t\r")); + } + + fn appendEntry(buf: []u8, len: *usize, entry: []const u8) void { + if (entry.len == 0) return; + if (hasEntry(buf[0..len.*], entry)) return; + const separator: usize = if (len.* == 0) 0 else 1; + if (len.* + separator + entry.len > buf.len) return; + if (separator == 1) { + buf[len.*] = ':'; + len.* += 1; + } + @memcpy(buf[len.*..][0..entry.len], entry); + len.* += entry.len; + } + + fn hasEntry(list: []const u8, entry: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, list, ':'); + while (it.next()) |have| if (std.mem.eql(u8, have, entry)) return true; + return false; + } + + fn allEntriesWithin(candidate: []const u8, list: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, candidate, ':'); + while (it.next()) |entry| if (!hasEntry(list, entry)) return false; + return true; + } + + fn readSmall(path: [:0]const u8, buf: []u8) ?[]const u8 { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return null; + defer _ = libc.close(fd); + var off: usize = 0; + while (off < buf.len) { + const n = libc.read(fd, buf[off..].ptr, buf.len - off); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return null; + } + if (n == 0) break; + off += @intCast(n); + } + return buf[0..off]; + } + + test "the launchd PATH is replaced and a configured one is left alone" { + var buf: [256]u8 = undefined; + var len: usize = 0; + appendEntry(&buf, &len, "/usr/bin"); + appendEntry(&buf, &len, "/bin"); + appendEntry(&buf, &len, "/usr/bin"); // already there: dedup keeps the first + appendEntry(&buf, &len, ""); + try std.testing.expectEqualStrings("/usr/bin:/bin", buf[0..len]); + + try std.testing.expect(allEntriesWithin("/usr/bin:/bin", "/usr/bin:/bin:/sbin")); + try std.testing.expect(allEntriesWithin("", "/usr/bin")); + try std.testing.expect(!allEntriesWithin("/Users/x/.cargo/bin:/usr/bin", "/usr/bin:/bin")); + try std.testing.expect(!allEntriesWithin("/opt/homebrew/bin", "/usr/bin:/bin")); + } + + test "system path files are sorted and duplicate directories keep their first position" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths", .data = " /usr/bin \n/bin\n\n/usr/bin\n" }); + try tmp.dir.createDirPath(std.testing.io, "paths.d"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/20-last", .data = "/opt/local/bin\n/usr/bin\n" }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/10-first", .data = "/opt/homebrew/bin\n/bin\n" }); + var root_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)]; + var file_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const paths_file = try std.fmt.bufPrintSentinel(&file_buf, "{s}/paths", .{root}, 0); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const paths_dir = try std.fmt.bufPrint(&dir_buf, "{s}/paths.d", .{root}); + var buf: [path_capacity]u8 = undefined; + var len: usize = 0; + collectSystemPath(paths_file, paths_dir, &buf, &len); + try std.testing.expectEqualStrings("/usr/bin:/bin:/opt/homebrew/bin:/opt/local/bin", buf[0..len]); + } + + const Family = enum { bash, fish, none }; + + fn family(bin: []const u8) Family { + const slash = std.mem.lastIndexOfScalar(u8, bin, '/'); + const base = if (slash) |s| bin[s + 1 ..] else bin; + if (std.mem.startsWith(u8, base, "bash")) return .bash; + if (std.mem.startsWith(u8, base, "fish")) return .fish; + return .none; + } + + /// `family`, for a shell whose name does not say it (a renamed copy, a + /// link named otherwise): what it really is, by the name its links end + /// at, else by the program itself -- bash's carries BASH_VERSINFO, fish's + /// fish_prompt. ponytail: a string scan of at most 16 MiB, once a spawn + /// and only for a name that says nothing; a --version probe would fork. + fn familyOf(path: [*:0]const u8) Family { + const named = family(std.mem.span(path)); + if (named != .none) return named; + // A name a POSIX shell answers to is that shell, whatever the file: + // bash run as `sh` is sh, and reads no --rcfile. + const bin = std.mem.span(path); + const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; + for ([_][]const u8{ "sh", "dash", "zsh", "ksh", "mksh", "yash", "nu", "elvish", "xonsh", "tcsh", "csh" }) |known| + if (std.mem.eql(u8, base, known)) return .none; + var real: [std.Io.Dir.max_path_bytes]u8 = undefined; + if (libc.realpath(path, &real)) |r| { + const by_link = family(std.mem.span(@as([*:0]const u8, @ptrCast(r)))); + if (by_link != .none) return by_link; + } + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return .none; + defer _ = libc.close(fd); + var chunk: [64 * 1024]u8 = undefined; + var carry: usize = 0; + var total: usize = 0; + while (total < 16 << 20) { + const n = libc.read(fd, chunk[carry..].ptr, chunk.len - carry); + if (n <= 0) break; + const have = carry + @as(usize, @intCast(n)); + total += @intCast(n); + // A script is no binary: its interpreter is what runs. + if (total == have and std.mem.startsWith(u8, chunk[0..have], "#!")) return .none; + if (std.mem.indexOf(u8, chunk[0..have], "BASH_VERSINFO") != null) return .bash; + if (std.mem.indexOf(u8, chunk[0..have], "fish_prompt") != null) return .fish; + // Keep the tail, so a marker cut by the chunk is still seen. + carry = @min(have, 16); + std.mem.copyForwards(u8, chunk[0..carry], chunk[have - carry .. have]); + } + return .none; + } + + test "a bash under another name is still told as bash" { + const bash: [:0]const u8 = "/usr/bin/bash"; + if (libc.access(bash, X_OK) != 0) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, bash, std.testing.allocator, .limited(16 << 20)); + defer std.testing.allocator.free(bytes); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mysh", .data = bytes, .flags = .{ .permissions = .executable_file } }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path: [4200:0]u8 = undefined; + const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0); + try std.testing.expectEqual(Family.bash, familyOf(p.ptr)); + try std.testing.expectEqual(Family.none, familyOf("/bin/sh")); + } + + const bash_rc = + \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc" + \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]' + \\PS2='\[\e]133;A;k=c;aid=pardes\a\]'"$PS2"'\[\e]133;B;aid=pardes\a\]' + \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}" + \\if ((BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 404)); then + \\ PS0='\e]133;C;aid=pardes\a'"$PS0" + \\else + \\ trap 'printf "\e]133;C;aid=pardes\a"' DEBUG + \\fi + \\ + ; + + // fish -C runs after config.fish; bash --rcfile must source .bashrc itself. + const fish_rc = + \\functions -c fish_prompt __pardes_user_prompt + \\function fish_prompt + \\ printf '\e]133;A;cl=line;aid=pardes\a' + \\ __pardes_user_prompt + \\ printf '\e]133;B;aid=pardes\a' + \\end + \\function __pardes_preexec --on-event fish_preexec + \\ printf '\e]133;C;aid=pardes\a' + \\end + \\function __pardes_postexec --on-event fish_postexec + \\ printf '\e]133;D;%s;aid=pardes\a' $status + \\end + \\ + ; + + const rc_path_capacity = 256; + + /// The prompt files a shell sources at start. Under $XDG_RUNTIME_DIR + /// (private to the user) there is one file per content, named by its + /// hash and shared by every pardes, so none is left behind by a pardes + /// that was killed: 72K of them piled up in /tmp when each host wrote + /// its own. Without that directory each host writes private mkstemp + /// files in /tmp and removes them at teardown, as before. + pub const PromptFiles = struct { + bash_path: [rc_path_capacity:0]u8 = @splat(0), + bash_len: u16 = 0, + bash_owned: bool = false, + fish_path: [rc_path_capacity:0]u8 = @splat(0), + fish_len: u16 = 0, + fish_owned: bool = false, + fish_command: [rc_path_capacity + "source ''".len:0]u8 = @splat(0), + fish_command_len: u16 = 0, + + pub fn init() PromptFiles { + var rcs: PromptFiles = .{}; + const bash = place(&rcs.bash_path, "bash", bash_rc); + rcs.bash_len = bash.len; + rcs.bash_owned = bash.owned; + const fish = place(&rcs.fish_path, "fish", fish_rc); + rcs.fish_len = fish.len; + rcs.fish_owned = fish.owned; + if (rcs.fishPath()) |path| { + // Quoted for fish; a path a quote would break is not used. + const command = if (std.mem.indexOfAny(u8, path, "'\\") != null) + error.NoSpaceLeft + else + std.fmt.bufPrintSentinel(&rcs.fish_command, "source '{s}'", .{path}, 0); + const ok = command catch { + if (rcs.fish_owned) _ = libc.unlink(path.ptr); + rcs.fish_len = 0; + return rcs; + }; + rcs.fish_command_len = @intCast(ok.len); + } + return rcs; + } + + pub fn deinit(rcs: *PromptFiles) void { + // Removed here, not again by a signal's handler. + for (&fatal_rc_len, 0..) |*len, i| for ([_]?[:0]const u8{ rcs.bashPath(), rcs.fishPath() }) |mine| { + if (mine) |path| if (len.* == path.len and std.mem.eql(u8, fatal_rcs[i][0..len.*], path)) { + len.* = 0; + }; + }; + if (rcs.bashPath()) |path| if (rcs.bash_owned) { + _ = libc.unlink(path.ptr); + }; + if (rcs.fishPath()) |path| if (rcs.fish_owned) { + _ = libc.unlink(path.ptr); + }; + rcs.bash_len = 0; + rcs.fish_len = 0; + rcs.fish_command_len = 0; + } + + fn bashPath(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.bash_len == 0) return null; + return rcs.bash_path[0..rcs.bash_len :0]; + } + + fn fishPath(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.fish_len == 0) return null; + return rcs.fish_path[0..rcs.fish_len :0]; + } + + fn fishCommand(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.fish_command_len == 0) return null; + return rcs.fish_command[0..rcs.fish_command_len :0]; + } + }; + + /// The shared file for `contents` under $XDG_RUNTIME_DIR, written + /// beside it and renamed into place when missing or different, so a + /// shell never reads half of one; failing that, a private /tmp file. + fn place(path_buf: *[rc_path_capacity:0]u8, name: []const u8, contents: []const u8) struct { len: u16, owned: bool } { + shared: { + const dir = std.mem.span(std.c.getenv("XDG_RUNTIME_DIR") orelse break :shared); + if (dir.len == 0 or dir[0] != '/') break :shared; + const final = std.fmt.bufPrintSentinel(path_buf, "{s}/pardes-osc133-{s}-{x:0>16}", .{ dir, name, std.hash.Wyhash.hash(0, contents) }, 0) catch break :shared; + var have: [2048]u8 = undefined; + if (readSmall(final, &have)) |got| if (std.mem.eql(u8, got, contents)) return .{ .len = @intCast(final.len), .owned = false }; + var tmp_buf: [rc_path_capacity:0]u8 = @splat(0); + var template_buf: [rc_path_capacity]u8 = undefined; + const tmp_template = std.fmt.bufPrint(&template_buf, "{s}.XXXXXX", .{final}) catch break :shared; + const n = stage(&tmp_buf, tmp_template, contents); + if (n == 0) break :shared; + if (libc.rename(tmp_buf[0..n :0].ptr, final.ptr) != 0) { + _ = libc.unlink(tmp_buf[0..n :0].ptr); + break :shared; + } + return .{ .len = @intCast(final.len), .owned = false }; + } + var tmp_template: [64]u8 = undefined; + // Its pid in the name: one a killed editor left is swept by the + // next (sweepDeadRcs). + const template = std.fmt.bufPrint(&tmp_template, "/tmp/pardes-osc133-{s}-{d}-XXXXXX", .{ name, @as(u32, @intCast(std.c.getpid())) }) catch return .{ .len = 0, .owned = false }; + return .{ .len = stage(path_buf, template, contents), .owned = true }; + } + + // Publish a path only after its private 0600 file is fully written and closed. + fn stage(path_buf: *[rc_path_capacity:0]u8, template: []const u8, contents: []const u8) u16 { + const path = std.fmt.bufPrintSentinel(path_buf, "{s}", .{template}, 0) catch return 0; + const fd = mkstemp(path.ptr); + if (fd < 0) return 0; + if (!writeFd(fd, contents)) { + _ = libc.close(fd); + _ = libc.unlink(path.ptr); + return 0; + } + if (libc.close(fd) != 0) { + _ = libc.unlink(path.ptr); + return 0; + } + return @intCast(path.len); + } + + test "shell family is the basename's prefix, and anything else runs unadorned" { + try std.testing.expectEqual(Family.fish, family("fish")); + try std.testing.expectEqual(Family.fish, family("/usr/bin/fish")); + try std.testing.expectEqual(Family.fish, family("/opt/homebrew/bin/fish")); + try std.testing.expectEqual(Family.bash, family("bash")); + try std.testing.expectEqual(Family.bash, family("/bin/bash")); + try std.testing.expectEqual(Family.bash, family("/usr/bin/bash-5.2")); + try std.testing.expectEqual(Family.fish, family("/usr/local/bin/fish-3.7")); + try std.testing.expectEqual(Family.none, family("/opt/fish/bin/nu")); + try std.testing.expectEqual(Family.none, family("/usr/bin/zsh")); + try std.testing.expectEqual(Family.none, family("/bin/sh")); + try std.testing.expectEqual(Family.none, family("nu")); + try std.testing.expectEqual(Family.none, family("")); + } + + const bin_dirs = [_][]const u8{ + "/usr/bin/", + "/bin/", + "/usr/local/bin/", + "/opt/homebrew/bin/", + "/opt/local/bin/", + "/usr/sbin/", + }; + + const fallbacks = [_][]const u8{ + if (builtin.os.tag == .linux) "/usr/bin/bash" else "/bin/bash", + "/bin/sh", + }; + + pub const Spawn = struct { + path: [*:0]const u8, + argv: [6:null]?[*:0]const u8, + }; + + // Resolve in the parent. The path buffer and prompt files must survive through exec. + pub fn resolve(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8, prompt_rcs: *const PromptFiles) Spawn { + const path = find(bin, buf) orelse fallback(buf); + const marks: [2]?[*:0]const u8 = switch (familyOf(path)) { + .bash => if (prompt_rcs.bashPath()) |rc| .{ "--rcfile", rc.ptr } else .{ null, null }, + .fish => if (prompt_rcs.fishCommand()) |command| .{ "-C", command.ptr } else .{ null, null }, + .none => .{ null, null }, + }; + return .{ .path = path, .argv = .{ path, marks[0], marks[1], null, null, null } }; + } + + /// A command pane's shell runs its one line with job control on, so a + /// job the line puts in the background has a process group of its own. + /// The shell leads the terminal's session, and when it exits the kernel + /// hangs up the terminal's foreground group: with job control off that + /// is the shell's own, the job's too, and the job died with the command + /// (nohup'd or not; only setsid got out, and not always in time). A + /// shell pardes does not know runs the line as it is. + pub fn commandArgv(path: [*:0]const u8, line: [*:0]const u8) [6:null]?[*:0]const u8 { + const bin = std.mem.span(path); + const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; + const posix_shells = [_][]const u8{ "bash", "sh", "dash", "zsh", "ksh", "mksh", "yash" }; + for (posix_shells) |name| if (std.mem.eql(u8, base, name)) + return .{ path, "-m", "-c", line, null, null }; + if (family(bin) == .fish) return .{ path, "-C", "status job-control full", "-c", line, null }; + return .{ path, "-c", line, null, null, null }; + } + + /// A shell by its path or its name in the usual directories, or null. + /// A path may be under a mount this editor serves: the turn goes out + /// with the lookups (pardes.Turn.yield). + pub fn find(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[*:0]const u8 { + if (bin.len == 0 or bin.len + 1 > buf.len) return null; + pardes.turn.yield(); + defer pardes.turn.back(); + if (std.mem.indexOfScalar(u8, bin, '/') != null) { + @memcpy(buf[0..bin.len], bin); + buf[bin.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + return if (libc.access(p, X_OK) == 0 and !isDirectory(p)) p else null; + } + for (bin_dirs) |dir| { + if (dir.len + bin.len + 1 > buf.len) continue; + @memcpy(buf[0..dir.len], dir); + @memcpy(buf[dir.len..][0..bin.len], bin); + buf[dir.len + bin.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + if (libc.access(p, X_OK) == 0) return p; + } + return null; + } + + /// A directory passes access(X_OK) (it can be searched): no shell. + pub fn isDirectory(path: [*:0]const u8) bool { + const d = libc.opendir(path) orelse return false; + _ = libc.closedir(d); + return true; + } + + /// 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.Io.Dir.max_path_bytes]u8 = undefined; + if (find(bin, &buf)) |found| { + // A script whose `#!` names a program that is not there: its + // exec fails ENOENT as a missing shell's does, so told apart. + var interp: [256]u8 = undefined; + const missing = missingInterpreter(found, &interp) orelse return null; + return std.fmt.bufPrint(said, "interpreter {s} not found", .{missing}) catch "interpreter not found"; + } + if (std.mem.indexOfScalar(u8, bin, '/') != null and bin.len < buf.len) { + @memcpy(buf[0..bin.len], bin); + buf[bin.len] = 0; + if (isDirectory(@ptrCast(&buf))) return std.fmt.bufPrint(said, "not a shell: {s} is a directory", .{bin}) catch "not a shell: a directory"; + // There, but no program: said so, not "not found". + if (libc.access(@ptrCast(&buf), 0) == 0) return std.fmt.bufPrint(said, "not a shell: {s} is not executable", .{bin}) catch "not a shell: not executable"; + } + // "not found": the words a mount reads as ENOENT. + return std.fmt.bufPrint(said, "shell \"{s}\" not found (a name on the usual paths, or a path to one)", .{bin}) catch "no such shell"; + } + + /// The program a script's `#!` line names, when it is not there to + /// run; null for a script whose interpreter is there, or no script. + pub fn missingInterpreter(path: [*:0]const u8, out: []u8) ?[]const u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return null; + defer _ = libc.close(fd); + var head: [256]u8 = undefined; + const n = libc.read(fd, &head, head.len); + if (n < 2) return null; + const got = head[0..@intCast(n)]; + if (!std.mem.startsWith(u8, got, "#!")) return null; + const line = got[2 .. std.mem.indexOfScalar(u8, got, '\n') orelse got.len]; + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + const interp = words.next() orelse return null; + if (interp.len + 1 > out.len) return null; + @memcpy(out[0..interp.len], interp); + out[interp.len] = 0; + if (libc.access(@ptrCast(out.ptr), X_OK) == 0) return null; + return out[0..interp.len]; + } + + test "a script whose #! names a program not there is told apart from a missing shell" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp -x\n", .flags = .{ .permissions = .executable_file } }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "good", .data = "#!/bin/sh\n", .flags = .{ .permissions = .executable_file } }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path: [4200]u8 = undefined; + var said: [320]u8 = undefined; + try std.testing.expectEqualStrings("interpreter /no/such/interp not found", refusal(try std.fmt.bufPrint(&path, "{s}/bad", .{dir}), &said).?); + try std.testing.expect(refusal(try std.fmt.bufPrint(&path, "{s}/good", .{dir}), &said) == null); + try std.testing.expect(std.mem.startsWith(u8, refusal(try std.fmt.bufPrint(&path, "{s}/none", .{dir}), &said).?, "shell \"")); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain", .data = "echo\n" }); + const plain = try std.fmt.bufPrint(&path, "{s}/plain", .{dir}); + try std.testing.expect(std.mem.endsWith(u8, refusal(plain, &said).?, "plain is not executable")); + } + + fn fallback(buf: *[std.Io.Dir.max_path_bytes]u8) [*:0]const u8 { + for (fallbacks) |f| { + @memcpy(buf[0..f.len], f); + buf[f.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + if (libc.access(p, X_OK) == 0) return p; + } + return @ptrCast(buf); + } + + test "a command pane's line runs with job control on in the shells that have it" { + const want = struct { + fn check(path: [*:0]const u8, words: []const []const u8) !void { + const argv = commandArgv(path, "sleep 9 &"); + for (words, 0..) |w, i| try std.testing.expectEqualStrings(w, std.mem.span(argv[i].?)); + try std.testing.expect(argv[words.len] == null); + } + }; + try want.check("/usr/bin/bash", &.{ "/usr/bin/bash", "-m", "-c", "sleep 9 &" }); + try want.check("/bin/sh", &.{ "/bin/sh", "-m", "-c", "sleep 9 &" }); + try want.check("/usr/bin/fish", &.{ "/usr/bin/fish", "-C", "status job-control full", "-c", "sleep 9 &" }); + try want.check("/usr/bin/nu", &.{ "/usr/bin/nu", "-c", "sleep 9 &" }); + } + + test "a path is taken at its word, a name is looked up, and both pick their own marks" { + if (builtin.os.tag == .windows) return; + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var prompt_rcs = PromptFiles.init(); + defer prompt_rcs.deinit(); + + const sh = resolve("/bin/sh", &buf, &prompt_rcs); + try std.testing.expectEqualStrings("/bin/sh", std.mem.span(sh.path)); + try std.testing.expect(sh.argv[1] == null); + + const bash = resolve("bash", &buf, &prompt_rcs); + try std.testing.expect(family(std.mem.span(bash.path)) == .bash); + try std.testing.expectEqualStrings("--rcfile", std.mem.span(bash.argv[1].?)); + try std.testing.expectEqualStrings(prompt_rcs.bashPath().?, std.mem.span(bash.argv[2].?)); + + const missing = resolve("zznosuchshell", &buf, &prompt_rcs); + try std.testing.expect(!std.mem.eql(u8, "zznosuchshell", std.mem.span(missing.path))); + try std.testing.expect(libc.access(missing.path, X_OK) == 0); + + const gone = resolve("/zz/no/such/shell", &buf, &prompt_rcs); + try std.testing.expect(libc.access(gone.path, X_OK) == 0); + } + + test "a private prompt file names its pid, and a dead pid's is swept while a live one's stays" { + if (builtin.os.tag == .windows) return; + const dead = "/tmp/pardes-osc133-bash-2147483647-AbCdEf"; + var live_buf: [80:0]u8 = undefined; + const live = try std.fmt.bufPrintSentinel(&live_buf, "/tmp/pardes-osc133-bash-{d}-AbCdEf", .{@as(u32, @intCast(std.c.getppid()))}, 0); + defer for ([_][:0]const u8{ dead, live }) |path| { + _ = libc.unlink(path.ptr); + }; + for ([_][:0]const u8{ dead, live }) |path| { + const fd = libc.open(path, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600)); + if (fd < 0) return error.SkipZigTest; + _ = libc.close(fd); + } + sweepDeadRcs(); + try std.testing.expect(libc.access(dead, 0) < 0); + try std.testing.expect(libc.access(live, 0) == 0); + // The pid is read only from that shape: an older name has none. + try std.testing.expectEqual(@as(?std.c.pid_t, 42), rcPid("pardes-osc133-fish-42-Xy12Zq")); + try std.testing.expectEqual(@as(?std.c.pid_t, null), rcPid("pardes-osc133-bash-01z3XK")); + } + + test "prompt files are one per content under the runtime dir, or private and cleaned up without it" { + if (builtin.os.tag == .windows) return; + var saved_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); + const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; + defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); + const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf); + _ = setenv("XDG_RUNTIME_DIR", dir_buf[0..dir_len :0].ptr, 1); + + // Shared: the same file for every owner, left in place, rewritten + // whole when what is there is not its content. + var a = PromptFiles.init(); + var b = PromptFiles.init(); + const a_bash = a.bashPath() orelse return error.TempCreateFailed; + try std.testing.expectEqualStrings(a_bash, b.bashPath().?); + try std.testing.expect(std.mem.startsWith(u8, a_bash, dir_buf[0..dir_len])); + const fish_command = a.fishCommand() orelse return error.MissingFishCommand; + var want: [rc_path_capacity + 16]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "source '{s}'", .{a.fishPath().?}), fish_command); + var buf: [2048]u8 = undefined; + try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed); + try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed); + const stat = try @import("core").filesystem.statPath(std.testing.io, a_bash, .{}); + try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077); + var kept: [rc_path_capacity:0]u8 = @splat(0); + @memcpy(kept[0..a_bash.len], a_bash); + a.deinit(); + b.deinit(); + try std.testing.expect(libc.access(&kept, 0) == 0); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = std.Io.Dir.path.basename(kept[0..a_bash.len]), .data = "half" }); + var c = PromptFiles.init(); + defer c.deinit(); + try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); + + // No runtime dir: private files, one per owner, gone at teardown. + _ = testUnsetenv("XDG_RUNTIME_DIR"); + var d = PromptFiles.init(); + var e = PromptFiles.init(); + defer e.deinit(); + const d_bash = d.bashPath() orelse return error.TempCreateFailed; + try std.testing.expect(!std.mem.eql(u8, d_bash, e.bashPath().?)); + try std.testing.expect(std.mem.startsWith(u8, d_bash, "/tmp/pardes-osc133-bash-")); + try std.testing.expectEqual(@as(?std.c.pid_t, std.c.getpid()), rcPid(std.Io.Dir.path.basename(d_bash))); + @memcpy(kept[0..d_bash.len], d_bash); + kept[d_bash.len] = 0; + d.deinit(); + try std.testing.expect(libc.access(&kept, 0) < 0); + } +}; + +/// In a child between fork and exec: every signal back to its default and +/// none blocked, whatever this process ignores or blocks (the tty's SIGWINCH, +/// a SIGHUP nohup ignored). A handler resets at exec by itself; an ignored +/// signal and the mask do not. Async-signal-safe: sigaction and sigprocmask. +pub fn resetChildSignals() void { + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + var sig: u8 = 1; + while (sig < 65) : (sig += 1) { + if (sig == @backingInt(posix.SIG.KILL) or sig == @backingInt(posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); + } + const none = posix.sigemptyset(); + posix.sigprocmask(posix.SIG.SETMASK, &none, null); +} + +extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int; +extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn chdir(path: [*:0]const u8) c_int; +extern "c" fn _exit(status: c_int) noreturn; + +pub const Child = struct { + file: std.Io.File, + pid: posix.pid_t, +}; + +/// The environment a pty child is handed: everything this process carries, +/// with the terminal's own identity written over whatever the launcher left +/// behind. The child is talking to the bundled VT, never to the terminal +/// pardes itself was started from, and a macOS `.app` launch supplies no +/// `TERM` at all — which is exactly why `clear` fails there, why nothing +/// paints a colour, and why every cursor-addressing program falls back to a +/// dumb line-at-a-time mode. +pub const ChildEnv = struct { + /// Entries pardes owns. The name of each is read back out of its own + /// spelling, so there is one place to edit and no second list to drift. + const own = [_][*:0]const u8{ + "TERM=" ++ pardes.config.child_term, + "COLORTERM=" ++ pardes.config.child_colorterm, + "TERM_PROGRAM=" ++ pardes.config.child_term_program, + }; + + /// What this editor tells its children of itself (exportEnv, `$winid`), + /// kept here rather than set into this process's environment: std's Io read + /// that block at startup, and setenv/unsetenv rewrite it in place under it + /// (a spawn then scans a null inside it). `build` puts each exported one in + /// place of an inherited variable of its name; a cleared one hides it; one + /// never exported is inherited as it is. + pub const exported_names = [_][]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "winid" }; + var exported_state: [exported_names.len]enum { inherited, cleared, set } = @splat(.inherited); + var exported_line: [exported_names.len][pardes.memory.limits.host_path_cap + 64:0]u8 = undefined; + + /// Set (or, null, clear) what children are told for `var_name`. + pub fn exportVar(var_name: []const u8, value: ?[]const u8) void { + const i = exportedIndex(var_name).?; + const v = value orelse { + exported_state[i] = .cleared; + return; + }; + _ = std.fmt.bufPrintSentinel(&exported_line[i], "{s}={s}", .{ var_name, v }, 0) catch { + exported_state[i] = .cleared; + return; + }; + exported_state[i] = .set; + } + + /// What children are told for `var_name`, as `exportVar` left it; null + /// when cleared or never exported. + pub fn exported(var_name: []const u8) ?[]const u8 { + const i = exportedIndex(var_name) orelse return null; + if (exported_state[i] != .set) return null; + return std.mem.span(@as([*:0]const u8, &exported_line[i]))[var_name.len + 1 ..]; + } + + fn exportedIndex(var_name: []const u8) ?usize { + for (exported_names, 0..) |n, i| if (std.mem.eql(u8, n, var_name)) return i; + return null; + } + + /// Wide enough for any real environment; `build` answers null rather than + /// truncate, because a child missing half its variables is a worse bug + /// than one missing TERM, and the caller then execs with `environ` intact. + pub const Slots = [1024]?[*:0]const u8; + + fn name(entry: [*:0]const u8) []const u8 { + const line = std.mem.span(entry); + return line[0 .. std.mem.indexOfScalar(u8, line, '=') orelse line.len]; + } + + /// Which pager a child is given where the user's environment names none: + /// a command pane's one-shot shell `cat` (its output is a pane already), + /// a terminal's shell `pardes -` (a +Pager pane). + pub const Paging = enum { command, terminal }; + + pub fn build(slots: *Slots, paging: Paging) ?[*:null]const ?[*:0]const u8 { + var n: usize = 0; + var i: usize = 0; + while (libc.environ[i]) |entry| : (i += 1) { + const inherited = name(entry); + const shadowed = for (own) |mine| { + if (std.mem.eql(u8, inherited, name(mine))) break true; + } else false; + if (shadowed) continue; + if (exportedIndex(inherited)) |e| if (exported_state[e] != .inherited) continue; + if (n + own.len + exported_names.len + 1 > slots.len) return null; + slots[n] = entry; + n += 1; + } + // No pager to wait in (less holds a run at its first screen for + // ever): a command pane's output is read whole, through cat; a + // terminal's goes to a +Pager pane. Only where the inherited + // environment chose none. + const defaults: []const [*:0]const u8 = switch (paging) { + .command => &cat_pagers, + .terminal => pardesPagers(), + }; + for (defaults) |default| { + const set = for (libc.environ[0..i]) |entry| { + if (std.mem.eql(u8, name(entry.?), name(default))) break true; + } else false; + if (set) continue; + if (n + own.len + exported_names.len + 4 > slots.len) return null; + slots[n] = default; + n += 1; + } + for (&exported_line, exported_state) |*line, state| if (state == .set) { + slots[n] = line; + n += 1; + }; + for (own) |mine| { + slots[n] = mine; + n += 1; + } + slots[n] = null; + return @ptrCast(slots); + } + + const cat_pagers = [_][*:0]const u8{ "PAGER=cat", "GIT_PAGER=cat" }; + + /// `PAGER=' -'`, its own path so no PATH lookup can find + /// another; plain `pardes -` where the path cannot be read or quoted. + fn pardesPagers() []const [*:0]const u8 { + const S = struct { + var pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; + var git_pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; + var systemd_pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; + var entries: [4][*:0]const u8 = undefined; + var ready = false; + }; + if (!S.ready) { + var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var quoted_buf: [std.Io.Dir.max_path_bytes + 2]u8 = undefined; + const n = if (comptime builtin.os.tag == .linux) libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len) else -1; + const exe: []const u8 = if (n > 0 and @as(usize, @intCast(n)) < exe_buf.len) exe_buf[0..@intCast(n)] else "pardes"; + const command = pagerCommand(exe, "ed_buf); + S.entries[0] = if (std.fmt.bufPrintSentinel(&S.pager, "PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "PAGER=pardes -"; + S.entries[1] = if (std.fmt.bufPrintSentinel(&S.git_pager, "GIT_PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "GIT_PAGER=pardes -"; + // systemd's tools (journalctl, systemctl) read their own, and + // in their secure mode run only less: this pager has no shell + // to escape to, so secure mode buys nothing. + S.entries[2] = if (std.fmt.bufPrintSentinel(&S.systemd_pager, "SYSTEMD_PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "SYSTEMD_PAGER=pardes -"; + S.entries[3] = "SYSTEMD_PAGERSECURE=0"; + S.ready = true; + } + return &S.entries; + } + + /// The pager's path as a command line takes it: as it is when it needs + /// no quoting (systemd splits on blanks and execs, never through sh), + /// in single quotes when it holds a blank or a shell character, plain + /// `pardes` when even that cannot hold it. + fn pagerCommand(exe: []const u8, buf: []u8) []const u8 { + const plain = for (exe) |c| { + if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "/._+-,@%=:", c) != null)) break false; + } else true; + if (plain) return exe; + if (std.mem.indexOfScalar(u8, exe, '\'') != null) return "pardes"; + return std.fmt.bufPrint(buf, "'{s}'", .{exe}) catch "pardes"; + } +}; + +extern "c" fn unsetenv(name: [*:0]const u8) c_int; + +/// For tests: unset `name` without compacting the environment block std +/// captured at startup (std.testing.environ and Io's spawns read it later). A +/// new variable first moves glibc's `environ` to a heap copy, which unsetenv +/// then compacts instead. Runtime code never changes this process's +/// environment (ChildEnv.exportVar). +pub fn testUnsetenv(name: [*:0]const u8) c_int { + _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); + return unsetenv(name); +} + +/// The environment a pane's command is given (exportEnv, `$winid`, +/// ChildEnv), as `NAME=value` lines in `arena`, for a command that is not a +/// pane's: an Edit's filters, run from pane `serial`. +pub fn commandEnv(arena: std.mem.Allocator, serial: u32, adopts: bool) ![]const []const u8 { + ninep_io.exportEnv(serial, adopts); + exportWinid(serial); + var slots: ChildEnv.Slots = undefined; + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; + var out: std.ArrayList([]const u8) = .empty; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) try out.append(arena, try arena.dupe(u8, std.mem.span(entry))); + return out.items; +} + +fn exportWinid(serial: u32) void { + var buf: [16]u8 = undefined; + ChildEnv.exportVar("winid", if (serial == 0) null else std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); // a u32 fits 16 +} + +/// The longest line a command pane runs (exec.zig refuses a longer one). +pub const exec_command_max = pardes.exec.command_max; + +/// A pane's pty size, in cells and in pixels: a program sizes its kitty +/// graphics by the pixels (yazi's previews; pardes nested in a pane). +pub fn ptyWinsize(core: ?*const pardes.Pardes, cols: u16, rows: u16) posix.winsize { + var ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; + if (core) |c| { + ws.xpixel = std.math.cast(u16, @as(u32, cols) * c.view().cell_pixels.w) orelse 0; + ws.ypixel = std.math.cast(u16, @as(u32, rows) * c.view().cell_pixels.h) orelse 0; + } + return ws; +} + +pub fn forkShell( + core: ?*pardes.Pardes, + pane: usize, + prompt_rcs: *const Shell.PromptFiles, + bin: []const u8, + cwd: []const u8, + rows: u16, + cols: u16, +) !Child { + const native_cwd = filesystem.localPath(cwd) orelse cwd; + if (std.mem.indexOfScalar(u8, native_cwd, 0) != null) return error.InvalidPath; + var cwd_buf: [4096]u8 = undefined; + const serial = if (core) |c| if (c.panes[pane]) |pn| pn.serial else 0 else 0; + const cwd_z: ?[:0]const u8 = if (native_cwd.len == 0) null else dir: { + const path = std.fmt.bufPrintSentinel(&cwd_buf, "{s}", .{native_cwd}, 0) catch return error.NameTooLong; + // A shell's directory may be inside a mount this editor serves. + pardes.turn.yield(); + defer pardes.turn.back(); + const stat = try @import("core").filesystem.statPath(std.Io.Threaded.global_single_threaded.io(), path, .{}); + if (stat.kind != .directory) return error.NotDir; + break :dir path; + }; + var master: c_int = -1; + var path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + // 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; + if (core) |c| if (c.panes[pane]) |pn| if (pn.shell) |name| { + const n = @min(name.len, own_buf.len); + @memcpy(own_buf[0..n], name[0..n]); + own = own_buf[0..n]; + }; + var spawn = Shell.resolve(own orelse bin, &path_buf, prompt_rcs); + // The turn was given up for the stat and the lookup: a 9P client may + // have closed the pane, and another taken its slot, whose command this + // is not. + if (core) |c| if ((if (c.panes[pane]) |pn| pn.serial else 0) != serial) return error.PaneGone; + // A command pane's child is the shell running its one line, which has + // no prompt to mark (exec.zig runCommand). + const one_line = if (core) |c| if (c.panes[pane]) |pn| pn.command else null else null; + var command_buf: [exec_command_max + 1]u8 = undefined; + if (one_line) |line| { + if (line.len > exec_command_max or std.mem.indexOfScalar(u8, line, 0) != null) return error.InvalidCommand; + @memcpy(command_buf[0..line.len], line); + command_buf[line.len] = 0; + spawn.argv = Shell.commandArgv(spawn.path, command_buf[0..line.len :0].ptr); + } + ninep_io.exportEnv( + if (core) |c| (if (c.panes[pane]) |pn| pn.serial else 0) else 0, + if (core) |c| !c.opts.nested else false, + ); + // acme's `$winid`: the pane a command was run from, so a script it runs + // can address that pane; unset for a shell and a header tag's command. + exportWinid(if (core) |c| (if (c.panes[pane]) |pn| (if (pn.command != null) pn.command_from else 0) else 0) else 0); + // Built here and not after the fork: between fork and exec the child may + // not call setenv, whose malloc can deadlock against a pty reader thread + // that held the heap when the fork took its snapshot. + var env_slots: ChildEnv.Slots = undefined; + const pages = if (core) |c| if (c.panes[pane]) |pn| pn.command_pages else false else false; + const paging: ChildEnv.Paging = if (one_line != null and !pages) + .command + else + .terminal; + const envp = ChildEnv.build(&env_slots, paging); + const ws = ptyWinsize(core, cols, rows); + // The child says here why it could not become the shell (its chdir or + // its exec failed, as for a script whose interpreter is not there): the + // pipe closes on exec, so the parent reads nothing when the shell runs, + // and a reason when it did not, before anyone is told it started. + var told: [2]c_int = .{ -1, -1 }; + // pipe and then CLOEXEC, not pipe2, which macOS has not. + if (libc.pipe(&told) != 0) return error.PipeFailed; + ninep_io.setCloexec(told[0]); + ninep_io.setCloexec(told[1]); + const pid = forkpty(&master, null, null, &ws); + if (pid < 0) { + _ = libc.close(told[0]); + _ = libc.close(told[1]); + return error.ForkFailed; + } + if (pid == 0) { + resetChildSignals(); + if (cwd_z) |path| if (chdir(path.ptr) != 0) { + const why = [_]u8{ 'c', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; + _ = libc.write(told[1], &why, why.len); + _exit(126); + }; + if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); + _ = execv(spawn.path, &spawn.argv); + const why = [_]u8{ 'x', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; + _ = libc.write(told[1], &why, why.len); + _exit(127); + } + _ = libc.close(told[1]); + const failed = failed: { + var why: [2]u8 = undefined; + pardes.turn.yield(); + defer pardes.turn.back(); + const n = libc.read(told[0], &why, why.len); + _ = libc.close(told[0]); + if (n != 2) break :failed null; + break :failed why; + }; + if (failed) |why| { + _ = libc.close(master); + _ = libc.waitpid(pid, null, 0); + const e: libc.E = @fromBackingInt(@intCast(why[1])); + if (why[0] == 'c') return if (e == .NOENT or e == .NOTDIR) error.FileNotFound else error.AccessDenied; + return switch (e) { + // Itself, or its script's interpreter: told apart by whether it + // is there. + .NOENT => if (libc.access(spawn.path, 0) == 0) error.InterpreterNotFound else error.ShellNotFound, + .ACCES, .PERM => error.ShellNotExecutable, + .NOEXEC => error.ShellNotExecutable, + else => error.ShellDidNotStart, + }; + } + ninep_io.setCloexec(master); + // The daemon keeps a dup: this session killed outright never hangs the + // shell up (daemon.zig). + @import("runtime").daemon.pty(pid, master); + if (core) |c| c.acknowledgeShell(pane, std.mem.span(spawn.path), one_line == null and spawn.argv[1] != null); + return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; +} + +pub fn writeFd(fd: c_int, data: []const u8) bool { + var off: usize = 0; + while (off < data.len) { + const n = libc.write(fd, data[off..].ptr, data.len - off); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return false; + } + if (n == 0) return false; + off += @intCast(n); + } + return true; +} + +const vnode_info_path = extern struct { + vi: [152]u8 align(8), // struct vnode_info: vinfo_stat + type + pad + fsid + path: [1024]u8, // MAXPATHLEN +}; +const proc_vnodepathinfo = extern struct { + cdir: vnode_info_path, + rdir: vnode_info_path, +}; +const PROC_PIDVNODEPATHINFO: c_int = 9; +extern "c" fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *anyopaque, buffersize: c_int) c_int; + +/// Whether an adopted shell marks its prompts: one pardes started with its +/// prompt files (bash, zsh, fish), which a pane's runs wait on. +pub fn marksPrompts(pid: libc.pid_t) bool { + var buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const exe = std.Io.Dir.path.basename(processExe(pid, &buf) orelse return false); + for ([_][]const u8{ "bash", "zsh", "fish" }) |shell| if (std.mem.eql(u8, exe, shell)) return true; + return false; +} + +/// The program `pid` runs, where the system says (an adopted shell's, for +/// 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 + return if (n > 1) buf[0 .. n - 1] else null; + } + if (comptime builtin.os.tag != .linux) return null; + var pbuf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/exe", .{pid}, 0) catch unreachable; // a pid fits 64 + const n = libc.readlink(path, buf.ptr, buf.len); + if (n <= 0 or n >= buf.len) return null; + return buf[0..@intCast(n)]; +} + +pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { + switch (builtin.os.tag) { + .linux => { + var pbuf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/cwd", .{pid}, 0) catch unreachable; // a pid fits 64 + const n = libc.readlink(path, buf.ptr, buf.len); + if (n <= 0 or n >= buf.len) return null; + const link = buf[0..@intCast(n)]; + // A directory removed under the shell reads ` (deleted)`: + // no directory to be named by, so the name it had stays, and a + // restart works there once it is back. + if (std.mem.endsWith(u8, link, " (deleted)")) { + _ = @import("core").filesystem.statPath(std.Io.Threaded.global_single_threaded.io(), link, .{}) catch return null; + } + return link; + }, + .macos, .ios, .tvos, .watchos, .visionos => { + var info: proc_vnodepathinfo = undefined; + const n = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, @sizeOf(proc_vnodepathinfo)); + if (n < @as(c_int, @sizeOf(proc_vnodepathinfo))) return null; + const path = std.mem.sliceTo(&info.cdir.path, 0); + if (path.len == 0 or path.len == info.cdir.path.len or path.len > buf.len) return null; + @memcpy(buf[0..path.len], path); + return buf[0..path.len]; + }, + .freebsd => { + // A struct kinfo_file (sys/user.h), its last 1024 bytes the path. + var kf: [1392]u8 align(8) = undefined; + const n = kernProc(pid, 42, &kf) orelse return null; // KERN_PROC_CWD + if (n <= 368) return null; + const path = std.mem.sliceTo(kf[368..n], 0); + if (path.len == 0 or path.len >= buf.len) return null; + @memcpy(buf[0..path.len], path); + return buf[0..path.len]; + }, + else => return null, + } +} + +/// FreeBSD's kern.proc.. into `buf`: the bytes it wrote. +fn kernProc(pid: libc.pid_t, what: c_int, buf: []u8) ?usize { + const mib = [_]c_int{ 1, 14, what, pid }; // CTL_KERN, KERN_PROC + var len: usize = buf.len; + if (libc.sysctl(&mib, mib.len, buf.ptr, &len, null, 0) != 0) return null; + return len; +} + +/// Where a terminal is. The process forked for it, while it still runs the +/// shell pardes started (`shell_exe`), as ever: a job it runs, in another +/// directory (`(cd sub && make)`, a nested pardes), never names the pane. +/// One that exec'd into something else is a wrapper whose own directory +/// never moves (fish's `exec 9ns --mntgen -- fish`): the shell is the +/// foreground group when that is the same shell, and while a job holds the +/// foreground there is no answer, the last one standing. +pub fn ttyCwd(shell_pid: libc.pid_t, master_fd: c_int, shell_exe: []const u8, buf: []u8) ?[]const u8 { + var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var shell_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const shell = realShell(shell_exe, &shell_buf) orelse return shellCwd(shell_pid, buf); + const exe = processExe(shell_pid, &exe_buf) orelse return shellCwd(shell_pid, buf); + if (std.mem.eql(u8, exe, shell)) return shellCwd(shell_pid, buf); + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return null; + const fg_exe = processExe(fg, &exe_buf) orelse return null; + return if (std.mem.eql(u8, fg_exe, shell)) shellCwd(fg, buf) else null; +} + +/// `shell_exe` as /proc//exe would read it: its links followed. +fn realShell(shell_exe: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[]const u8 { + var z: [std.Io.Dir.max_path_bytes:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&z, "{s}", .{shell_exe}, 0) catch return null; + const r = libc.realpath(path, buf) orelse return null; + return std.mem.span(@as([*:0]const u8, @ptrCast(r))); +} + +extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; + +const occ_max_depth: u8 = 8; +const occ_max_visited: usize = 32; + +/// Where `ttyTaken` answers from evidence rather than from `false`. The two +/// implementations are different walks over the same question, so they share +/// one suite rather than each asserting half of it. +const tty_probe_platform = switch (builtin.os.tag) { + .linux, .macos => true, + else => false, +}; + +const TtyProbe = struct { + self_exe: [std.Io.Dir.max_path_bytes]u8 = undefined, + exe: [std.Io.Dir.max_path_bytes]u8 = undefined, + blob: [4096]u8 = undefined, + pending: [occ_max_visited]Node = undefined, + + const Node = struct { pid: libc.pid_t, depth: u8 }; +}; + +pub fn ttyTaken(shell_pid: libc.pid_t, master_fd: c_int) bool { + switch (builtin.os.tag) { + .linux => { + var probe: TtyProbe = undefined; + const fg = tcgetpgrp(master_fd); + if (fg < 0) return false; + const self_exe = processExe(shell_pid, &probe.self_exe) orelse return false; + + var saw_fg = fg == shell_pid; + var pending: usize = 0; + var visited: usize = 0; + switch (pushChildren(&probe, &pending, shell_pid, 1)) { + .pushed => {}, + .unreadable => return false, + .full => return true, + } + + while (pending > 0) { + pending -= 1; + const node = probe.pending[pending]; + visited += 1; + if (visited > occ_max_visited) return true; + + const pgrp = procPgrp(node.pid, &probe.blob); + if (pgrp) |g| { + if (g == fg) saw_fg = true; + } + + const exe = processExe(node.pid, &probe.exe) orelse { + if (offTty(node.pid, &probe.blob)) continue; + // Exiting (its exe gone, not a zombie yet), or not ours + // to read: outside the foreground group it holds + // nothing, as a killed background job does for a moment. + if (pgrp) |g| if (g != fg) continue; + return true; + }; + if (!std.mem.eql(u8, exe, self_exe)) { + if (pgrp) |g| if (g == fg) return true; + continue; + } + if (node.depth >= occ_max_depth) return true; + switch (pushChildren(&probe, &pending, node.pid, node.depth + 1)) { + .pushed => {}, + .unreadable => {}, + .full => return true, + } + } + return !saw_fg; + }, + .macos => { + const fg = tcgetpgrp(master_fd); + if (fg <= 0) return false; + if (fg == shell_pid) return false; + return darwin.taken(shell_pid, fg); + }, + // ponytail: any foreground job but the shell's own group, so a + // nested interactive shell counts as taken; walk the group + // (KERN_PROC_PGRP) as darwin does if that matters. + .freebsd => { + const fg = tcgetpgrp(master_fd); + return fg > 0 and fg != shell_pid; + }, + else => return false, + } +} + +/// The same question the Linux walk asks, answered the way macOS can answer +/// it. There is no /proc to descend and no children list, but the tty's +/// foreground process group can be enumerated in one call — and "is anything +/// but the shell itself holding this terminal?" is exactly a statement about +/// the executables in that group. The test is the shell's own executable and +/// never its pid, which is what keeps a nested interactive shell a prompt, +/// and what still catches `bash -c 'sleep 30'`: the group holds `sleep` too. +/// +/// Until this existed, `ttyTaken` answered `false` on darwin for every pane, +/// so `exec.takesCommandLine` was permanently true and every bare Escape in +/// a raw terminal ran the `Last` builtin instead of reaching the child. +const darwin = struct { + const proc_pgrp_only: u32 = 2; + const proc_pidt_shortbsdinfo: c_int = 13; + const zombie_status: u32 = 5; // SZOMB + /// PROC_PIDPATHINFO_MAXSIZE. + const path_max = 4 * 1024; + /// A foreground group is a pipeline; anything larger is not a prompt. + const group_max = 64; + + const ShortBsdInfo = extern struct { + pid: u32, + ppid: u32, + pgid: u32, + status: u32, + comm: [16]u8, + flags: u32, + uid: u32, + gid: u32, + ruid: u32, + rgid: u32, + svuid: u32, + svgid: u32, + rfu: u32, + }; + + extern "c" fn proc_listpids(kind: u32, typeinfo: u32, buffer: ?*anyopaque, buffersize: c_int) c_int; + extern "c" fn proc_pidpath(pid: c_int, buffer: [*]u8, buffersize: u32) c_int; + + fn exe(pid: libc.pid_t, buf: *[path_max]u8) ?[]const u8 { + const got = proc_pidpath(pid, buf, buf.len); + if (got <= 0) return null; + return buf[0..@intCast(got)]; + } + + /// A pid with no readable path is either gone or not ours. Only a zombie + /// is provably harmless — it holds no tty — so everything else is taken. + fn zombie(pid: libc.pid_t) bool { + var info: ShortBsdInfo = undefined; + const got = proc_pidinfo(pid, proc_pidt_shortbsdinfo, 0, &info, @sizeOf(ShortBsdInfo)); + if (got != @sizeOf(ShortBsdInfo)) return false; + return info.status == zombie_status; + } + + fn taken(shell_pid: libc.pid_t, fg: libc.pid_t) bool { + var shell_buf: [path_max]u8 = undefined; + const shell_exe = exe(shell_pid, &shell_buf) orelse return false; + var group: [group_max]libc.pid_t = undefined; + const bytes = proc_listpids(proc_pgrp_only, @intCast(fg), &group, @sizeOf(@TypeOf(group))); + // An empty group is a group whose last member just exited: the shell + // is about to have its terminal back, and calling that taken would + // blink the prompt heuristic off for a frame every time a job ends. + if (bytes <= 0) return false; + const n = @as(usize, @intCast(bytes)) / @sizeOf(libc.pid_t); + if (n >= group.len) return true; + var exe_buf: [path_max]u8 = undefined; + for (group[0..n]) |pid| { + if (pid <= 0 or pid == shell_pid) continue; + const path = exe(pid, &exe_buf) orelse { + if (zombie(pid)) continue; + return true; + }; + if (!std.mem.eql(u8, path, shell_exe)) return true; + } + return false; + } +}; + +/// A program a plumbing rule starts (Effect.start), as Plan 9's plumber +/// starts one (match.c's startup): out of the editor's way, a session of +/// its own reaped by init, stdin, stdout and stderr /dev/null and no other +/// fd of the editor's, its argv exec'd (no shell: a rule that wants one +/// says `sh -c`) in its directory. `line` is its directory, then its argv, +/// each ended by a NUL. Null once it runs, else why not, as errno says it, +/// in `why` (as the tape replays a host's words): a pipe closed at the +/// exec carries the child's errno back. +pub fn startDetached(_: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 { + const words = startWords(line) orelse return null; + const n = @min(words.len, why.len); + @memcpy(why[0..n], words[0..n]); + return why[0..n]; +} + +fn startWords(line: []const u8) ?[]const u8 { + var buf: [pardes.effect_path_cap]u8 = undefined; + if (line.len == 0 or line.len > buf.len or line[line.len - 1] != 0) return "malformed"; + @memcpy(buf[0..line.len], line); + var argv: [64:null]?[*:0]const u8 = @splat(null); + var n: usize = 0; + var at: usize = 0; + var dir: [*:0]const u8 = undefined; + while (at < line.len) { + const end = std.mem.indexOfScalarPos(u8, line, at, 0).?; + const word: [*:0]const u8 = @ptrCast(&buf[at]); + if (at == 0) dir = word else if (n < argv.len) { + argv[n] = word; + n += 1; + } else return "more than 64 words"; + at = end + 1; + } + if (n == 0) return "no program"; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return "no pipe"; + for (fds) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[0]); + _ = libc.close(fds[1]); + return "no fork"; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + if (libc.fork() != 0) libc._exit(0); + resetChildSignals(); + // What failed, then errno: 'd' the directory, 'x' the exec. + const Fail = struct { + fn say(fd: c_int, what: u8) noreturn { + var said: [5]u8 = undefined; + said[0] = what; + std.mem.writeInt(u32, said[1..5], @intFromEnum(libc.errno(-1)), .little); + _ = libc.write(fd, &said, said.len); + libc._exit(127); + } + }; + const err_fd = libc.fcntl(fds[1], libc.F.DUPFD_CLOEXEC, @as(c_int, 3)); + if (err_fd < 0) libc._exit(127); + if (dir[0] != 0 and libc.chdir(dir) != 0) Fail.say(err_fd, 'd'); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + if (null_fd >= 0) for (0..3) |i| { + _ = libc.dup2(null_fd, @intCast(i)); + }; + // Every fd of the editor's but the errno pipe's gone: a pty's + // master held open would keep its terminal alive. + if (libc.dup2(err_fd, 3) < 0) libc._exit(127); + _ = libc.fcntl(3, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const shut = if (comptime builtin.os.tag == .linux) + std.os.linux.close_range(4, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0 + else + false; + if (!shut) { + var fd: c_int = 4; + while (fd < 1024) : (fd += 1) _ = libc.close(fd); + } + _ = execvp(argv[0].?, &argv); + Fail.say(3, 'x'); + } + _ = libc.close(fds[1]); + while (libc.waitpid(first, null, 0) < 0 and libc.errno(-1) == .INTR) {} + var said: [5]u8 = undefined; + var got: usize = 0; + while (got < said.len) { + const r = libc.read(fds[0], said[got..].ptr, said.len - got); + if (r < 0 and libc.errno(r) == .INTR) continue; + if (r <= 0) break; + got += @intCast(r); + } + _ = libc.close(fds[0]); + if (got < said.len) return null; + const code = std.mem.readInt(u32, said[1..5], .little); + const E = libc.E; + if (code == @intFromEnum(E.NOENT)) return if (said[0] == 'd') "its directory: no such directory" else "not found"; + if (code == @intFromEnum(E.ACCES)) return "permission denied"; + if (code == @intFromEnum(E.NOTDIR)) return "not a directory"; + if (code == @intFromEnum(E.NOEXEC)) return "not an executable"; + return if (said[0] == 'd') "its directory: cannot go there" else "cannot start it"; +} + +extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; + +/// A terminal pane's shell is done with (its pane gone, its pty closed or at +/// end of file): say hangup, for a shell that ignores the tty's, and see it +/// reaped, killed if it is still there 100 ms on. A thread does the waiting +/// so that no host loop needs a timer for it (macOS's has none); a thread +/// that cannot start kills and reaps it here. +/// ponytail: only the window waits for them at exit (waitRetired); the tui +/// and macOS leave a shell still inside its 100 ms to init, a waitRetired at +/// their exit if that matters. +pub fn retireShell(pid: libc.pid_t) void { + if (pid <= 0) return; + _ = libc.kill(pid, libc.SIG.HUP); + if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; + _ = retiring.fetchAdd(1, .monotonic); + const thread = std.Thread.spawn(.{}, reapRetiring, .{pid}) catch { + _ = retiring.fetchSub(1, .monotonic); + return reapShell(pid, 0); + }; + thread.detach(); +} + +/// retireShell's threads still waiting on a shell. +var retiring: std.atomic.Value(u32) = .init(0); + +fn reapRetiring(pid: libc.pid_t) void { + defer _ = retiring.fetchSub(1, .release); + reapShell(pid, 100); +} + +/// An exit's sweep: every shell retireShell still waits on is seen out, gone +/// on its hangup or killed at the end of its 100 ms, and reaped, rather than +/// left to init. +pub fn waitRetired() void { + while (retiring.load(.acquire) != 0) { + const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } +} + +// ---- a command pane's child, watched to its exit ---- +// +// A command pane's command is done when its process exits, not when its pty +// reaches end of file: a job it put in the background can hold the pty open +// after it has gone, and a command can close its terminal and run on. A +// thread per command waits for the exit without reaping (WNOWAIT), so the +// pid is still the child's -- no Kill can reach another process that took +// it -- until the host, told through `takeExited`, reaps it in its own loop +// with `exitStatus` and tells the core. + +const freebsd = builtin.os.tag == .freebsd; +const waitid_p_pid: c_int = if (freebsd) 0 else 1; +const waitid_wexited: c_int = if (freebsd) 16 else 4; +const waitid_wnowait: c_int = switch (builtin.os.tag) { + .linux => 0x01000000, + .freebsd => 8, + else => 0x20, +}; +// FreeBSD's id_t is 64 bits. +extern "c" fn waitid(idtype: c_int, id: if (freebsd) i64 else c_uint, infop: *anyopaque, options: c_int) c_int; + +var exited: [pardes.MAX_PANES * 2]std.atomic.Value(libc.pid_t) = @splat(.init(0)); +var exit_lock: libc.pthread_mutex_t = .{}; +var exit_wake: ?struct { ctx: ?*anyopaque, f: *const fn (?*anyopaque) void } = null; + +/// Who wakes the host's loop when a watched child exits; null at shutdown, +/// after which a watcher still waiting tells nobody. +pub fn setExitWake(ctx: ?*anyopaque, f: ?*const fn (?*anyopaque) void) void { + _ = libc.pthread_mutex_lock(&exit_lock); + defer _ = libc.pthread_mutex_unlock(&exit_lock); + exit_wake = if (f) |wake| .{ .ctx = ctx, .f = wake } else null; +} + +/// Watches a command pane's child; false when no thread could be started, +/// and the host then reads its exit at end of file instead. +pub fn watchExit(pid: libc.pid_t) bool { + const thread = std.Thread.spawn(.{}, watchChild, .{pid}) catch return false; + thread.detach(); + return true; +} + +fn watchChild(pid: libc.pid_t) void { + var info: [128]u8 align(16) = undefined; + while (waitid(waitid_p_pid, @intCast(pid), &info, waitid_wexited | waitid_wnowait) < 0 and libc.errno(-1) == .INTR) {} + // A cell for it, waiting for one if the host is slow to take them. + place: while (true) { + for (&exited) |*cell| if (cell.cmpxchgStrong(0, pid, .acq_rel, .acquire) == null) break :place; + const ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + wakeForExit(); +} + +fn wakeForExit() void { + _ = libc.pthread_mutex_lock(&exit_lock); + defer _ = libc.pthread_mutex_unlock(&exit_lock); + if (exit_wake) |wake| wake.f(wake.ctx); +} + +/// Where a host's command pane is between its child's exit and the end of +/// its output. The exit is told once the output before it is in: at the +/// pty's end of file; or, when something else still holds the pty (a job +/// the command left in the background), once nothing is waiting to be read +/// -- checked when the exit is seen and again after each chunk of output, +/// with no timer to miss. acme's waitthread tells an exit when it is +/// reaped (acme.c:587-700); a terminal also has output in flight. +pub const CommandWatch = struct { + watched: bool = false, + /// The master, to ask whether output is still waiting. + fd: c_int = -1, + eof: bool = false, + exited: bool = false, + told: bool = false, + status: ?u8 = null, + + /// Whether the exit is to be told now. + pub fn due(w: *const CommandWatch) bool { + if (!w.exited or w.told) return false; + if (w.eof) return true; + var pfd = [1]libc.pollfd{.{ .fd = w.fd, .events = libc.POLL.IN, .revents = 0 }}; + if (libc.poll(&pfd, 1, 0) < 0) return true; + // Every holder of its terminal gone: the end of file comes, after + // the rest of the output. + if (pfd[0].revents & libc.POLL.HUP != 0) return false; + return pfd[0].revents & libc.POLL.IN == 0; + } +}; + +/// A host's pty slot, whichever way it keeps it: an optional, or one whose +/// `fd` is -1 when empty. +fn SlotPty(comptime S: type) type { + return switch (@typeInfo(S)) { + .optional => |o| *o.child, + else => *S, + }; +} + +fn slotPty(slot: anytype) ?SlotPty(@TypeOf(slot.*)) { + return switch (@typeInfo(@TypeOf(slot.*))) { + .optional => if (slot.*) |*pt| pt else null, + else => if (slot.fd < 0) null else slot, + }; +} + +/// Each watched child that exited: reaped, and the core told once its +/// output is in, its pty closed (`close(ctx, id)`) if its end of file came +/// first. Every host runs this after an exit's wake and after each chunk +/// of a command's output; `ptys` is its slot array, each slot with a `pid` +/// and a `cmd`. +pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime close: anytype) void { + while (takeExited()) |pid| for (ptys) |*slot| { + const pt = slotPty(slot) orelse continue; + if (!pt.cmd.watched or pt.pid != pid or pt.cmd.exited) continue; + pt.cmd.status = (reapExited(pid) orelse break).status; + pt.cmd.exited = true; + pt.pid = 0; // reaped: no signal or retire may reach whoever gets it next + break; + }; + for (ptys, 0..) |*slot, id| { + const pt = slotPty(slot) orelse continue; + if (!pt.cmd.watched or !pt.cmd.due()) continue; + pt.cmd.told = true; + const eof = pt.cmd.eof; + core.update(.{ .exited = .{ .pane = @intCast(id), .status = pt.cmd.status } }); + if (eof) close(ctx, id); + } +} + +/// A watched command's pty reached end of file: the core hears its output +/// is over; the pty is closed now if its exit was told, else when it is. +pub fn commandEof(core: *pardes.Pardes, ptys: anytype, id: usize, ctx: anytype, comptime close: anytype) void { + const pt = slotPty(&ptys[id]) orelse return; + pt.cmd.eof = true; + core.update(.{ .eof = .{ .pane = @intCast(id) } }); + if (pt.cmd.told) return close(ctx, id); + takeExits(core, ptys, ctx, close); +} + +/// Reaps `pid` if it has exited: its status (null: unknown, or not ours +/// to read), or null when it is still running -- a pid a watcher reported +/// may since have been reaped by another and taken by a new child. +pub fn reapExited(pid: libc.pid_t) ?struct { status: ?u8 } { + if (pid <= 0) return .{ .status = null }; + var status: c_int = 0; + const got = libc.waitpid(pid, &status, libc.W.NOHANG); + if (got == 0) return null; + if (got != pid) return .{ .status = null }; + return .{ .status = statusOf(status) }; +} + +/// A wait status as a shell says it: the exit code, or 128 and the signal +/// that ended it; null for neither. +fn statusOf(status: c_int) ?u8 { + const s: u32 = @bitCast(status); + if (libc.W.IFEXITED(s)) return @truncate(libc.W.EXITSTATUS(s)); + if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))); + return null; +} + +/// A watched child that has exited, not yet reaped, or null. +pub fn takeExited() ?libc.pid_t { + for (&exited) |*cell| { + const pid = cell.swap(0, .acq_rel); + if (pid != 0) return pid; + } + return null; +} + +/// A pane's child at its pty's end of file: reaped, and how it exited +/// (its code, or 128 and the signal that ended it), if it is gone within +/// `wait_ms`; null if it is still running (a job it left holds nothing +/// open, but the child itself may be a moment behind its pty), which the +/// caller then retires as it would any shell. +pub fn exitStatus(pid: libc.pid_t, wait_ms: u32) ?u8 { + if (pid <= 0) return null; + var waited: u32 = 0; + while (true) : (waited += 2) { + var status: c_int = 0; + const got = libc.waitpid(pid, &status, libc.W.NOHANG); + if (got == pid) return statusOf(status); + if (got < 0 or waited >= wait_ms) return null; + const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } +} + +fn reapShell(pid: libc.pid_t, grace_ms: u32) void { + var waited: u32 = 0; + while (waited < grace_ms) : (waited += 5) { + // Not 0 is reaped, or someone else reaped it: either way not ours. + if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; + const ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; + _ = libc.kill(pid, libc.SIG.KILL); + while (libc.waitpid(pid, null, 0) < 0 and libc.errno(-1) == .INTR) {} +} + +/// The tty's foreground job is signalled. A command pane's shell (`command`) +/// is its command too: its line runs with job control on, so the job +/// running is in a group of its own, and the shell's group goes as well, or +/// the rest of the line would run on after the job it was on. A stop (TERM +/// or KILL) of a command reaches its `&` jobs too, each in a group of its +/// own in the shell's session: Kill leaves nothing the line started. +/// The shell goes first: a job that died before it would let it run the +/// line's next command in the gap, and the gap is a scan of all of /proc +/// (signalSession), long once pids have wrapped below the old processes'. +pub fn signalTty(shell_pid: libc.pid_t, master_fd: c_int, which: pardes.PtySignal, command: bool) void { + const sig = switch (which) { + .int => libc.SIG.INT, + .term => libc.SIG.TERM, + .hup => libc.SIG.HUP, + .quit => libc.SIG.QUIT, + .kill => libc.SIG.KILL, + }; + const fg = tcgetpgrp(master_fd); + if (command and shell_pid > 0 and fg != shell_pid) _ = libc.kill(-shell_pid, sig); + if (command and shell_pid > 0 and (which == .term or which == .kill)) signalSession(shell_pid, sig); + if (fg > 0) _ = libc.kill(-fg, sig); + if (fg <= 0 and !command and shell_pid > 0) _ = libc.kill(shell_pid, sig); +} + +/// Every process group in the session `sid` leads, but its own (which the +/// caller signals last). forkpty made the shell the session's leader, and +/// job control moves a job to a new group, never out of the session. +// ponytail: Linux only (a /proc scan); elsewhere a `&` job outlives Kill, +// add sysctl KERN_PROC_SESSION on macOS if that matters. +fn signalSession(sid: libc.pid_t, sig: libc.SIG) void { + if (comptime builtin.os.tag != .linux) return; + const d = libc.opendir("/proc") orelse return; + defer _ = libc.closedir(d); + var buf: [4096]u8 = undefined; + while (libc.readdir(d)) |ent| { + const name = std.mem.sliceTo(&ent.name, 0); + const pid = std.fmt.parseInt(libc.pid_t, name, 10) catch continue; + var path_buf: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/stat", .{pid}, 0) catch unreachable; // a pid fits 64 + const ids = parseGroupSession(readProc(path, &buf) orelse continue) orelse continue; + if (ids.session == sid and ids.pgrp != sid) _ = libc.kill(-ids.pgrp, sig); + } +} + +fn parseGroupSession(stat: []const u8) ?struct { pgrp: libc.pid_t, session: libc.pid_t } { + const close = std.mem.lastIndexOfScalar(u8, stat, ')') orelse return null; + var fields = std.mem.tokenizeAny(u8, stat[close + 1 ..], " \t\n"); + _ = fields.next() orelse return null; // 3: state + _ = fields.next() orelse return null; // 4: ppid + const pgrp = std.fmt.parseInt(libc.pid_t, fields.next() orelse return null, 10) catch return null; + const session = std.fmt.parseInt(libc.pid_t, fields.next() orelse return null, 10) catch return null; + return .{ .pgrp = pgrp, .session = session }; +} + +/// Kill: SIGTERM to the job in the tty's foreground, never to the shell. +/// The shell leads its own group, and a job it runs has another; with job +/// control off (`set +m`, a shell run as `sh -c`) the job shares the shell's +/// group, and there is no job to signal apart from it: false. +pub fn killJob(shell_pid: libc.pid_t, master_fd: c_int) bool { + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return false; + return libc.kill(-fg, libc.SIG.TERM) == 0; +} + +/// The command name of the tty's foreground job, when that is not the +/// shell: what `pty/run` says is running. /proc//comm on Linux, the +/// program's name on FreeBSD. +pub fn foregroundName(shell_pid: libc.pid_t, master_fd: c_int, buf: []u8) ?[]const u8 { + if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) return null; + const fg = tcgetpgrp(master_fd); + if (fg <= 0 or fg == shell_pid) return null; + if (comptime builtin.os.tag == .freebsd) return std.Io.Dir.path.basename(processExe(fg, buf) orelse return null); + var name: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/comm", .{@as(u32, @intCast(fg))}, 0) catch unreachable; // a u32 fits 64 + const comm = std.mem.trimEnd(u8, readProc(path, buf) orelse return null, "\n"); + return if (comm.len > 0) comm else null; +} + +fn readProc(path: [*:0]const u8, buf: []u8) ?[]const u8 { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return null; + defer _ = libc.close(fd); + const got = libc.read(fd, buf.ptr, buf.len); + if (got <= 0) return null; + return buf[0..@intCast(got)]; +} + +fn procPgrp(pid: libc.pid_t, buf: *[4096]u8) ?libc.pid_t { + var name: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/stat", .{@as(u32, @intCast(pid))}, 0) catch unreachable; // a u32 fits 64 + return (parseGroupSession(readProc(path, buf) orelse return null) orelse return null).pgrp; +} + +fn offTty(pid: libc.pid_t, buf: *[4096]u8) bool { + var name: [64:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/status", .{@as(u32, @intCast(pid))}, 0) catch unreachable; // a u32 fits 64 + const status = readProc(path, buf) orelse return true; + return parseZombie(status); +} + +fn parseZombie(status: []const u8) bool { + var lines = std.mem.splitScalar(u8, status, '\n'); + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "State:")) continue; + const state = std.mem.trim(u8, line["State:".len..], " \t\r"); + return state.len > 0 and state[0] == 'Z'; + } + return false; +} + +const Pushed = enum { pushed, unreadable, full }; + +fn pushChildren(probe: *TtyProbe, pending: *usize, pid: libc.pid_t, depth: u8) Pushed { + var name: [96:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/task/{d}/children", .{ + @as(u32, @intCast(pid)), @as(u32, @intCast(pid)), + }, 0) catch unreachable; // two u32s fit 96 + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return .unreadable; + defer _ = libc.close(fd); + const got = libc.read(fd, &probe.blob, probe.blob.len); + if (got < 0) return .unreadable; + + var kids: [occ_max_visited]libc.pid_t = undefined; + const total = parseChildren(probe.blob[0..@intCast(got)], &kids); + if (total > kids.len or pending.* + total > probe.pending.len) return .full; + for (kids[0..total]) |kid| { + probe.pending[pending.*] = .{ .pid = kid, .depth = depth }; + pending.* += 1; + } + return .pushed; +} + +fn parseChildren(text: []const u8, out: []libc.pid_t) usize { + var total: usize = 0; + var it = std.mem.tokenizeAny(u8, text, " \t\n\r"); + while (it.next()) |tok| { + if (std.mem.indexOfNone(u8, tok, "0123456789") != null) continue; + const kid = std.fmt.parseInt(libc.pid_t, tok, 10) catch continue; + if (total < out.len) out[total] = kid; + total += 1; + } + return total; +} + +const test_shell = "/bin/bash"; +const test_prompt = "PZX> "; + +const TestShell = struct { + master: c_int, + pid: libc.pid_t, + tail: [8192]u8 = undefined, + tail_len: usize = 0, + + fn start() ?TestShell { + if (!haveFile(test_shell)) return null; + var master: c_int = undefined; + const ws = std.posix.winsize{ .row = 24, .col = 80, .xpixel = 0, .ypixel = 0 }; + const pid = forkpty(&master, null, null, &ws); + if (pid < 0) return null; + if (pid == 0) { + const argv: [3:null]?[*:0]const u8 = .{ test_shell, "--norc", "-i" }; + _ = execv(test_shell, &argv); + _exit(127); + } + var sh: TestShell = .{ .master = master, .pid = pid }; + sh.send("export PS1='PZ''X> '\n"); + if (!sh.waitText(test_prompt, 10_000)) { + sh.stop(); + return null; + } + sh.forget(); + return sh; + } + + fn send(sh: *TestShell, bytes: []const u8) void { + _ = libc.write(sh.master, bytes.ptr, bytes.len); + } + + fn forget(sh: *TestShell) void { + sh.tail_len = 0; + } + + fn drain(sh: *TestShell) void { + while (true) { + var fds = [1]libc.pollfd{.{ .fd = sh.master, .events = libc.POLL.IN, .revents = 0 }}; + if (libc.poll(&fds, 1, 0) <= 0) return; + if (fds[0].revents & libc.POLL.IN == 0) return; + var chunk: [4096]u8 = undefined; + const n = libc.read(sh.master, &chunk, chunk.len); + if (n <= 0) return; + sh.append(chunk[0..@intCast(n)]); + } + } + + fn append(sh: *TestShell, bytes: []const u8) void { + if (bytes.len >= sh.tail.len) { + @memcpy(&sh.tail, bytes[bytes.len - sh.tail.len ..]); + sh.tail_len = sh.tail.len; + return; + } + const room = sh.tail.len - sh.tail_len; + if (bytes.len > room) { + const drop = bytes.len - room; + std.mem.copyForwards(u8, sh.tail[0 .. sh.tail_len - drop], sh.tail[drop..sh.tail_len]); + sh.tail_len -= drop; + } + @memcpy(sh.tail[sh.tail_len..][0..bytes.len], bytes); + sh.tail_len += bytes.len; + } + + fn waitText(sh: *TestShell, needle: []const u8, ms: i64) bool { + const deadline = nowMs() + ms; + while (true) { + sh.drain(); + if (std.mem.indexOf(u8, sh.tail[0..sh.tail_len], needle) != null) return true; + if (nowMs() >= deadline) return false; + sleepMs(5); + } + } + + fn taken(sh: *TestShell) bool { + sh.drain(); + return ttyTaken(sh.pid, sh.master); + } + + fn waitTaken(sh: *TestShell, want: bool, ms: i64) bool { + const deadline = nowMs() + ms; + while (true) { + if (sh.taken() == want) return true; + if (nowMs() >= deadline) return false; + sleepMs(5); + } + } + + fn holdsTaken(sh: *TestShell, want: bool, ms: i64) bool { + const deadline = nowMs() + ms; + while (nowMs() < deadline) { + if (sh.taken() != want) return false; + sleepMs(5); + } + return true; + } + + fn stop(sh: *TestShell) void { + if (comptime builtin.os.tag == .linux) { + var probe: TtyProbe = undefined; + var pending: usize = 0; + var doomed: [occ_max_visited]libc.pid_t = undefined; + var n: usize = 0; + _ = pushChildren(&probe, &pending, sh.pid, 1); + while (pending > 0) { + pending -= 1; + const node = probe.pending[pending]; + if (n == doomed.len) break; + doomed[n] = node.pid; + n += 1; + if (node.depth < occ_max_depth) _ = pushChildren(&probe, &pending, node.pid, node.depth + 1); + } + _ = libc.kill(sh.pid, libc.SIG.KILL); + for (doomed[0..n]) |kid| { + _ = libc.kill(kid, libc.SIG.KILL); + _ = libc.kill(-kid, libc.SIG.KILL); + } + } else { + // No children list to descend. forkpty made the shell a session + // leader, so its own group plus whichever group currently holds + // the tty covers the job the test left running. + const fg = tcgetpgrp(sh.master); + if (fg > 0 and fg != sh.pid) _ = libc.kill(-fg, libc.SIG.KILL); + _ = libc.kill(-sh.pid, libc.SIG.KILL); + _ = libc.kill(sh.pid, libc.SIG.KILL); + } + _ = libc.waitpid(sh.pid, null, 0); + _ = libc.close(sh.master); + } +}; + +fn haveFile(path: [*:0]const u8) bool { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return false; + _ = libc.close(fd); + return true; +} + +fn nowMs() i64 { + return std.Io.Clock.awake.now(std.testing.io).toMilliseconds(); +} + +fn sleepMs(ms: i64) void { + std.testing.io.sleep(.fromMilliseconds(ms), .awake) catch {}; +} + +// ---- what every host's vtable does alike ---- + +/// A Save's write: the file written through the core's filesystem, the +/// pane's watch told the new text is the editor's own (so it is no outside +/// change), and "saved" said on the pane. +pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { + filesystem.write(core, path, bytes) catch |err| + return core.saveFailed(pane, path, err); + if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { + if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { + .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, + .kind => {}, + }; + }; + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); + // The init file, saved here (Config): its settings take effect now. + pardes.exec.reapplyInitFile(core, path, bytes); + // The plumbing file (Plumb): its rules in force now. + pardes.Plumb.saved(core, pane, path, bytes); +} + +/// A Dump's write: into the state file under a label of its own +/// (Db.putDump), or as a file of its own where `Dump export` names one or +/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its +/// goldens). +pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { + const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; + if (to) |path| { + filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); + return core.setLastDump(path); + } + var stamp: [64]u8 = undefined; + var buf: [128]u8 = undefined; + const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { + var path: [4200]u8 = undefined; + // In the words a host reports failures in (tape.Failure). + const said: pardes.tape.Failure = switch (err) { + error.NoStateFile => error.NoDumpDirectory, + error.OutOfMemory => error.OutOfMemory, + error.NoSpaceLeft => error.NoSpaceLeft, + error.AccessDenied => error.AccessDenied, + else => error.InputOutput, + }; + return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); + }; + core.setLastDump(label); +} + +/// DumpThemes: the built-in themes written below the config directory. +pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { + const config_dir = core.opts.config_dir orelse return; + const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { + core.reportError(pane, "dump themes", err); + return; + }; + defer gpa.free(out_dir); + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); +} + +pub const PtyTests = struct { + pub fn waitBlocked(queue: *Inbox) !void { + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + queue.lock(); + const waiting = queue.waiting; + queue.unlock(); + if (waiting != 0) return; + try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + return error.ReaderDidNotBlock; + } + + fn tail(queue: *Inbox, bytes: []u8) void { + if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + } +}; + +test { + _ = Lsp; +} + +test "a child starts with every signal at its default and none blocked" { + var blocked = posix.sigemptyset(); + posix.sigaddset(&blocked, posix.SIG.WINCH); + posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); + defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); + const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; + var was: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, &ignore, &was); + defer posix.sigaction(posix.SIG.HUP, &was, null); + const pid = libc.fork(); + if (pid == 0) { + resetChildSignals(); + var now: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, null, &now); + var mask = posix.sigemptyset(); + posix.sigprocmask(posix.SIG.BLOCK, null, &mask); + const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); + libc._exit(if (ok) 0 else 1); + } + var status: c_int = 0; + _ = libc.waitpid(pid, &status, 0); + try std.testing.expectEqual(@as(c_int, 0), status); +} + +test "the pager's path is quoted only when it needs it" { + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); + try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); + try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); +} + +test "the child environment replaces the launcher's terminal identity exactly once" { + const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + if (t.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..t.len], t); + saved_buf[t.len] = 0; + break :blk saved_buf[0..t.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + + // A launcher TERM must be shadowed rather than duplicated, and the rest of + // the environment must arrive untouched. + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); + + var slots: ChildEnv.Slots = undefined; + // Where the user named no pager: a terminal's shell pages into a + // +Pager pane (`pardes -`); a command pane's through cat. A pager the + // user named is kept. + var shell_slots: ChildEnv.Slots = undefined; + const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; + var said: usize = 0; + var systemd: usize = 0; + var j: usize = 0; + while (shell_envp[j]) |entry| : (j += 1) { + const line = std.mem.span(entry); + if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; + if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; + if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { + try std.testing.expect(std.mem.endsWith(u8, line, " -")); + said += 1; + } + } + if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); + // systemd's pager and its secure mode off, with ours only. + if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) + try std.testing.expectEqual(@as(usize, 2), systemd); + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; + var terms: usize = 0; + var colorterms: usize = 0; + var probes: usize = 0; + var dumb = false; + var pagers: usize = 0; + var git_pagers: usize = 0; + var pager_cat = false; + var git_pager_cat = false; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) { + const line = std.mem.span(entry); + if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; + if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; + if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; + if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; + if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; + if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; + if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; + if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; + } + // A pager only where the user named none: cat, so nothing waits in less. + try std.testing.expectEqual(@as(usize, 1), pagers); + try std.testing.expectEqual(@as(usize, 1), git_pagers); + if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); + if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); + try std.testing.expectEqual(@as(usize, 1), terms); + try std.testing.expectEqual(@as(usize, 1), colorterms); + try std.testing.expectEqual(@as(usize, 1), probes); + try std.testing.expect(!dumb); + // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it + // is a separate entry and never a second TERM. + try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); +} + +test "shell spawn rejects invalid directories before creating a child" { + const rcs: Shell.PromptFiles = .{}; + try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); + const too_long = @as([4096]u8, @splat('x')); + try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; + var path_buf: [4096]u8 = undefined; + const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); + const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); + const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); + try std.testing.expect(missing.len > 256); + try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); +} + +test "a forked shell is told which terminal it is talking to" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + // Whatever launched the test is the wrong answer, so make it a loud one. + const saved = libc.getenv("TERM"); + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + const span = std.mem.span(t); + if (span.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..span.len], span); + saved_buf[span.len] = 0; + break :blk saved_buf[0..span.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + _ = Shell.setenv("TERM", "dumb", 1); + + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + // The echoed command carries the unexpanded `$TERM`, so only the shell's + // own expansion can match this. + try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); + try std.testing.expect(sh.waitText( + "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, + 5_000, + )); +} + +test "shell spawn uses an explicit OS directory longer than 256 bytes" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(std.testing.io, sub_path); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; + try std.testing.expect(directory.len > 256); + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); + var expected_buf: [4096]u8 = undefined; + const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); + try std.testing.expect(sh.waitText(expected, 5_000)); +} + +test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "start/a/b"); + var path_buf: [4096]u8 = undefined; + const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; + var inner_buf: [4096]u8 = undefined; + const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; + const rcs: Shell.PromptFiles = .{}; + var result: [4096]u8 = undefined; + // A wrapper exec'd over the shell (timeout standing in for 9ns) runs + // another, two directories down, in the foreground. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); + try std.testing.expect(sh.waitText("pardes-in-", 5_000)); + // printf runs before the inner shell takes the foreground. + var tries: usize = 0; + while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) + try std.testing.io.sleep(.fromMilliseconds(20), .awake); + try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } + // A job of the shell's own, gone into a/b, leaves the pane where the + // shell is. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); + try std.testing.expect(sh.waitText("pardes-job", 5_000)); + try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } +} + +test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(io, nested); + var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; + try std.testing.expect(directory.len > 1024); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); +} + +test "a shell whose directory was removed is not named `... (deleted)`" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "gone"); + var path_buf: [4096]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [4096]u8 = undefined; + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try tmp.dir.deleteDir(io, "gone"); + try std.testing.expect(shellCwd(child.pid, &result) == null); +} + +test "the children blob parses to pids, and a garbage token never becomes one" { + var out: [8]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); + try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); + try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); + try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); + try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); + var two: [2]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); +} + +test "the process group comes off the last ')', not a comm-shifted stat field" { + const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ + "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; + try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); + try std.testing.expect(parseGroupSession("") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); + try std.testing.expect(parseGroupSession("no parens here at all") == null); +} + +test "the zombie state comes off its own status line" { + try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); + try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); + try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nSta")); + try std.testing.expect(!parseZombie("State:\t")); +} + +test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + try std.testing.expect(sh.holdsTaken(false, 200)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); +} + +test "Kill stops the foreground job, never the shell, and finds none with job control off" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + // At the prompt the shell is the foreground: there is nothing to stop. + try std.testing.expect(!killJob(sh.pid, sh.master)); + sleepMs(100); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.forget(); + try std.testing.expect(killJob(sh.pid, sh.master)); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + // Job control off: the job runs in the shell's own group. + sh.forget(); + sh.send("set +m; sleep 30\n"); + sleepMs(300); + try std.testing.expect(!killJob(sh.pid, sh.master)); + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +} + +test "a command pane's child is its shell running the one line, and its exit status is read at the end" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + var got: [256]u8 = undefined; + var n: usize = 0; + while (n < got.len) { + const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); + if (r <= 0) break; // EIO once the child is gone: the pty's end + n += @intCast(r); + } + try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); + try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); +} + +test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const Case = struct { line: []const u8, status: u8 }; + // A job left in the background holds the pty open past the command's + // exit; a command that lets go of its terminal runs on past its end of + // file. Either way the exit is the process's. + for ([_]Case{ + .{ .line = "sleep 3 & exit 4", .status = 4 }, + .{ .line = "exec /dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, + }) |c| { + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", c.line); + while (core.nextEffect()) |_| {} + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + try std.testing.expect(watchExit(child.pid)); + var got: ?libc.pid_t = null; + var waited: i64 = 0; + while (got == null and waited < 5000) : (waited += 10) { + got = takeExited(); + if (got == null) sleepMs(10); + } + try std.testing.expectEqual(@as(?libc.pid_t, child.pid), got); + // Told before it is reaped: the pid is still the child's. + try std.testing.expectEqual(@as(?u8, c.status), reapExited(child.pid).?.status); + try core.removePane(id, null); + } +} + +test "a command's background job outlives it and its pty, and Kill stops its whole line, its & jobs too" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane + if (comptime !tty_probe_platform) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + const Case = struct { line: []const u8, kill: bool, made: bool }; + for ([_]Case{ + // The shell leads the pty's session; its exit hangs up only the + // foreground group, which the job, in a group of its own, is not. + .{ .line = "(sleep 0.4; touch left) & exit 0", .kill = false, .made = true }, + // The job running is in its own group; the shell goes too. + .{ .line = "sleep 0.4; touch killed", .kill = true, .made = false }, + // Kill stops the whole command, its `&` jobs as well. + .{ .line = "(sleep 0.4; touch killed) & sleep 5", .kill = true, .made = false }, + }) |c| { + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, dir, c.line); + while (core.nextEffect()) |_| {} + const child = try forkShell(core, id, &rcs, "/bin/sh", dir, 24, 80); + if (c.kill) { + sleepMs(150); + signalTty(child.pid, child.file.handle, .term, true); + } + _ = exitStatus(child.pid, 2000); + _ = libc.close(child.file.handle); // the pane closes: the pty hangs up + sleepMs(800); + const name = if (c.kill) "killed" else "left"; + const made = if (tmp.dir.statFile(std.testing.io, name, .{})) |_| true else |_| false; + try std.testing.expectEqual(c.made, made); + try core.removePane(id, null); + } +} + +test "a retired shell that ignores the hangup is killed and reaped, not left a zombie" { + const pid = libc.fork(); + if (pid == 0) { + const argv = [_:null]?[*:0]const u8{ "/bin/sh", "-c", "trap '' HUP; exec sleep 30" }; + const envp = [_:null]?[*:0]const u8{}; + _ = libc.execve("/bin/sh", &argv, &envp); + libc._exit(127); + } + try std.testing.expect(pid > 0); + sleepMs(100); // past the trap + retireShell(pid); + // A zombie still answers kill(pid, 0); only a reaped pid is gone. + var waited: i64 = 0; + while (libc.kill(pid, @fromBackingInt(@intCast(0))) == 0 and waited < 2000) : (waited += 10) sleepMs(10); + try std.testing.expect(libc.kill(pid, @fromBackingInt(@intCast(0))) != 0); + try std.testing.expect(waited >= 90); // it did ignore the hangup +} + +test "a background job is not the tty's owner" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + sh.send("sleep 30 &\n"); + try std.testing.expect(sh.waitText("[1]", 10_000)); + try std.testing.expect(sh.holdsTaken(false, 300)); + + sh.send("kill %1\n"); + try std.testing.expect(sh.holdsTaken(false, 300)); +} + +test "a nested interactive shell is still a prompt" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + sh.forget(); + sh.send("bash --norc -i\n"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expect(sh.holdsTaken(false, 300)); + + sh.forget(); + sh.send("bash --norc -i\n"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expect(sh.holdsTaken(false, 300)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); +} + +test "the walk reaches the leaf: bash -c 'sleep 30' takes the tty" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + sh.send("bash --norc -c 'sleep 30'\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); + + sh.send("bash --norc -c 'sleep 30; :'\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + + // Why the shallow answer is the wrong one, in each walk's own evidence: + // the wrapper between the shell and `sleep` wears the shell's executable, + // so a probe that stopped at it would report a prompt. + if (comptime builtin.os.tag == .linux) { + var probe: TtyProbe = undefined; + var pending: usize = 0; + try std.testing.expectEqual(Pushed.pushed, pushChildren(&probe, &pending, sh.pid, 1)); + try std.testing.expectEqual(@as(usize, 1), pending); + var wrapper_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var shell_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + try std.testing.expectEqualStrings( + processExe(sh.pid, &shell_buf).?, + processExe(probe.pending[0].pid, &wrapper_buf).?, + ); + } else { + const fg = tcgetpgrp(sh.master); + try std.testing.expect(fg > 0 and fg != sh.pid); + var leader_buf: [darwin.path_max]u8 = undefined; + var shell_buf: [darwin.path_max]u8 = undefined; + // The group's leader IS that wrapper, and it is the shell's binary. + try std.testing.expectEqualStrings( + darwin.exe(sh.pid, &shell_buf).?, + darwin.exe(fg, &leader_buf).?, + ); + // Taken all the same, because the rest of the group is not. + try std.testing.expect(darwin.taken(sh.pid, fg)); + } + + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); +} + +test "a full-screen program takes the tty until it quits" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + const cases = [_]struct { bin: [*:0]const u8, run: []const u8, quit: []const u8 }{ + .{ .bin = "/usr/bin/vim", .run = "vim -u NONE -i NONE\n", .quit = "\x1b:q!\r" }, + .{ .bin = "/usr/bin/less", .run = "env LESS= less /etc/hosts\n", .quit = "q" }, + }; + var ran: usize = 0; + for (cases) |c| { + if (!haveFile(c.bin)) continue; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + sh.send(c.run); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.forget(); + sh.send(c.quit); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + ran += 1; + } + if (ran == 0) return error.SkipZigTest; +} + +test "completion survives a full output queue" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 7 }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ + .pane = 0, + .gen = 1, + .bytes = try gpa.dupe(u8, "output"), + } }); + for (0..selection_pipe.Tasks.capacity) |id| queue.push(.{ .pipe = .{ + .id = @intCast(id), + .success = false, + .outputs = &.{}, + .failure = .{ .stderr = try gpa.dupe(u8, "pipe failure") }, + } }); + queue.push(.{ .lsp = .{ .id = 7, .rows = try gpa.dupe(u8, "completion") } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.output_capacity + selection_pipe.Tasks.capacity + 1, batch.len); + for (batch.items[0..Inbox.output_capacity]) |msg| { + try std.testing.expect(msg == .output); + try std.testing.expectEqualStrings("output", msg.output.bytes); + } + for (batch.items[Inbox.output_capacity..][0..selection_pipe.Tasks.capacity], 0..) |msg, id| { + try std.testing.expect(msg == .pipe); + try std.testing.expectEqual(@as(u32, @intCast(id)), msg.pipe.id); + } + var found = false; + for (batch.slice()) |msg| if (msg == .lsp) { + try std.testing.expectEqual(@as(u32, 7), msg.lsp.id); + try std.testing.expectEqualStrings("completion", msg.lsp.rows.?); + found = true; + }; + try std.testing.expect(found); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); +} + +test "PTY backpressure retains byte order and tail before EOF" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); + const tail = try gpa.dupe(u8, "tail"); + var thread: ?std.Thread = std.Thread.spawn(.{}, PtyTests.tail, .{ &queue, tail }) catch |err| { + gpa.free(tail); + return err; + }; + defer { + queue.cancelReader(0, 1); + if (thread) |owned| owned.join(); + } + try PtyTests.waitBlocked(&queue); + queue.push(.files_changed); + queue.push(.files_changed); + var first = queue.take(); + defer for (first.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.output_capacity + 1, first.len); + for (first.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); + try std.testing.expect(first.items[Inbox.output_capacity] == .files_changed); + thread.?.join(); + thread = null; + var last = queue.take(); + defer for (last.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 2), last.len); + try std.testing.expectEqualStrings("tail", last.items[0].output.bytes); + try std.testing.expect(last.items[1] == .eof); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); +} + +test "PTY backpressure cancellation and close release owned producers" { + const gpa = std.testing.allocator; + for ([_]bool{ false, true }) |close| { + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(0, 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); + const tail = try gpa.dupe(u8, "cancelled"); + const thread = std.Thread.spawn(.{}, PtyTests.tail, .{ &queue, tail }) catch |err| { + gpa.free(tail); + return err; + }; + defer { + queue.cancelReader(0, 1); + thread.join(); + } + try PtyTests.waitBlocked(&queue); + if (close) queue.close() else queue.cancelReader(0, 1); + if (!close) { + queue.acceptReader(0, 2); + queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + try std.testing.expect(queue.pushOutput(0, 2, try gpa.dupe(u8, "replacement"))); + queue.push(.{ .eof = .{ .pane = 0, .gen = 2 } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 2), batch.len); + try std.testing.expectEqualStrings("replacement", batch.items[0].output.bytes); + try std.testing.expectEqual(@as(u32, 2), batch.items[1].eof.gen); + } else try std.testing.expectEqual(@as(usize, 0), queue.take().len); + } +} + +test "PTY EOF reserve cannot evict terminal output" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + for (0..pardes.MAX_PANES) |pane| queue.acceptReader(@intCast(pane), 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); + for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = @intCast(pane), .gen = 1 } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.capacity, batch.len); + for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); + for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane); +} + +test "completions retain their arrival order across LSP and pipes" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 }; + defer queue.deinit(); + queue.push(.{ .pipe = .{ .id = 1, .success = true, .outputs = &.{} } }); + queue.push(.{ .lsp = .{ .id = 2, .rows = try gpa.dupe(u8, "second") } }); + queue.push(.{ .pipe = .{ .id = 3, .success = false, .outputs = &.{} } }); + queue.push(.{ .lsp = .{ .id = 1, .rows = try gpa.dupe(u8, "late") } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 3), batch.len); + try std.testing.expectEqual(@as(u32, 1), batch.items[0].pipe.id); + try std.testing.expectEqual(@as(u32, 2), batch.items[1].lsp.id); + try std.testing.expectEqual(@as(u32, 3), batch.items[2].pipe.id); +} + +test "completion reset frees queued payloads and rejects late LSP workers" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 9 }; + defer queue.deinit(); + queue.acceptReader(0, 1); + queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "retained") } }); + queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "current") } }); + queue.push(.{ .lsp = .{ .id = 8, .rows = try gpa.dupe(u8, "late old request") } }); + try std.testing.expectEqualStrings("current", queue.completions[0].lsp.rows.?); + for (0..selection_pipe.Tasks.capacity) |id| { + const outputs = try gpa.alloc([]u8, 1); + outputs[0] = try gpa.dupe(u8, "cancelled result"); + queue.push(.{ .pipe = .{ .id = @intCast(id), .success = true, .outputs = outputs } }); + } + queue.discardCompletions(); + queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "late before Restore") } }); + try std.testing.expectEqual(@as(usize, 0), queue.completion_len); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("retained", batch.items[0].output.bytes); + + queue.lsp_id = 10; + queue.push(.{ .lsp = .{ .id = 10, .rows = null } }); + queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "late after Restore") } }); + var next = queue.take(); + defer for (next.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), next.len); + try std.testing.expectEqual(@as(u32, 10), next.items[0].lsp.id); + try std.testing.expect(next.items[0].lsp.rows == null); + + queue.push(.{ .lsp = .{ .id = 10, .rows = try gpa.dupe(u8, "closing result") } }); + queue.push(.{ .pipe = .{ + .id = 17, + .success = false, + .outputs = &.{}, + .failure = .{ .stderr = try gpa.dupe(u8, "closing failure") }, + } }); + queue.close(); + queue.push(.{ .lsp = .{ .id = 10, .rows = try gpa.dupe(u8, "late closed result") } }); + queue.push(.{ .pipe = .{ + .id = 18, + .success = false, + .outputs = &.{}, + .failure = .{ .stderr = try gpa.dupe(u8, "late closed failure") }, + } }); + try std.testing.expectEqual(@as(usize, 0), queue.take().len); +} + +test "LSP query answers, and a newer one cancels it" { + const gpa = std.testing.allocator; + const io = std.testing.io; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + _ = try core.setTestFile("abc"); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + for (0..2) |_| { + core.lspRequest(core.view().active, .status, ""); + queue.startLsp(core, .{ .id = core.lsp_ask.wait.?.id, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); + } + const last = core.lsp_ask.wait.?.id; + queue.lsp_task.?.future.await(io); + queue.lsp_task = null; + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqual(last, batch.items[0].lsp.id); + try std.testing.expect(batch.items[0].lsp.rows != null); + core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); + try std.testing.expect(core.lsp_ask.wait == null); +} + +test "a plumbing rule's program starts detached, or says why not: a program not found, a directory not there" { + if (comptime builtin.os.tag != .linux) return; + var why: [64]u8 = undefined; + try std.testing.expect(startDetached(null, "/\x00true\x00", &why) == null); + try std.testing.expectEqualStrings("not found", startDetached(null, "/\x00no-such-program-x\x00", &why).?); + try std.testing.expectEqualStrings("its directory: no such directory", startDetached(null, "/no/such/dir\x00true\x00", &why).?); + try std.testing.expectEqualStrings("malformed", startDetached(null, "/\x00true", &why).?); +} diff --git a/dev/jump_trail.zig b/dev/jump_trail.zig new file mode 100644 index 00000000..25eba636 --- /dev/null +++ b/dev/jump_trail.zig @@ -0,0 +1,87 @@ +//! JumpTrail: a jump of the cursor, three cells or more between two frames, +//! leaves a trail of three to five cells behind it along its path, most +//! beside the cursor, all fading out over 120 ms. A frontend's own: it sees +//! the cursor of the Surface it shows, frame after frame, and times the fade +//! on its own clock; the tty tints those cells' ground toward the text, the +//! window draws over them. Nothing of it reaches the core, which keeps the +//! setting alone (config.Runtime.jump_trail). +const std = @import("std"); + +pub const life_ns: u64 = 120 * std.time.ns_per_ms; + +/// A cell of the trail, and how far toward the text it is drawn (0 to 1). +pub const Cell = struct { x: i32, y: i32, strength: f32 }; + +last: ?[2]u16 = null, +from: [2]u16 = .{ 0, 0 }, +to: [2]u16 = .{ 0, 0 }, +start_ns: u64 = 0, +/// Fading: a frontend draws frames until it is not. +active: bool = false, + +const JumpTrail = @This(); + +/// A frame shows the cursor at `cursor` (null: none) at `now_ns`: the +/// trail's cells in it, the one beside the cursor first, or none. +pub fn see(trail: *JumpTrail, cursor: ?[2]u16, on: bool, now_ns: u64, out: *[5]Cell) []const Cell { + const here = cursor orelse { + trail.* = .{}; + return out[0..0]; + }; + 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.* = .{ .from = was, .to = here, .start_ns = now_ns, .active = true }; + } + trail.last = here; + const age = now_ns -| trail.start_ns; + if (!on or !trail.active or age >= life_ns or !std.meta.eql(trail.to, here)) { + trail.active = false; + return out[0..0]; + } + const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); + const fade = (1 - t) * (1 - t); + const dx: f32 = @floatFromInt(@as(i32, trail.from[0]) - trail.to[0]); + const dy: 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 len: usize = 0; + 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; + const strength = 0.55 * fade * (1 - @as(f32, @floatFromInt(k - 1)) / @as(f32, @floatFromInt(n))); + if (strength < 0.02) continue; + out[len] = .{ .x = x, .y = y, .strength = strength }; + len += 1; + } + return out[0..len]; +} + +test "a jump leaves a few cells behind the cursor, fading in 120 ms; a step, or off, leaves none" { + const ms = std.time.ns_per_ms; + var trail: JumpTrail = .{}; + var out: [5]Cell = undefined; + try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 2, 1 }, true, 1000 * ms, &out).len); + // Ten cells right: a trail back toward where it was, on its row, behind + // it, never its own cell, strongest beside it. + const lit = trail.see(.{ 12, 1 }, true, 1016 * ms, &out); + try std.testing.expect(trail.active and lit.len >= 3 and lit.len <= 5); + for (lit, 0..) |cell, i| { + try std.testing.expectEqual(@as(i32, 1), cell.y); + try std.testing.expect(cell.x > 2 and cell.x < 12); + if (i > 0) try std.testing.expect(cell.strength < lit[i - 1].strength and cell.x < lit[i - 1].x); + } + // Gone by 120 ms. + try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 12, 1 }, true, 1150 * ms, &out).len); + try std.testing.expect(!trail.active); + // A step of a cell leaves none; nor does a jump with it off. + try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 13, 1 }, true, 1200 * ms, &out).len); + try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 2, 1 }, false, 1216 * ms, &out).len); + try std.testing.expect(!trail.active); +} diff --git a/dev/lsp/Scip.zig b/dev/lsp/Scip.zig new file mode 100644 index 00000000..839f9117 --- /dev/null +++ b/dev/lsp/Scip.zig @@ -0,0 +1,357 @@ +//! A repository's code intelligence, read from its `index.scip` (SCIP, +//! scip-code.org; the schema is scip.proto in sourcegraph/scip): the +//! language words ask it first and the language server when it has +//! nothing to say (lsp_client.zig). An indexer writes it at the project's +//! root (the Index word runs one); the nearest above a file's directory +//! answers for the file. It is read on the first question that wants it, +//! on the query's worker, off the typing path, and again once it changes. +//! +//! Kept: each document's path, position encoding and occurrences (range, +//! symbol, roles, the enclosing node's range), the symbols interned with +//! their occurrences listed by symbol, and the bytes of each symbol's +//! information, read again when a word wants its documentation, signature, +//! kind or relationships. Skipped: the metadata (paths resolve against +//! the index's own directory), external symbols, syntax kinds, an +//! occurrence's diagnostics and a document's text. +const std = @import("std"); +const statPath = @import("core").filesystem.statPath; + +/// Agave's workspace index is 104 MiB; leave room for it and its lookup tables. +/// A bigger index is refused, in words. +pub const max_bytes = 512 << 20; +const tables_bytes = 512 << 20; +/// Indexes kept loaded at once, the one asked least recently replaced. +const kept = 2; + +pub const Range = struct { sl: u32 = 0, sc: u32 = 0, el: u32 = 0, ec: u32 = 0 }; +/// What a document's characters count (its `position_encoding`). +pub const Enc = enum { utf8, utf16, utf32 }; +/// An occurrence's role bit (scip.proto SymbolRole) for a definition. +pub const role_definition = 1; + +pub const Occurrence = struct { + range: Range, + /// The node a definition names, a function's signature and body, when + /// the indexer gave it; empty otherwise. + enclosing: Range, + symbol: u32, + doc: u32, + roles: u32, +}; + +pub const Document = struct { path: []const u8, enc: Enc, first: u32, len: u32 }; + +pub const Index = struct { + path_buf: [4096]u8 = undefined, + path_len: usize = 0, + mtime: i96 = 0, + size: u64 = 0, + used: u64 = 0, + /// A document newer than the index has been said once. + stale_said: bool = false, + documents: []Document = &.{}, + occurrences: []Occurrence = &.{}, + /// By symbol id: its string, its information's bytes (empty for one + /// defined in no document here), and its occurrences, + /// `order[starts[id]..starts[id + 1]]`. + symbols: std.ArrayList([]const u8) = .empty, + infos: std.ArrayList([]const u8) = .empty, + starts: []u32 = &.{}, + order: []u32 = &.{}, + ids: std.StringHashMapUnmanaged(u32) = .empty, + + pub fn path(ix: *const Index) []const u8 { + return ix.path_buf[0..ix.path_len]; + } + + pub fn root(ix: *const Index) []const u8 { + return std.Io.Dir.path.dirname(ix.path()) orelse "/"; + } + + /// The document of the file at `abs`, or null. + pub fn document(ix: *const Index, abs: []const u8) ?u32 { + const r = ix.root(); + if (abs.len <= r.len + 1 or !std.mem.startsWith(u8, abs, r) or abs[r.len] != '/') return null; + for (ix.documents, 0..) |d, i| if (std.mem.eql(u8, d.path, abs[r.len + 1 ..])) return @intCast(i); + return null; + } + + /// The innermost occurrence of `doc` at (line, ch), counted in the + /// document's units; one ending at the cursor counts. + pub fn at(ix: *const Index, doc: u32, line: u32, ch: u32) ?u32 { + const d = ix.documents[doc]; + var best: ?u32 = null; + for (d.first..d.first + d.len) |i| { + const r = ix.occurrences[i].range; + if (!holds(r, .{ .sl = line, .sc = ch, .el = line, .ec = ch })) continue; + if (best == null or holds(ix.occurrences[best.?].range, r)) best = @intCast(i); + } + return best; + } + + /// Whether the file at `abs` changed after the index was written. + pub fn stale(ix: *const Index, io: std.Io, abs: []const u8) bool { + const st = statPath(io, abs, .{}) catch return false; + return st.mtime.nanoseconds > ix.mtime; + } + + pub fn of(ix: *const Index, symbol: u32) []const u32 { + return ix.order[ix.starts[symbol]..ix.starts[symbol + 1]]; + } + + /// The definition whose node holds occurrence `o`, the innermost, of a + /// function-like symbol: where the call `o` is made from. + pub fn enclosingDefinition(ix: *const Index, o: u32) ?u32 { + const d = ix.documents[ix.occurrences[o].doc]; + var best: ?u32 = null; + for (d.first..d.first + d.len) |i| { + const def = ix.occurrences[i]; + if (i == o or def.roles & role_definition == 0 or !holds(def.enclosing, ix.occurrences[o].range)) continue; + if (!callable(ix.infos.items[def.symbol])) continue; + if (best == null or holds(ix.occurrences[best.?].enclosing, def.enclosing)) best = @intCast(i); + } + return best; + } +}; + +/// Whether `outer` holds `inner`, its ends included. +pub fn holds(outer: Range, inner: Range) bool { + const starts_before = outer.sl < inner.sl or (outer.sl == inner.sl and outer.sc <= inner.sc); + const ends_after = outer.el > inner.el or (outer.el == inner.el and outer.ec >= inner.ec); + return starts_before and ends_after and (outer.sl != outer.el or outer.sc != outer.ec); +} + +/// A symbol information's kind (5) is a function's or a method's. +pub fn callable(info: []const u8) bool { + const kind = (field(info, 5) orelse return false).int; + return switch (kind) { + 9, 17, 18, 25, 26, 45, 47, 66...72, 74, 76, 80 => true, + else => false, + }; +} + +// ------------------------------------------------------------------ the wire + +/// One field of a Protobuf message: its number, and its varint or its +/// length-delimited bytes (fixed 32- and 64-bit ones are skipped whole). +pub const Field = struct { num: u64, int: u64 = 0, bytes: []const u8 = "" }; + +pub const Reader = struct { + bytes: []const u8, + at: usize = 0, + + pub fn varint(r: *Reader) error{Malformed}!u64 { + var n: u64 = 0; + var shift: u7 = 0; + while (r.at < r.bytes.len and shift < 64) : (shift += 7) { + const b = r.bytes[r.at]; + r.at += 1; + n |= @as(u64, b & 0x7f) << @intCast(shift); + if (b < 0x80) return n; + } + return error.Malformed; + } + + pub fn next(r: *Reader) error{Malformed}!?Field { + if (r.at == r.bytes.len) return null; + const key = try r.varint(); + var f: Field = .{ .num = key >> 3 }; + switch (key & 7) { + 0 => f.int = try r.varint(), + 1 => r.at += 8, + 5 => r.at += 4, + 2 => { + const len = try r.varint(); + if (len > r.bytes.len - r.at) return error.Malformed; + f.bytes = r.bytes[r.at..][0..@intCast(len)]; + r.at += @intCast(len); + }, + else => return error.Malformed, + } + if (r.at > r.bytes.len) return error.Malformed; + return f; + } +}; + +/// The first field `num` of a message. +pub fn field(msg: []const u8, num: u64) ?Field { + var r: Reader = .{ .bytes = msg }; + while (r.next() catch return null) |f| if (f.num == num) return f; + return null; +} + +/// A range written as packed varints, `[line, start, end]` or `[line, +/// start, end line, end]`, or as a SingleLineRange or MultiLineRange +/// message (`typed`), its zeros left out. +fn rangeOf(bytes: []const u8, typed: enum { packed_ints, single, multi }) error{Malformed}!Range { + var v: [4]u32 = @splat(0); + var n: usize = 0; + var r: Reader = .{ .bytes = bytes }; + if (typed == .packed_ints) { + while (r.at < bytes.len and n < 4) : (n += 1) v[n] = @truncate(try r.varint()); + if (n == 3) return .{ .sl = v[0], .sc = v[1], .el = v[0], .ec = v[2] }; + if (n != 4) return error.Malformed; + } else while (try r.next()) |f| if (f.num >= 1 and f.num <= 4) { + v[f.num - 1] = @truncate(f.int); + }; + if (typed == .single) return .{ .sl = v[0], .sc = v[1], .el = v[0], .ec = v[2] }; + return .{ .sl = v[0], .sc = v[1], .el = v[2], .ec = v[3] }; +} + +// ------------------------------------------------------------------ loading + +// Keep the large bounded regions out of the executable's static address range. +var regions: [kept]?[]u8 = @splat(null); +var slots: [kept]Index = @splat(.{}); +var clock: u64 = 0; + +pub const Error = error{ TooBig, Malformed, Unreadable, OutOfMemory }; + +/// The index for a file in `dir`: the nearest `index.scip` there or up to +/// seven directories above, read again when it changed since; null with +/// none. +pub fn find(io: std.Io, dir: []const u8) Error!?*Index { + var buf: [4096]u8 = undefined; + var d = dir; + for (0..8) |_| { + const p = std.fmt.bufPrint(&buf, "{s}/index.scip", .{if (std.mem.eql(u8, d, "/")) "" else d}) catch return null; + if (statPath(io, p, .{})) |st| return try use(io, p, st) else |_| {} + d = std.Io.Dir.path.dirname(d) orelse return null; + } + return null; +} + +fn use(io: std.Io, p: []const u8, st: std.Io.File.Stat) Error!*Index { + clock += 1; + var pick: usize = 0; + for (&slots, 0..) |*ix, i| { + if (std.mem.eql(u8, ix.path(), p) and ix.mtime == st.mtime.nanoseconds and ix.size == st.size) { + ix.used = clock; + return ix; + } + if (ix.used < slots[pick].used) pick = i; + } + if (st.size > max_bytes) return error.TooBig; + const ix = &slots[pick]; + ix.* = .{ .mtime = st.mtime.nanoseconds, .size = st.size, .used = clock, .path_len = p.len }; + @memcpy(ix.path_buf[0..p.len], p); + errdefer ix.* = .{}; + const region = regions[pick] orelse blk: { + const memory = try std.heap.page_allocator.alloc(u8, max_bytes + tables_bytes); + regions[pick] = memory; + break :blk memory; + }; + const file = std.Io.Dir.cwd().openFile(io, p, .{}) catch return error.Unreadable; + defer file.close(io); + const got = file.readPositionalAll(io, region[0..@intCast(st.size)], 0) catch return error.Unreadable; + var fba: std.heap.FixedBufferAllocator = .init(region[max_bytes..]); + parse(ix, region[0..got], fba.allocator()) catch |e| return if (e == error.OutOfMemory) error.TooBig else error.Malformed; + return ix; +} + +/// Two walks over the documents: one counts them and their occurrences, +/// the other fills the tables sized from the counts. +fn parse(ix: *Index, bytes: []const u8, a: std.mem.Allocator) !void { + var docs: usize = 0; + var occs: usize = 0; + var r: Reader = .{ .bytes = bytes }; + while (try r.next()) |f| if (f.num == 2) { + docs += 1; + var d: Reader = .{ .bytes = f.bytes }; + while (try d.next()) |g| occs += @intFromBool(g.num == 2); + }; + ix.documents = try a.alloc(Document, docs); + ix.occurrences = try a.alloc(Occurrence, occs); + occs = 0; + docs = 0; + r = .{ .bytes = bytes }; + while (try r.next()) |f| if (f.num == 2) { + const doc = &ix.documents[docs]; + doc.* = .{ .path = "", .enc = .utf8, .first = @intCast(occs), .len = 0 }; + var d: Reader = .{ .bytes = f.bytes }; + while (try d.next()) |g| switch (g.num) { + 1 => doc.path = g.bytes, + 2 => { + const o = &ix.occurrences[occs]; + o.* = .{ .range = .{}, .enclosing = .{}, .symbol = 0, .doc = @intCast(docs), .roles = 0 }; + var name: []const u8 = ""; + var e: Reader = .{ .bytes = g.bytes }; + while (try e.next()) |h| switch (h.num) { + 1 => o.range = try rangeOf(h.bytes, .packed_ints), + 2 => name = h.bytes, + 3 => o.roles = @truncate(h.int), + 7 => o.enclosing = try rangeOf(h.bytes, .packed_ints), + 8, 10 => (if (h.num == 8) &o.range else &o.enclosing).* = try rangeOf(h.bytes, .single), + 9, 11 => (if (h.num == 9) &o.range else &o.enclosing).* = try rangeOf(h.bytes, .multi), + else => {}, + }; + o.symbol = try intern(ix, a, name, docs); + occs += 1; + }, + 3 => if (field(g.bytes, 1)) |s| { + const id = try intern(ix, a, s.bytes, docs); + ix.infos.items[id] = g.bytes; + }, + 6 => doc.enc = switch (g.int) { + 2 => .utf16, + 3 => .utf32, + else => .utf8, + }, + else => {}, + }; + doc.len = @intCast(occs - doc.first); + docs += 1; + }; + // The occurrences listed by symbol: counted, the counts summed, filled. + ix.starts = try a.alloc(u32, ix.symbols.items.len + 1); + @memset(ix.starts, 0); + for (ix.occurrences) |o| ix.starts[o.symbol + 1] += 1; + for (1..ix.starts.len) |i| ix.starts[i] += ix.starts[i - 1]; + ix.order = try a.alloc(u32, ix.occurrences.len); + const filled = try a.alloc(u32, ix.symbols.items.len); + @memset(filled, 0); + for (ix.occurrences, 0..) |o, i| { + ix.order[ix.starts[o.symbol] + filled[o.symbol]] = @intCast(i); + filled[o.symbol] += 1; + } +} + +/// A symbol's id, a `local N` one's in its document alone (its key is the +/// document's number and the name), the first time it is met a new one. +fn intern(ix: *Index, a: std.mem.Allocator, name: []const u8, doc: usize) !u32 { + var buf: [64]u8 = undefined; + const local = std.mem.startsWith(u8, name, "local "); + const key = if (local) std.fmt.bufPrint(&buf, "{d} {s}", .{ doc, name }) catch return error.Malformed else name; + const got = try ix.ids.getOrPut(a, key); + if (!got.found_existing) { + if (local) got.key_ptr.* = try a.dupe(u8, key); + got.value_ptr.* = @intCast(ix.symbols.items.len); + try ix.symbols.append(a, name); + try ix.infos.append(a, ""); + } + return got.value_ptr.*; +} + +test "a varint and every wire type a reader skips" { + var r: Reader = .{ .bytes = &.{ 0xac, 0x02 } }; + try std.testing.expectEqual(@as(u64, 300), try r.varint()); + // field 1 varint 7, field 2 fixed64, field 3 bytes "hi", field 4 fixed32, field 5 varint 1 + const msg = [_]u8{ 0x08, 0x07, 0x11 } ++ @as([8]u8, @splat(9)) ++ [_]u8{ 0x1a, 0x02, 'h', 'i', 0x25 } ++ @as([4]u8, @splat(9)) ++ [_]u8{ 0x28, 0x01 }; + try std.testing.expectEqual(@as(u64, 7), field(&msg, 1).?.int); + try std.testing.expectEqualStrings("hi", field(&msg, 3).?.bytes); + try std.testing.expectEqual(@as(u64, 1), field(&msg, 5).?.int); + try std.testing.expect(field(&msg, 6) == null); + // cut short, an unknown wire type, a length past the end + for ([_][]const u8{ &.{0x80}, &.{ 0x0b, 0x00 }, &.{ 0x1a, 0x05, 'h' } }) |bad| { + var b: Reader = .{ .bytes = bad }; + try std.testing.expectError(error.Malformed, b.next()); + } +} + +test "ranges in the packed form and the typed ones, zeros left out" { + try std.testing.expectEqual(Range{ .sl = 3, .sc = 4, .el = 3, .ec = 7 }, try rangeOf(&.{ 3, 4, 7 }, .packed_ints)); + try std.testing.expectEqual(Range{ .sl = 1, .sc = 0, .el = 2, .ec = 5 }, try rangeOf(&.{ 1, 0, 2, 5 }, .packed_ints)); + try std.testing.expectEqual(Range{ .sl = 0, .sc = 0, .el = 0, .ec = 3 }, try rangeOf(&.{ 0x18, 3 }, .single)); + try std.testing.expectEqual(Range{ .sl = 2, .sc = 0, .el = 4, .ec = 1 }, try rangeOf(&.{ 0x08, 2, 0x18, 4, 0x20, 1 }, .multi)); + try std.testing.expectError(error.Malformed, rangeOf(&.{ 1, 2 }, .packed_ints)); +} diff --git a/dev/lsp/lsp_client.zig b/dev/lsp/lsp_client.zig new file mode 100644 index 00000000..83aea44f --- /dev/null +++ b/dev/lsp/lsp_client.zig @@ -0,0 +1,3183 @@ +//! A real Language Server Protocol client: child processes spoken to over +//! JSON-RPC 2.0 with `Content-Length` framing. Nothing here knows any single +//! language — `specs` is a table of (binary, languageId, extensions, root +//! markers), and zls, rust-analyzer, clangd and gopls are rows in it: every +//! language pardes answers questions about. +//! +//! THE PROCESS LIFECYCLE IS THE DESIGN. `lsp.query` is a synchronous call on a +//! worker thread, and a language server costs tens of milliseconds to start +//! and MINUTES to index a large workspace. So a server is spawned lazily on +//! the first query that needs it, kept for the life of the editor, and each +//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` +//! because a canceled query can still be inside `run` when the next arrives. +//! Every wait is an `Io` cancelation point: a shell cancels the worker of a +//! query it no longer wants, and the worker stops there. +//! +//! ONE READER THREAD PER SERVER, and it is not optional. The first design +//! pumped the socket only while a query waited, which works for a server that +//! only ever answers. A real server TALKS: rust-analyzer streams `$/progress` +//! for the whole minutes-long index of a big workspace, publishes diagnostics +//! it was never asked for, and asks its own `workspace/configuration` +//! questions mid-flight. The reader owns the read side of the socket, routes +//! responses to the one waiting query (a mailbox under the conn's mutex), +//! answers server-to-client requests so the server never blocks on us, feeds +//! the diagnostics store, and narrates state changes through `status sink` — +//! the shell posts them to `Pardes.setMessage`, so "rust-analyzer indexing 45%" +//! lands on the same transient message row a save narrates into. The reader is +//! also the ONLY closer of its socket fd: teardown calls `shutdown(2)` and the +//! reader closes on the EOF it then reads, so the fd number cannot be recycled +//! under a thread still polling it. +//! +//! Nothing here may wedge the editor: +//! - every write is bounded by a deadline, and every mailbox wait by a +//! deadline or, while the server narrates progress, by cancelation, +//! - a query the server does not answer in time returns no rows and sends +//! `$/cancelRequest`; the server is NOT killed for being busy (an indexing +//! server is busy for minutes and the status row says so) — but three +//! consecutive timeouts mean wedged, and wedged is killed and respawned, +//! - the transport is an AF_UNIX socketpair, so a dead server answers EPIPE +//! from `send(MSG_NOSIGNAL)` instead of killing pardes with SIGPIPE +//! (ignoring SIGPIPE process-wide would be inherited by every pty shell we +//! fork and would change what `yes | head` does in a pane), +//! - a binary missing from PATH costs one cached probe, disables the spec +//! for the session, and says so ONCE on the message row. +//! +//! Position encoding is negotiated to utf-8 and the SERVER'S ANSWER is +//! believed, not our request; the utf-16 conversion is implemented in both +//! directions for servers that refuse (`Req.offset` is a byte offset, and a +//! misconverted column is wrong on every line with non-ASCII in it). +const std = @import("std"); +const builtin = @import("builtin"); +const libc = std.c; +const lsp = @import("core").lsp; +const Scip = @import("Scip.zig"); + +extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn usleep(usec: c_uint) c_int; +extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; +// test-only libc (the seam's own tests build a real directory tree) +extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; +extern "c" fn system(cmd: [*:0]const u8) c_int; + +/// darwin has no MSG_NOSIGNAL and gets SO_NOSIGPIPE on the socket instead, +/// set right after socketpair. +const msg_nosignal = if (builtin.os.tag.isDarwin()) 0 else libc.MSG.NOSIGNAL; + +/// One language server this client knows how to run. Adding a language is +/// adding a row; nothing below the table branches on a language. +const Spec = struct { + /// what the message row and `SPC l i` call it + name: []const u8, + /// argv[0], searched on PATH unless it contains a slash + bin: []const u8, + args: []const []const u8 = &.{}, + /// the protocol's `languageId` for didOpen + lang: []const u8, + /// extensions that route a file here (the seam asks `speaks`) + exts: []const []const u8, + /// project markers, walked UP from the file: the TOP-MOST directory + /// holding one is the root (helix's find_root rule), `.git` the fallback + markers: []const []const u8, + /// environment override: a binary path/name to use instead of `bin`, or + /// empty ("") to disable the spec entirely. How the snapshot harness pins + /// a deterministic mock server, and how a user points at a custom build. + env: [:0]const u8, + /// The command that writes the language's `index.scip` at the project + /// root (Scip.zig), which the Index word runs there; `PARDES_SCIP_*` + /// (the env's language) names another. + indexer: []const u8, +}; + +/// Each spec's indexer override, `PARDES_SCIP_RS` beside `PARDES_LSP_RS`. +const indexer_envs = blk: { + var names: [specs.len][:0]const u8 = undefined; + for (specs, &names) |spec, *name| name.* = "PARDES_SCIP_" ++ spec.env["PARDES_LSP_".len..]; + break :blk names; +}; + +pub const specs = [_]Spec{ + .{ + .name = "zls", + .bin = "zls", + .lang = "zig", + .exts = &.{".zig"}, + .markers = &.{ "build.zig", "build.zig.zon" }, + .env = "PARDES_LSP_ZIG", + .indexer = "scip-zig", + }, + .{ + .name = "rust-analyzer", + .bin = "rust-analyzer", + .lang = "rust", + .exts = &.{".rs"}, + .markers = &.{ "Cargo.toml", "rust-project.json" }, + .env = "PARDES_LSP_RS", + .indexer = "rust-analyzer scip .", + }, + .{ + .name = "clangd", + .bin = "clangd", + .lang = "c", + .exts = &.{ ".c", ".h", ".cc", ".cpp", ".hpp", ".cxx", ".hxx" }, + .markers = &.{ "compile_commands.json", "compile_flags.txt", ".clangd" }, + .env = "PARDES_LSP_C", + .indexer = "scip-clang", + }, + .{ + .name = "gopls", + .bin = "gopls", + .lang = "go", + .exts = &.{".go"}, + .markers = &.{ "go.mod", "go.work" }, + .env = "PARDES_LSP_GO", + .indexer = "scip-go", + }, + .{ + .name = "typescript-language-server", + .bin = "typescript-language-server", + .args = &.{"--stdio"}, + .lang = "typescript", + .exts = &.{ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs" }, + .markers = &.{ "tsconfig.json", "jsconfig.json", "package.json" }, + .env = "PARDES_LSP_TS", + .indexer = "scip-typescript index", + }, + .{ + .name = "pyright", + .bin = "pyright-langserver", + .args = &.{"--stdio"}, + .lang = "python", + .exts = &.{".py"}, + .markers = &.{ "pyproject.toml", "setup.py", "requirements.txt" }, + .env = "PARDES_LSP_PY", + .indexer = "scip-python index .", + }, +}; + +/// Everything. Whether one SERVER can answer is a capability question +/// answered per connection; a kind its server never advertised simply returns +/// no rows, which the harness reports as CLAIMED-EMPTY per language — honest, +/// since the claim here is about the protocol, not about every server. +pub const supports: std.EnumSet(lsp.Kind) = .full; + +/// Routing: an extension in the table whose spec is not disabled by its env +/// var. Deliberately does NOT probe for the binary — this runs on the Tab +/// keystroke. A missing binary is discovered at spawn, disables the spec, and +/// says so once on the message row; until then Tab in a `.rs` file diverts, +/// gets "no rows" instantly (the disabled flag short-circuits), and indents +/// late exactly like any other unanswerable completion. +pub fn speaks(path: []const u8) bool { + return specFor(path) != null; +} + +fn specFor(path: []const u8) ?usize { + for (&specs, 0..) |*s, i| { + for (s.exts) |e| { + if (!std.mem.endsWith(u8, path, e)) continue; + if (libc.getenv(s.env)) |v| if (v[0] == 0) return null; // "" disables + return i; + } + } + return null; +} + +// Deadlines. A shell cancels-and-joins the previous worker on a new query, +// and its waits are cancelation points: so a request needs no deadline to +// keep the editor responsive, and waits for its answer. Past req_ms the +// message row says the server is still at it; only a server silent and idle +// (no $/progress) for wedge_ms has failed to answer. Timeouts do NOT kill the +// server — an indexing rust-analyzer legitimately sits on a `gd` for minutes. +// The handshake runs protected from cancelation, so it keeps its deadline. +const init_ms = 8_000; // spawn + initialize handshake +const req_ms = 4_000; // a request past this is said to be still working +const wedge_ms = 300_000; // silent and idle this long: not answering (rust-analyzer takes ~1 min on `default`'s callers in agave) +const diag_ms = 1_200; // wait for a publishDiagnostics push after didChange +const reply_ms = 2_000; // our answers to server-to-client requests +const reply_queue_bytes = 64 << 10; // replies waiting for the socket (Conn.replies) +const parse_kept = 1 << 20; // what the reader's parse arena keeps between messages +const max_diag_files = 256; // files a server's pushed diagnostics are kept for +const max_diag_bytes = 32 << 20; // and their bytes +const wedged_strikes = 3; // consecutive timeouts before a restart + +/// Rows one answer may hold, and its writer's bytes: carved from the query's +/// fixed region (memory.limits.arena.lsp_query) with the rest of its memory. +const max_rows = 100_000; +/// What a Callstack walk leaves of its query's region for rendering the +/// tree it found: past this it stops and says so. +const callstack_reserve = 32 << 20; +/// What rendering leaves of the answer's writer for its closing line. +const row_room = 4096; +const max_doc_bytes = 8 << 20; + +const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed, Canceled }; + +/// Long-lived state outlives every query arena and cannot borrow the caller's +/// gpa (a different one shows up in the harness than in the shell), so +/// connections own their memory from the page allocator. +const sa = std.heap.page_allocator; + +/// Which units `character` counts in — see the header note on believing the +/// server. +const Enc = Scip.Enc; + +const Doc = struct { + uri: []u8, + version: u32, + /// content hash: a query whose buffer has not moved since the last one + /// sends no didChange at all, which is most of what makes warm queries fast + hash: u64, + /// a didChange the server has not answered with diagnostics yet + stale: bool = true, +}; + +/// The last publishDiagnostics per file, kept as raw params and re-parsed +/// against a query's arena. The accumulation IS workspace diagnostics for a +/// server with no pull support. +const DiagSet = struct { uri: []u8, body: []u8 }; + +/// The slice of server capabilities this client changes behaviour on. Silent +/// kinds (a server with no renameProvider) need no flag — the request errors +/// and errors render as no rows. These four either pick between two code +/// paths or gate a second round trip. +const Caps = struct { + enc: Enc = .utf16, + /// textDocument/diagnostic (LSP 3.17 pull) — preferred over the push store + pull: bool = false, + /// workspace/diagnostic + pull_workspace: bool = false, + call_hier: bool = false, + type_hier: bool = false, + /// workspace/didChangeWorkspaceFolders is worth sending + folders: bool = false, +}; + +const State = enum(u8) { + /// never spawned — the row every spec starts on + off, + /// spawned, initialize in flight + starting, + ready, + /// transport broke or the server was declared wedged; next query respawns + dead, + /// binary missing or two failed handshakes; stays down for the session + disabled, +}; + +const Conn = struct { + mu: std.Io.Mutex = .init, + cond: std.Io.Condition = .init, + /// Frames go out whole: a query's requests and the reader's replies + /// share the socket, and interleaved halves are a parse error that ends + /// the server. + write_mu: std.Io.Mutex = .init, + /// Replies the reader made while a query's write held the socket, sent + /// by that writer once its own message is out (releaseWrite): the reader + /// never waits to write, since a server blocked on its output reads + /// nothing more of ours. + /// Two halves: the reader appends to `replies[filling]`, and the writer + /// flips them and sends the other, with no copy and no wait. + replies: [2][reply_queue_bytes]u8 = undefined, + replies_len: [2]usize = .{ 0, 0 }, + filling: u1 = 0, + replies_mu: std.Io.Mutex = .init, + state: State = .off, + /// bumped per spawn. A reader thread that sees a different gen than its + /// own is reading a corpse and exits; a waiter that sees one stops waiting. + gen: u32 = 0, + handshake_fails: u8 = 0, + /// monotonic ms before which a dead/failed server is not respawned — + /// exponential backoff against forking a doomed child per keystroke + retry_after_ms: i64 = 0, + /// monotonic ms when the last handshake completed — a crash shortly + /// after "ready" counts as a handshake failure for backoff purposes + ready_at_ms: i64 = 0, + timeouts: u8 = 0, + pid: libc.pid_t = -1, + sock: c_int = -1, + next_id: u32 = 1, + caps: Caps = .{}, + /// the workspace root sent in initialize (sa-owned) + root: []u8 = &.{}, + /// roots added since, via didChangeWorkspaceFolders (sa-owned entries) + extra_roots: std.ArrayList([]u8) = .empty, + docs: std.ArrayList(Doc) = .empty, + diags: std.ArrayList(DiagSet) = .empty, + /// The bytes `diags` holds, kept under max_diag_bytes. + diag_bytes: usize = 0, + /// the response mailbox: one request outstanding per connection + want_id: u32 = 0, + resp: ?[]u8 = null, + /// active $/progress begins, and the last begin's title for report rows + progress: i32 = 0, + title: [48]u8 = @splat(0), + title_len: u8 = 0, + /// The server says it is still loading its workspace (rust-analyzer's + /// serverStatus, not quiescent): an empty answer now is not one. + loading: bool = false, + /// its index in `conns`, for what it posts + si: usize = 0, + + fn alive(c: *const Conn) bool { + return c.state == .starting or c.state == .ready; + } +}; + +var conns: [specs.len]Conn = @splat(.{}); + +// ------------------------------------------------------------- status sink + +/// One registered listener for unsolicited state changes; both native shells +/// register at startup and DEREGISTER before tearing their loop down — the +/// registry lock is held across the callback, so a null-ing shell cannot race +/// a reader thread mid-post. The callback must copy `text` before returning. +var sink_mu: std.atomic.Mutex = .unlocked; +var sink_ctx: ?*anyopaque = null; +var sink_cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null; +/// throttle for chatty progress reports, per spec +var sink_last_ms: [specs.len]i64 = @splat(0); +var sink_last_text: [specs.len][96]u8 = @splat(@splat(0)); +var sink_last_len: [specs.len]u8 = @splat(0); + +pub fn setStatusSink(ctx: ?*anyopaque, cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void) void { + while (!sink_mu.tryLock()) std.atomic.spinLoopHint(); + defer sink_mu.unlock(); + sink_ctx = ctx; + sink_cb = cb; +} + +const Chat = enum { + /// a progress report: at most one per 150ms per server, dropped when it + /// repeats the previous text — rust-analyzer emits thousands over a big + /// index and the message row repaints per post + chatty, + /// a state change: starting, ready, exited, errors. Always posted. + always, +}; + +fn post(si: usize, chat: Chat, comptime fmt: []const u8, args: anytype) void { + var buf: [192]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + w.print(fmt, args) catch {}; // a long one is cut at the row's end + const text = w.buffered(); + while (!sink_mu.tryLock()) std.atomic.spinLoopHint(); + defer sink_mu.unlock(); + const cb = sink_cb orelse return; + // Repeating the row that is already showing is never news, whatever the + // class — and it is what makes the FINAL state deterministic for the + // snapshot harness: however many intermediate reports the throttle let + // through, an `.always` end state lands exactly once. + const cut = @min(text.len, sink_last_text[si].len); + if (std.mem.eql(u8, text[0..cut], sink_last_text[si][0..sink_last_len[si]])) return; + if (chat == .chatty) { + const now = nowMs(); + if (now - sink_last_ms[si] < 150) return; + sink_last_ms[si] = now; + } + sink_last_len[si] = @intCast(cut); + @memcpy(sink_last_text[si][0..cut], text[0..cut]); + cb(sink_ctx, text); +} + +// ------------------------------------------------------------- introspection + +const LogEntry = struct { + used: bool = false, + kind: lsp.Kind = .definition, + spec: u8 = 0, + us: u64 = 0, + rows: usize = 0, + err: [24]u8 = @splat(0), + err_len: u8 = 0, + file: [64]u8 = @splat(0), + file_len: u8 = 0, +}; +const log_cap = 24; +var log_buf: [log_cap]LogEntry = @splat(.{}); +var log_next: usize = 0; +var log_total: u64 = 0; +var log_mu: std.atomic.Mutex = .unlocked; + +fn record(si: usize, req: lsp.Req, us: u64, rows: usize, err: []const u8) void { + while (!log_mu.tryLock()) std.atomic.spinLoopHint(); + defer log_mu.unlock(); + const e = &log_buf[log_next]; + e.* = .{ .used = true, .kind = req.kind, .spec = @intCast(si), .us = us, .rows = rows }; + const base = std.Io.Dir.path.basename(req.path); + e.file_len = @intCast(@min(base.len, e.file.len)); + @memcpy(e.file[0..e.file_len], base[0..e.file_len]); + e.err_len = @intCast(@min(err.len, e.err.len)); + @memcpy(e.err[0..e.err_len], err[0..e.err_len]); + log_next = (log_next + 1) % log_cap; + log_total += 1; +} + +fn hideTime() bool { + return @import("core").Messages.Message.noTime(); +} + +/// `SPC l w` narration, threaded through the real path, so it cannot +/// disagree with what `gd` actually did. +const Trace = struct { + on: bool = false, + buf: [16 * 1024]u8 = undefined, + len: usize = 0, + + fn note(t: *Trace, comptime fmt: []const u8, args: anytype) void { + if (!t.on or t.len == t.buf.len) return; + var w: std.Io.Writer = .fixed(t.buf[t.len..]); + w.print(fmt ++ "\n", args) catch {}; + t.len += w.buffered().len; + } +}; + +// ------------------------------------------------------------------- query + +/// What answered a logged query: a server, or `scip`, the index. +fn sourceName(spec: u8) []const u8 { + return if (spec < specs.len) specs[spec].name else "scip"; +} + +fn status(io: std.Io, path: []const u8, out: *std.Io.Writer) !void { + // The index the file would ask first, what it holds and how old it is. + const dir = std.Io.Dir.path.dirname(path) orelse "/"; + if (Scip.find(io, dir)) |found| if (found) |ix| { + var symbols: usize = 0; + for (ix.infos.items) |info| symbols += @intFromBool(info.len > 0); + var newer: usize = 0; + var pbuf: [4096]u8 = undefined; + for (ix.documents) |d| newer += @intFromBool(ix.stale(io, std.fmt.bufPrint(&pbuf, "{s}/{s}", .{ ix.root(), d.path }) catch continue)); + try out.print("scip: {s}, {d} KB, {d} documents, {d} symbols", .{ ix.path(), (ix.size + 999) / 1000, ix.documents.len, symbols }); + if (!hideTime()) { + const secs: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@divTrunc(ix.mtime, std.time.ns_per_s)) }; + const day = secs.getEpochDay().calculateYearDay(); + const md = day.calculateMonthDay(); + try out.print(", indexed {d}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} UTC", .{ day.year, md.month.numeric(), md.day_index + 1, secs.getDaySeconds().getHoursIntoDay(), secs.getDaySeconds().getMinutesIntoHour() }); + } + try out.print(", {d} files newer\n", .{newer}); + } else { + try out.print("scip: no index.scip above {s}", .{dir}); + if (specFor(path)) |si| try out.print("; Index runs {s}", .{if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer}); + try out.writeByte('\n'); + } else |e| try out.print("scip: index.scip above {s}: {s}\n", .{ dir, @errorName(e) }); + try out.print("language servers:\n", .{}); + for (&specs, 0..) |*s, i| { + const c = &conns[i]; + c.mu.lockUncancelable(io); + const state = c.state; + var rootbuf: [256]u8 = undefined; + const rootlen = @min(c.root.len, rootbuf.len); + @memcpy(rootbuf[0..rootlen], c.root[0..rootlen]); + const root = rootbuf[0..rootlen]; + const enc = c.caps.enc; + const ndocs = c.docs.items.len; + const ndiag = c.diags.items.len; + const pull = c.caps.pull; + const chier = c.caps.call_hier; + const thier = c.caps.type_hier; + c.mu.unlock(io); + const env_v = if (libc.getenv(s.env)) |v| std.mem.span(v) else null; + // Never spawned is not off: the first query of its files starts it. + try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) }); + if (state == .ready or state == .starting) { + try out.print(" root {s} {s}", .{ root, @tagName(enc) }); + if (pull) try out.print(" pull-diags", .{}); + if (chier) try out.print(" call-hier", .{}); + if (thier) try out.print(" type-hier", .{}); + try out.print(" docs {d} diag-files {d}", .{ ndocs, ndiag }); + } + if (env_v) |v| try out.print(" [{s}={s}]", .{ s.env, if (v.len == 0) "(disabled)" else v }); + try out.print("\n ", .{}); + for (s.exts) |e| try out.print("{s} ", .{e}); + try out.print("\n", .{}); + } + + while (!log_mu.tryLock()) std.atomic.spinLoopHint(); + defer log_mu.unlock(); + try out.print("\nclient queries ({d} total, keeping {d}):\n", .{ log_total, log_cap }); + var shown: usize = 0; + for (0..log_cap) |i| { + const e = &log_buf[(log_next + i) % log_cap]; + if (!e.used) continue; + shown += 1; + if (hideTime()) { + try out.print(" {s:<18} {s:<14} {s:<20} {d:>4} row(s){s}{s}\n", .{ + @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.rows, + if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], + }); + } else { + try out.print(" {s:<18} {s:<14} {s:<20} {d:>7}us {d:>4} row(s){s}{s}\n", .{ + @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.us, e.rows, + if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], + }); + } + } + if (shown == 0) try out.print(" (none yet — press gd in a file with a server, then ask again)\n", .{}); +} + +/// The Index word's command line: the language's indexer, at the +/// project's root, where the index it writes answers for every file under +/// it (`PARDES_SCIP_RS` and the like name another indexer). +fn indexCommand(req: lsp.Req, out: *std.Io.Writer) !void { + const si = specFor(req.path) orelse return lsp.none(out, "no indexer for {s}", .{std.Io.Dir.path.basename(req.path)}); + const cmd = if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer; + try out.writeAll("@run cd '"); + for (rootOf(std.Io.Dir.path.dirname(req.path) orelse "/", specs[si].markers)) |ch| try if (ch == '\'') out.writeAll("'\\''") else out.writeByte(ch); + try out.print("' && {s}\n", .{cmd}); +} + +fn nowUs() u64 { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) *| 1_000_000 +| @as(u64, @intCast(ts.nsec)) / 1000; +} + +/// Byte offset -> LSP position. `lsp.lineCol` gives the line and the BYTE +/// column; only the column needs re-counting, and only when the server +/// refused utf-8. +fn posOf(src: []const u8, off: u32, enc: Enc) Pos { + const lc = lsp.lineCol(src, off); + if (enc == .utf8) return .{ .line = @intCast(lc.line), .ch = @intCast(lc.col) }; + const bol = @min(off, src.len) - lc.col; + var units: u32 = 0; + var i: usize = bol; + while (i < bol + lc.col) { + const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; + units += if (l == 4 and enc == .utf16) 2 else 1; + i += l; + } + return .{ .line = @intCast(lc.line), .ch = units }; +} + +fn emitOcc(cx: *Cx, ix: *const Scip.Index, o: u32, note: []const u8) Err!void { + const occ = ix.occurrences[o]; + try emitPath(cx, ix.documents[occ.doc].enc, try indexPath(cx.arena, ix, occ.doc), occ.range, note); +} + +/// A symbol's definitions, as rows: named by the symbol, as a type +/// hierarchy's are, or by their source lines. +fn emitDefinitions(cx: *Cx, ix: *Scip.Index, symbol: u32, named: bool) Err!void { + for (ix.of(symbol)) |o| if (ix.occurrences[o].roles & Scip.role_definition != 0) { + const sig = if (Scip.field(ix.infos.items[symbol], 7)) |f| (Scip.field(f.bytes, 5) orelse Scip.Field{ .num = 0 }).bytes else ""; + const note = if (!named) "" else if (sig.len == 0) displayName(ix, symbol) else try std.fmt.allocPrint(cx.arena, "{s} {s}", .{ displayName(ix, symbol), flat(cx.arena, sig) }); + try emitOcc(cx, ix, o, note); + }; +} + +/// The symbols `symbol`'s relationships name with flag `flag` set +/// (scip.proto Relationship: 2 is_reference, 3 is_implementation, 4 +/// is_type_definition), the ones the index knows. +fn related(a: std.mem.Allocator, ix: *const Scip.Index, symbol: u32, flag: u64) Err![]u32 { + var out: std.ArrayList(u32) = .empty; + var r: Scip.Reader = .{ .bytes = ix.infos.items[symbol] }; + while (r.next() catch null) |f| if (f.num == 4) { + const to = Scip.field(f.bytes, 1) orelse continue; + if ((Scip.field(f.bytes, flag) orelse continue).int == 0) continue; + if (ix.ids.get(to.bytes)) |id| try out.append(a, id); + }; + return out.items; +} + +/// The index's answer (Scip.zig), in the rows the server's would make: true +/// when it had one, false to ask the server: no index above the file, a +/// file it does not hold, unsaved changes it has not seen, nothing at the +/// cursor, a symbol it does not know, or a word only a server answers. +fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, out: *std.Io.Writer, tr: *Trace) Err!bool { + switch (kind) { + .definition, .type_definition, .implementation, .references, .select_refs, .hover, .document_symbols, .workspace_symbols, .incoming_calls, .outgoing_calls, .callstack, .supertypes, .subtypes => {}, + else => return false, + } + if (req.dirty) { + tr.note("unsaved changes the index has not seen: the server", .{}); + return false; + } + const dir = std.Io.Dir.path.dirname(req.path) orelse return false; + const ix = (Scip.find(io, dir) catch |e| { + tr.note("index.scip above {s}: {s}", .{ dir, @errorName(e) }); + return false; + }) orelse { + tr.note("no index.scip above {s}", .{dir}); + return false; + }; + const doc = ix.document(req.path) orelse { + tr.note("{s} holds no {s}", .{ ix.path(), std.Io.Dir.path.basename(req.path) }); + return false; + }; + const si = specFor(req.path) orelse 0; + if (ix.stale(io, req.path)) { + tr.note("stale: {s} is newer than the index", .{std.Io.Dir.path.basename(req.path)}); + if (!ix.stale_said) post(si, .always, "{s} is older than {s}: Index makes it again", .{ ix.path(), std.Io.Dir.path.basename(req.path) }); + ix.stale_said = true; + } + const enc = ix.documents[doc].enc; + var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = kind == .callstack }; + for (req.others) |d| try cx.files.append(arena, .{ .path = d.path, .text = d.source }); + if (kind == .document_symbols or kind == .workspace_symbols) { + for (ix.occurrences, 0..) |o, i| { + if (kind == .document_symbols and o.doc != doc) continue; + // A name, never a local or a whole file's module. + if (o.roles & Scip.role_definition == 0 or o.range.sl != o.range.el or std.mem.startsWith(u8, ix.symbols.items[o.symbol], "local ")) continue; + const name = displayName(ix, o.symbol); + if (kind == .workspace_symbols and std.ascii.findIgnoreCase(name, req.arg) == null) continue; + try emitOcc(&cx, ix, @intCast(i), name); + } + tr.note("<- {d} row(s) from the index", .{cx.rows}); + return cx.rows > 0; + } + const pos = posOf(req.source, req.offset, enc); + const at = ix.at(doc, pos.line, pos.ch) orelse { + tr.note("no occurrence at {d}:{d} in {s}", .{ pos.line + 1, pos.ch + 1, ix.path() }); + return false; + }; + const sym = ix.occurrences[at].symbol; + tr.note("{s}: occurrence '{s}' at {d}:{d}", .{ ix.path(), ix.symbols.items[sym], pos.line + 1, pos.ch + 1 }); + switch (kind) { + .definition => try emitDefinitions(&cx, ix, sym, false), + .type_definition => for (try related(arena, ix, sym, 4)) |to| try emitDefinitions(&cx, ix, to, false), + .supertypes => for (try related(arena, ix, sym, 3)) |to| try emitDefinitions(&cx, ix, to, true), + .implementation, .subtypes => for (ix.infos.items, 0..) |_, from| { + if (std.mem.indexOfScalar(u32, try related(arena, ix, @intCast(from), 3), sym) != null) + try emitDefinitions(&cx, ix, @intCast(from), kind == .subtypes); + }, + .references, .select_refs => { + var also = try related(arena, ix, sym, 2); + also = try std.mem.concat(arena, u32, &.{ &.{sym}, also }); + for (also) |of| for (ix.of(of)) |o| if (kind == .references or ix.occurrences[o].doc == doc) try emitOcc(&cx, ix, o, ""); + }, + .hover => { + const info = ix.infos.items[sym]; + var said = false; + if (Scip.field(info, 7)) |sig| if (Scip.field(sig.bytes, 5)) |text| { + try out.writeAll(std.mem.trim(u8, text.bytes, " \t\r\n")); + said = true; + }; + var r: Scip.Reader = .{ .bytes = info }; + while (r.next() catch null) |f| if (f.num == 3) { + if (said) try out.writeAll("\n\n"); + try out.writeAll(std.mem.trim(u8, f.bytes, " \t\r\n")); + said = true; + }; + if (said) try out.writeByte('\n') else tr.note("no documentation for it in the index", .{}); + return said; + }, + .incoming_calls => for (try indexHops(arena, ix, sym)) |hop| for (hop.sites.items) |site| + try emitPath(&cx, ix.documents[hop.doc].enc, try indexPath(arena, ix, hop.doc), site, hop.call.name), + .outgoing_calls => for (ix.of(sym)) |d| { + // The calls inside its definition, each function once, at its + // own definition. + const def = ix.occurrences[d]; + if (def.roles & Scip.role_definition == 0) continue; + var seen: std.ArrayList(u32) = .empty; + const in = ix.documents[def.doc]; + for (ix.occurrences[in.first..][0..in.len]) |o| { + if (o.roles & Scip.role_definition != 0 or !Scip.holds(def.enclosing, o.range) or !Scip.callable(ix.infos.items[o.symbol])) continue; + if (std.mem.indexOfScalar(u32, seen.items, o.symbol) != null) continue; + try seen.append(arena, o.symbol); + try emitDefinitions(&cx, ix, o.symbol, true); + } + break; + }, + .callstack => { + const def = for (ix.of(sym)) |o| { + if (ix.occurrences[o].roles & Scip.role_definition != 0) break ix.occurrences[o]; + } else { + tr.note("no definition of it in the index", .{}); + return false; + }; + // The rows come from the tree alone: the core reads the sources. + cx.no_text = true; + const focus: CallTree.Call = .{ .uri = try indexUri(arena, ix, def.doc), .name = "", .at = def.range }; + try callTree(.{ .index = ix }, si, &cx, enc, focus, try indexHops(arena, ix, sym), tr, req.callstack_depth, req.budget); + return true; + }, + else => unreachable, + } + tr.note("<- {d} row(s) from the index", .{cx.rows}); + return cx.rows > 0; +} + +pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) Err!void { + const req = lsp.explaining(asked); + if (req.kind == .status) return status(io, req.path, out); + if (req.kind == .index) return indexCommand(req, out); + + var tr: Trace = .{ .on = req.kind == .explain }; + // Raw: `alloc` fills a safe build's new memory, all 51 MB of it, per query. + const scratch_buf = (arena.rawAlloc(max_rows * 512, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0 .. max_rows * 512]; + var scratch: std.Io.Writer = .fixed(scratch_buf); + + // The index first: what it answers wants no server. + const t0 = nowUs(); + if (fromIndex(io, arena, req, if (req.kind == .explain) req.explains else req.kind, &scratch, &tr) catch |e| blk: { + tr.note("index: {s}", .{@errorName(e)}); + break :blk false; + }) { + const us = nowUs() -| t0; + const rows = std.mem.count(u8, scratch.buffered(), "\n"); + record(specs.len, req, us, rows, ""); + if (req.kind == .explain) return traceOut(&tr, req, out, rows, us); + return out.writeAll(scratch.buffered()); + } + scratch.end = 0; + const si = specFor(req.path) orelse { + tr.note("STOP: no language server spec matches {s}", .{ + if (req.path.len == 0) "a pane with no file" else req.path, + }); + if (req.kind != .explain) return lsp.none(out, "no language server for {s}", .{if (req.path.len == 0) "a pane with no file" else std.Io.Dir.path.basename(req.path)}); + return traceOut(&tr, req, out, 0, 0); + }; + tr.note("file {s} -> {s} (languageId {s})", .{ std.Io.Dir.path.basename(req.path), specs[si].name, specs[si].lang }); + + const t1 = nowUs(); + var err_name: []const u8 = ""; + var failure: ?Err = null; + answer(io, arena, si, req, &scratch, &tr) catch |e| { + failure = e; + err_name = @errorName(e); + tr.note("ERROR: {s}", .{err_name}); + }; + const us = nowUs() -| t1; + const rows = std.mem.count(u8, scratch.buffered(), "\n"); + record(si, req, us, rows, err_name); + + if (req.kind == .explain) return traceOut(&tr, req, out, rows, us); + // No server to start for the language: said, not "did not answer". + if (failure) |err| if (err == error.NoServer) return lsp.none(out, "language server for {s} not found", .{std.Io.Dir.path.extension(req.path)}); + // Installed, but it failed a moment ago: said so, and when it is tried + // again, not that it is not there. + if (failure) |err| if (err == error.Backoff) { + const c = &conns[si]; + c.mu.lockUncancelable(io); + const left_ms = c.retry_after_ms -| nowMs(); + c.mu.unlock(io); + return lsp.none(out, "{s} failed recently; retry in {d}s", .{ specs[si].name, @divFloor(left_ms + 999, 1000) }); + }; + if (failure) |err| return err; + try out.writeAll(scratch.buffered()); +} + +fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us: u64) std.Io.Writer.Error!void { + if (req.kind != .explain) return; + try out.print("lsp explain — the {s} query at byte {d} of {s}\n\n", .{ + @tagName(req.explains), req.offset, if (req.path.len == 0) "(no file)" else std.Io.Dir.path.basename(req.path), + }); + try out.writeAll(tr.buf[0..tr.len]); + if (hideTime()) + try out.print("\n{d} row(s)\n", .{rows}) + else + try out.print("\n{d} row(s) in {d}us\n", .{ rows, us }); +} + +fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { + const c = &conns[si]; + try c.mu.lock(io); + defer c.mu.unlock(io); + const g = try ensure(c, io, si, arena, req, tr); + const before = out.end; + try attempt(c, io, si, arena, req, out, tr, g); + // An empty answer can beat the startup progress notification onto the wire. + const answered = out.buffered()[before..]; + if (c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) { + const startup_deadline = c.ready_at_ms + 250; + const starting = nowMs() < startup_deadline; + while (starting and !c.loading and c.progress == 0 and c.gen == g and c.alive()) { + if (!try timedWait(c, io, startup_deadline)) break; + } + if (starting or c.loading or c.progress > 0) { + tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); + post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); + while ((c.loading or c.progress > 0) and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); + out.end = before; + try attempt(c, io, si, arena, req, out, tr, g); + } + } +} + +/// One run of a query, and what its failure says of the server. +fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace, g: u32) Err!void { + run(c, io, si, arena, req, out, tr) catch |e| { + switch (e) { + // transport-level: this server is gone; forget it, and the next + // query respawns. Gen-checked so a respawn that happened while we + // waited is not the one we kill. + error.Dead, error.Protocol => shutdownIf(c, io, g), + error.Timeout => { + // Slow is only wedged when the server is IDLE. One with + // active `$/progress` work (rust-analyzer running cargo + // check over a thousand crates) is demonstrably alive, is + // narrating its own excuse on the message row, and killing + // it would throw the index away right before it pays off. + if (c.progress > 0) { + c.timeouts = 0; + } else { + c.timeouts +|= 1; + if (c.timeouts >= wedged_strikes and c.gen == g) { + post(si, .always, "{s} not answering — restarting", .{specs[si].name}); + shutdownIf(c, io, g); + } + } + }, + // Canceled: the shell asked something newer, not a wedged server. + error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed, error.Canceled => {}, + } + return e; + }; + c.timeouts = 0; +} + +/// didOpen the first time a file is seen, didChange when its bytes moved, +/// nothing when they did not — the common case between two presses of gd. +fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { + const hash = std.hash.Wyhash.hash(0, src); + var doc: ?*Doc = null; + for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { + doc = d; + break; + }; + if (doc) |d| if (d.hash == hash) return; + + var b: std.ArrayList(u8) = .empty; + if (doc) |d| { + d.version += 1; + d.hash = hash; + d.stale = true; + try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didChange\",\"params\":{{\"textDocument\":{{\"uri\":", .{}); + try jstr(&b, arena, uri); + try b.print(arena, ",\"version\":{d}}},\"contentChanges\":[{{\"text\":", .{d.version}); + try jstr(&b, arena, src); + try b.appendSlice(arena, "}]}}"); + } else { + if (c.docs.items.len >= 256) return; // a session does not open this many + const owned = try sa.dupe(u8, uri); + c.docs.append(sa, .{ .uri = owned, .version = 1, .hash = hash }) catch { + sa.free(owned); + return error.OutOfMemory; + }; + try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"textDocument\":{\"uri\":"); + try jstr(&b, arena, uri); + try b.print(arena, ",\"languageId\":\"{s}\",\"version\":1,\"text\":", .{specs[si].lang}); + try jstr(&b, arena, src); + try b.appendSlice(arena, "}}}"); + } + // A server busy with what it was sent last reads no more meanwhile + // (clangd parses its compile database at a first open): this waits as + // an answer does, for a cancel or a server that has stopped. + try send(c, io, b.items, nowMs() + wedge_ms); +} + +/// The current-buffer byte column for a (line, ch) position — used only for +/// rows that point at the asking position itself. +fn byteCol(src: []const u8, line: u32, ch: u32, enc: Enc) usize { + var bol: usize = 0; + var n: u32 = 0; + while (n < line) : (n += 1) + bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return ch) + 1; + const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; + return colBytes(src[bol..eol], ch, enc); +} + +fn hierText(arena: std.mem.Allocator, item: std.json.Value) []const u8 { + const name = str(get(item, "name")) orelse ""; + const detail = str(get(item, "detail")) orelse return name; + return std.fmt.allocPrint(arena, "{s} {s}", .{ name, flat(arena, detail) }) catch name; +} + +/// The two-step hierarchy kinds: prepare at the cursor, then follow every +/// item the server returned (usually one). Gated on the server capability so +/// an old server costs zero round trips. +fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { + const call_side = h == .incoming or h == .outgoing; + if (call_side and !c.caps.call_hier) { + tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); + return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); + } + if (!call_side and !c.caps.type_hier) { + tr.note("STOP: {s} does not advertise typeHierarchyProvider", .{specs[si].name}); + return lsp.none(cx.out, "{s} does not answer type hierarchy (no typeHierarchyProvider)", .{specs[si].name}); + } + const prepare: []const u8 = if (call_side) "textDocument/prepareCallHierarchy" else "textDocument/prepareTypeHierarchy"; + const follow: []const u8 = switch (h) { + .incoming => "callHierarchy/incomingCalls", + .outgoing => "callHierarchy/outgoingCalls", + .supers => "typeHierarchy/supertypes", + .subs => "typeHierarchy/subtypes", + }; + const b = try atPos(arena, uri, pos); + const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; + for (items(prepared)) |item| { + const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; + for (items(result)) |entry| switch (h) { + .incoming => { + // one row per CALL SITE, under the caller's name — that is + // what n/N want to walk + const from = get(entry, "from") orelse continue; + const fu = str(get(from, "uri")) orelse continue; + const name = str(get(from, "name")) orelse ""; + const ranges = items(get(entry, "fromRanges")); + if (ranges.len == 0) { + try emitRange(cx, c.caps.enc, fu, get(from, "selectionRange"), name); + } else for (ranges) |r| try emitRange(cx, c.caps.enc, fu, r, name); + }, + .outgoing => { + const to = get(entry, "to") orelse continue; + try emitRange(cx, c.caps.enc, str(get(to, "uri")) orelse continue, get(to, "selectionRange") orelse get(to, "range"), hierText(cx.arena, to)); + }, + .supers, .subs => try emitRange(cx, c.caps.enc, str(get(entry, "uri")) orelse continue, get(entry, "selectionRange") orelse get(entry, "range"), hierText(cx.arena, entry)), + }; + } +} + +fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { + // `explain` narrates the last query asked (a definition, `gd`, when + // none was) — dispatch below on the effective kind so the trace + // follows the code that query really runs. + const kind: lsp.Kind = if (req.kind == .explain) req.explains else req.kind; + + // Both arg-taking kinds are useless without one, and an empty + // workspace/symbol query means "every symbol in the project". + if ((kind == .rename or kind == .workspace_symbols) and req.arg.len == 0) return; + + var uri: std.ArrayList(u8) = .empty; + try uriOf(&uri, arena, req.path); + try syncDoc(c, io, si, arena, uri.items, req.source); + // Every other open file this server answers for, before a query whose + // answer reaches them: zls renames only in the documents it has. + if (lsp.reachesOtherFiles(kind)) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path)) { + var other: std.ArrayList(u8) = .empty; + try uriOf(&other, arena, doc.path); + try syncDoc(c, io, si, arena, other.items, doc.source); + tr.note("synced {s} first", .{std.Io.Dir.path.basename(doc.path)}); + }; + + const pos = posOf(req.source, req.offset, c.caps.enc); + var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack }; + for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); + tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ + @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), + }); + const deadline = nowMs() + req_ms; + + switch (kind) { + .definition, .declaration, .type_definition, .implementation, .references => { + const method = switch (kind) { + .definition => "textDocument/definition", + .declaration => "textDocument/declaration", + .type_definition => "textDocument/typeDefinition", + .implementation => "textDocument/implementation", + else => "textDocument/references", + }; + var b = try atPos(arena, uri.items, pos); + if (kind == .references) try b.appendSlice(arena, ",\"context\":{\"includeDeclaration\":true}"); + tr.note("-> {s} @ {d}:{d}", .{ method, pos.line + 1, pos.ch + 1 }); + const result = (try call(c, io, arena, method, b.items, deadline)) orelse { + tr.note("<- empty (no result, an error response, or null)", .{}); + return; + }; + try locations(&cx, c.caps.enc, result); + tr.note("<- {d} row(s)", .{cx.rows}); + }, + .select_refs => { + const b = try atPos(arena, uri.items, pos); + const result = (try call(c, io, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; + for (items(result)) |h| try emitRange(&cx, c.caps.enc, uri.items, get(h, "range"), ""); + }, + .hover => { + const b = try atPos(arena, uri.items, pos); + const result = (try call(c, io, arena, "textDocument/hover", b.items, deadline)) orelse return; + const contents = get(result, "contents") orelse return; + const text = str(contents) orelse str(get(contents, "value")) orelse blk: { + for (items(contents)) |m| if (str(m) orelse str(get(m, "value"))) |t| break :blk t; + break :blk ""; + }; + if (text.len == 0) return; + try out.writeAll(std.mem.trim(u8, text, " \t\r\n")); + try out.writeByte('\n'); + }, + .document_symbols => { + const b = try docParams(arena, uri.items); + const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; + try walkSymbols(&cx, c.caps.enc, uri.items, result, 0); + }, + .workspace_symbols => { + var b: std.ArrayList(u8) = .empty; + try b.appendSlice(arena, "\"query\":"); + try jstr(&b, arena, req.arg); + const result = (try call(c, io, arena, "workspace/symbol", b.items, deadline)) orelse return; + for (items(result)) |sym| { + const loc = get(sym, "location") orelse continue; + try emitRange(&cx, c.caps.enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), str(get(sym, "name")) orelse ""); + } + }, + .diagnostics => try diagnostics(c, io, arena, &cx, uri.items, deadline), + .workspace_diagnostics => try workspaceDiagnostics(c, io, arena, &cx, deadline), + .rename => { + var b = try atPos(arena, uri.items, pos); + try b.appendSlice(arena, ",\"newName\":"); + try jstr(&b, arena, req.arg); + const result = (try call(c, io, arena, "textDocument/rename", b.items, deadline)) orelse return; + // Other open files that say the old name, should the server + // answer for this file alone (zls renaming at a declaration does, + // whatever it was told): applied here, they would no longer build. + var also: std.ArrayList([]const u8) = .empty; + const old = identAt(req.source, req.offset); + if (old.len > 0) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path) and holdsWord(doc.source, old)) + try also.append(arena, doc.path); + try renameEdits(&cx, c.caps.enc, uri.items, result, req.source, old, also.items); + }, + .format => { + var b = try docParams(arena, uri.items); + try b.appendSlice(arena, ",\"options\":{\"tabSize\":4,\"insertSpaces\":true}"); + const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return; + try formatEdits(&cx, c.caps.enc, result, req.source); + }, + .code_action => { + var b = try docParams(arena, uri.items); + try b.print(arena, ",\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch }); + const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return; + for (items(result)) |ca| { + const title = str(get(ca, "title")) orelse continue; + try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title)); + cx.rows += 1; + } + }, + .completion => { + var b = try atPos(arena, uri.items, pos); + try b.appendSlice(arena, ",\"context\":{\"triggerKind\":1}"); + const result = (try call(c, io, arena, "textDocument/completion", b.items, deadline)) orelse return; + const list = if (get(result, "items")) |it| items(it) else items(result); + const here = lsp.rel(cx.base, cx.cur_path); + var n: usize = 0; + for (list) |item| { + if (n >= 100) break; + const label = str(get(item, "label")) orelse continue; + const detail = str(get(item, "detail")) orelse ""; + var text: std.ArrayList(u8) = .empty; + try text.appendSlice(arena, label); + if (detail.len > 0) { + try text.appendSlice(arena, " "); + try text.appendSlice(arena, flat(arena, detail)); + } + // Every row carries the ASKING position: a completion item has + // no location of its own, so the honest place is where it would + // be inserted. n/N still step the list; Enter goes nowhere new. + try lsp.row(cx.out, here, pos.line, byteCol(req.source, pos.line, pos.ch, c.caps.enc), text.items); + n += 1; + } + }, + .callstack => try callstack(c, io, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth, req.budget), + .incoming_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), + .outgoing_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), + .supertypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .supers, tr), + .subtypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .subs, tr), + .status, .explain, .index => unreachable, + } +} + +// -------------------------------------------------------- kind sub-handlers + +/// Goto/references result shapes: bare Location, Location[], LocationLink[]. +fn locations(cx: *Cx, enc: Enc, result: std.json.Value) Err!void { + if (result == .object) { + try emitRange(cx, enc, str(get(result, "uri")) orelse return, get(result, "range"), ""); + return; + } + for (items(result)) |loc| { + if (get(loc, "targetUri")) |tu| { + const r = get(loc, "targetSelectionRange") orelse get(loc, "targetRange"); + try emitRange(cx, enc, str(tu) orelse continue, r, ""); + } else { + try emitRange(cx, enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), ""); + } + } +} + +/// DocumentSymbol[] nests (`children`), SymbolInformation[] is flat. +fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: u8) Err!void { + if (depth > 8) return; + for (items(node)) |sym| { + const name = str(get(sym, "name")) orelse continue; + if (get(get(sym, "location"), "range")) |r| { + try emitRange(cx, enc, str(get(get(sym, "location"), "uri")) orelse uri, r, name); + } else { + try emitRange(cx, enc, uri, get(sym, "selectionRange") orelse get(sym, "range"), name); + } + if (get(sym, "children")) |kids| try walkSymbols(cx, enc, uri, kids, depth + 1); + } +} + +/// Pull when the server does (LSP 3.17), the push store otherwise. The store +/// path waits briefly for a publish that postdates the didChange we just +/// sent, so `]d` right after an edit sees the new truth, not the old one. +fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { + if (c.caps.pull) { + const b = try docParams(arena, uri); + const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; + for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); + return; + } + var stale = true; + for (c.docs.items) |d| if (std.mem.eql(u8, d.uri, uri)) { + stale = d.stale; + break; + }; + if (stale) try waitFresh(c, io, uri, nowMs() + diag_ms); + try renderStore(c, arena, cx, uri); +} + +fn workspaceDiagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { + if (c.caps.pull_workspace) { + const result = (try call(c, io, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; + for (items(get(result, "items"))) |per| { + const uri = str(get(per, "uri")) orelse continue; + for (items(get(per, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); + } + return; + } + try renderStore(c, arena, cx, null); +} + +/// One diagnostic row: `severity: message`, at the diagnostic's own range. +fn emitDiag(cx: *Cx, enc: Enc, uri: []const u8, dg: std.json.Value, arena: std.mem.Allocator) Err!void { + const sev = num(get(dg, "severity")) orelse 1; + const label: []const u8 = switch (sev) { + 1 => "error", + 2 => "warning", + 3 => "info", + else => "hint", + }; + const msg = try std.fmt.allocPrint(arena, "{s}: {s}", .{ label, flat(arena, str(get(dg, "message")) orelse "") }); + try emitRange(cx, enc, uri, get(dg, "range"), msg); +} + +fn renderStore(c: *Conn, arena: std.mem.Allocator, cx: *Cx, only_uri: ?[]const u8) Err!void { + for (c.diags.items) |d| { + if (only_uri) |u| if (!std.mem.eql(u8, d.uri, u)) continue; + const v = std.json.parseFromSliceLeaky(std.json.Value, arena, d.body, .{}) catch continue; + for (items(get(get(v, "params"), "diagnostics"))) |dg| try emitDiag(cx, c.caps.enc, d.uri, dg, arena); + } +} + +/// Block (mutex released) until the reader marks `uri` fresh or the deadline +/// passes. The reader broadcasts on every publishDiagnostics. +fn waitFresh(c: *Conn, io: std.Io, uri: []const u8, deadline: i64) error{Canceled}!void { + const g = c.gen; + while (c.gen == g and c.alive()) { + var fresh = false; + for (c.docs.items) |d| if (std.mem.eql(u8, d.uri, uri)) { + fresh = !d.stale; + break; + }; + if (fresh) return; + if (!try timedWait(c, io, deadline)) return; + } +} + +/// The identifier at byte `at` of `src`: the word a rename there names. +fn identAt(src: []const u8, at: usize) []const u8 { + const isId = struct { + fn f(ch: u8) bool { + return std.ascii.isAlphanumeric(ch) or ch == '_'; + } + }.f; + var start = @min(at, src.len); + while (start > 0 and isId(src[start - 1])) start -= 1; + var end = @min(at, src.len); + while (end < src.len and isId(src[end])) end += 1; + return src[start..end]; +} + +/// Whether `text` holds `word` as a whole identifier. +fn holdsWord(text: []const u8, word: []const u8) bool { + var from: usize = 0; + while (std.mem.indexOfPos(u8, text, from, word)) |i| : (from = i + 1) { + const before = i == 0 or !(std.ascii.isAlphanumeric(text[i - 1]) or text[i - 1] == '_'); + const end = i + word.len; + const after = end == text.len or !(std.ascii.isAlphanumeric(text[end]) or text[end] == '_'); + if (before and after) return true; + } + return false; +} + +/// (line, character) -> byte offset, or null when the line does not exist or +/// the character runs past its end. End-of-line (character == line length) is +/// a real position — that is where an insert-at-EOL lands. +fn strictOffset(src: []const u8, line: u32, ch: u32, enc: Enc) ?usize { + var bol: usize = 0; + var n: u32 = 0; + while (n < line) : (n += 1) + bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return null) + 1; + const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; + if (enc == .utf8) { + if (ch > eol - bol) return null; + return bol + ch; + } + var units: u32 = 0; + var i: usize = bol; + while (i < eol and units < ch) { + const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; + units += if (l == 4 and enc == .utf16) 2 else 1; + i += l; + } + if (units < ch) return null; + return i; +} + +/// Whole-document Range -> half-open byte span for a MUTATING record. +/// STRICT: null unless both endpoints denote positions that exist in the +/// document — for edits, a clamped range is a wrong edit, and wrong edits +/// fail closed (the render paths keep their forgiving conversions; a row a +/// column off is an inconvenience, a splice a column off is corruption). +fn byteSpan(src: []const u8, range: ?std.json.Value, enc: Enc) ?struct { start: usize, end: usize } { + const r = rangeOf(range) orelse return null; + const start = strictOffset(src, r.sl, r.sc, enc) orelse return null; + const end = strictOffset(src, r.el, r.ec, enc) orelse return null; + if (end < start) return null; + return .{ .start = start, .end = end }; +} + +/// A WorkspaceEdit that stays inside the asked-about file becomes `@put` +/// records the core applies as one undo transaction; anything wider (a real +/// multi-file rename, file creates/renames) becomes a PREVIEW — one location +/// row per would-be edit, in the same buffer `gr` fills, because silently +/// applying a fraction of a workspace rename would be worse than either. +fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value, src: []const u8, old: []const u8, also: []const []const u8) Err!void { + var edits: std.ArrayList(PutEdit) = .empty; + var foreign = false; + + // (uri, edits) per file, from either shape of a WorkspaceEdit + var files: std.ArrayList(struct { []const u8, ?std.json.Value }) = .empty; + if (get(result, "documentChanges")) |dcs| { + for (items(dcs)) |dc| { + if (get(dc, "kind") != null) { + foreign = true; // create/rename/delete file operations + continue; + } + const u = str(get(get(dc, "textDocument"), "uri")) orelse continue; + try files.append(cx.arena, .{ u, get(dc, "edits") }); + } + } else if (get(result, "changes")) |ch| if (ch == .object) { + var it = ch.object.iterator(); + while (it.next()) |e| try files.append(cx.arena, .{ e.key_ptr.*, e.value_ptr.* }); + }; + for (files.items) |f| { + const in_self = std.mem.eql(u8, f[0], self_uri); + if (!in_self) foreign = true; + for (items(f[1])) |ed| { + if (in_self) { + // one malformed edit poisons the WHOLE mutating response: + // applying the valid remainder would be a partial edit set + const span = byteSpan(src, get(ed, "range"), enc) orelse return; + const text = str(get(ed, "newText")) orelse return; + try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }); + } else try emitRange(cx, enc, f[0], get(ed, "range"), flat(cx.arena, str(get(ed, "newText")) orelse "")); + } + } + + // Answered for this file alone while other open files say the old + // name: previewed, never applied, each such file named in a row. + const partial = !foreign and also.len > 0; + if (foreign or partial) { + // the preview needs the self-file rows too — the point is the full map + // Rows as the other files' are, `file:L:C-E` with the range's end. + for (edits.items) |ed| { + const lc = lsp.lineCol(src, ed.start); + const end = lsp.lineCol(src, ed.end); + try lsp.spanRow(cx.out, lsp.rel(cx.base, cx.cur_path), lc.line, lc.col, end.line, end.col, flat(cx.arena, ed.text)); + cx.rows += 1; + } + if (partial) for (also) |path| { + try cx.out.print("{s}: also says {s}, which the server did not rename\n", .{ lsp.rel(cx.base, path), old }); + cx.rows += 1; + }; + return; + } + sortEdits(edits.items); + for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text); +} + +/// TextEdit[] from formatting is by definition about the current document: +/// straight to sorted `@put` records. +fn formatEdits(cx: *Cx, enc: Enc, result: std.json.Value, src: []const u8) Err!void { + var edits: std.ArrayList(PutEdit) = .empty; + for (items(result)) |ed| { + // fail the whole response on the first malformed TextEdit — a subset + // of a format is not a format + const span = byteSpan(src, get(ed, "range"), enc) orelse return; + const text = str(get(ed, "newText")) orelse return; + try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }); + } + sortEdits(edits.items); + for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text); +} + +/// One would-be buffer mutation, on its way to an `@put` record. +const PutEdit = struct { start: usize, end: usize, text: []const u8 }; + +fn sortEdits(edits: []PutEdit) void { + std.mem.sort(PutEdit, edits, {}, struct { + fn lt(_: void, a: PutEdit, b: PutEdit) bool { + return a.start < b.start; + } + }.lt); +} + +/// A bounded static hierarchy. Reuse the prepared item verbatim (including +/// server data), and retain every call-site range rather than just a declaration. +fn hierarchyResult(c: *Conn, io: std.Io, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { + if (jsonDepth(item, 0) > 96) return null; + var body: std.ArrayList(u8) = .empty; + try body.appendSlice(arena, "\"item\":"); + try body.appendSlice(arena, try std.json.Stringify.valueAlloc(arena, item, .{})); + return call(c, io, arena, method, body.items, deadline); +} + +const CallTree = struct { + /// What a node keeps of its caller: its own copies, so the response it + /// came in is freed once its subtree is walked. + const Call = struct { uri: []const u8, name: []const u8, at: Range }; + const Site = struct { range: Range, focus: bool }; + const Node = struct { + call: Call, + ranges: std.ArrayList(Site) = .empty, + children: std.ArrayList(usize) = .empty, + cycle: bool = false, + }; + nodes: std.ArrayList(Node) = .empty, + roots: std.ArrayList(usize) = .empty, + path: [lsp.callstack_max_depth]Hop = undefined, + depth_limit: usize = lsp.callstack_default_depth, + limited: bool = false, + out_of_time: bool = false, + out_of_memory: bool = false, + budget: ?*const std.heap.FixedBufferAllocator = null, + si: usize = 0, + collected: usize = 0, + started_ms: i64 = 0, + narrated: bool = false, + siblings: [lsp.callstack_max_depth]bool = @splat(false), + rendered: usize = 0, + /// The rows rendering the tree takes: the walk stops before `row_cap`, + /// as at the memory limit (`out_of_memory`). + rows: usize = 0, + row_cap: usize = max_rows - 16, + /// The bytes those rows take, over-estimated (the uri for the path it + /// becomes), kept under the answer writer's room. + bytes: usize = 0, + byte_cap: usize = std.math.maxInt(usize), + + /// A row of a caller at `depth`: its tree columns, the uri the path is + /// made from, the name, and room for the address. + fn rowBytes(depth: usize, caller: Call) usize { + return 5 * (depth + 2) + caller.uri.len + caller.name.len + 40; + } + + /// Incoming paths arrive nearest-first. Insert them outermost-first, + /// sharing common caller prefixes and retaining all their call sites. + fn addPath(tree: *CallTree, arena: std.mem.Allocator, path: []const Hop, cycle: bool) Err!void { + var parent: ?usize = null; + var at = path.len; + while (at > 0) { + at -= 1; + const hop = path[at]; + const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items; + const found = for (children) |id| { + if (sameCall(tree.nodes.items[id].call, hop.call)) break id; + } else null; + const depth = path.len - 1 - at; + const id = found orelse blk: { + const id = tree.nodes.items.len; + try tree.nodes.append(arena, .{ .call = .{ .uri = try arena.dupe(u8, hop.call.uri), .name = try arena.dupe(u8, hop.call.name), .at = hop.call.at } }); + tree.rows += 1; + tree.bytes += rowBytes(depth, tree.nodes.items[id].call); + if (parent) |pid| { + try tree.nodes.items[pid].children.append(arena, id); + } else try tree.roots.append(arena, id); + break :blk id; + }; + const node = &tree.nodes.items[id]; + node.cycle = node.cycle or (cycle and at == 0); + for (hop.sites.items) |parsed| { + for (node.ranges.items) |*other| { + if (std.meta.eql(parsed, other.range)) { + other.focus = other.focus or at == 0; + break; + } + } else { + try node.ranges.append(arena, .{ .range = parsed, .focus = at == 0 }); + tree.rows += 1; + tree.bytes += rowBytes(depth + 1, .{ .uri = node.call.uri, .name = "", .at = parsed }); + } + } + parent = id; + } + } +}; + +/// A caller one level up a Callstack: the function, the calls it makes +/// there, and what its own callers are asked by, the server's item or the +/// index's symbol (and document). +const Hop = struct { call: CallTree.Call, sites: std.ArrayList(Range) = .empty, item: ?std.json.Value = null, symbol: u32 = 0, doc: u32 = 0 }; + +/// Where a Callstack's callers come from: the index, else the server. +const Calls = union(enum) { + index: *Scip.Index, + server: struct { c: *Conn, io: std.Io, parse: ?*std.heap.FixedBufferAllocator }, +}; + +fn sameCall(a: CallTree.Call, b: CallTree.Call) bool { + return std.mem.eql(u8, a.uri, b.uri) and std.meta.eql(a.at, b.at); +} + +/// The server's incoming calls as hops, their strings the response's. +fn serverHops(a: std.mem.Allocator, incoming: ?std.json.Value) Err![]Hop { + var hops: std.ArrayList(Hop) = .empty; + for (items(incoming)) |entry| { + const from = get(entry, "from") orelse continue; + const uri = str(get(from, "uri")) orelse continue; + const at = rangeOf(get(from, "selectionRange") orelse get(from, "range")) orelse continue; + if (!std.mem.startsWith(u8, uri, "file:")) continue; + var hop: Hop = .{ .call = .{ .uri = uri, .name = str(get(from, "name")) orelse "(unnamed)", .at = at }, .item = from }; + for (items(get(entry, "fromRanges"))) |r| if (rangeOf(r)) |site| try hop.sites.append(a, site); + try hops.append(a, hop); + } + return hops.items; +} + +/// The index's callers of `symbol` as hops: the definition enclosing each +/// of its references, the references it holds its sites. +fn indexHops(a: std.mem.Allocator, ix: *Scip.Index, symbol: u32) Err![]Hop { + var hops: std.ArrayList(Hop) = .empty; + for (ix.of(symbol)) |o| { + if (ix.occurrences[o].roles & Scip.role_definition != 0) continue; + const def = ix.occurrences[ix.enclosingDefinition(o) orelse continue]; + const hop = for (hops.items) |*h| { + if (h.symbol == def.symbol) break h; + } else blk: { + try hops.append(a, .{ .call = .{ .uri = try indexUri(a, ix, def.doc), .name = displayName(ix, def.symbol), .at = def.range }, .symbol = def.symbol, .doc = def.doc }); + break :blk &hops.items[hops.items.len - 1]; + }; + try hop.sites.append(a, ix.occurrences[o].range); + } + return hops.items; +} + +fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { + for (tree.siblings[0..depth]) |more| try out.writeAll(if (more) "│ " else " "); +} + +fn callstack(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator) Err!void { + if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); + const b = try atPos(arena, uri, pos); + const prepared = (try call(c, io, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; + if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); + // The rows come from the tree alone: the core reads the sources. + cx.no_text = true; + // Each response is parsed into its own part of the region, freed once + // its subtree is walked; only the path being walked is live JSON. + // Raw, as query()'s scratch: `alloc` would fill all ~100 MB of it. + const parse_len = if (budget) |fixed| (fixed.buffer.len - fixed.end_index) / 2 else 0; + var parse_fba: std.heap.FixedBufferAllocator = .init(if (budget != null) + (arena.rawAlloc(parse_len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..parse_len] + else + &.{}); + const parse = if (budget != null) parse_fba.allocator() else arena; + for (items(prepared)) |item| { + const focus: CallTree.Call = .{ .uri = str(get(item, "uri")) orelse continue, .name = "", .at = rangeOf(get(item, "selectionRange") orelse get(item, "range")) orelse continue }; + const incoming = try hierarchyResult(c, io, parse, item, "callHierarchy/incomingCalls", deadline); + const src: Calls = .{ .server = .{ .c = c, .io = io, .parse = if (budget != null) &parse_fba else null } }; + try callTree(src, si, cx, c.caps.enc, focus, try serverHops(parse, incoming), tr, max_depth, budget); + } +} + +/// A Callstack from the first callers of the function asked at: walked to +/// the depth setting, rendered, and why it stopped said. +fn callTree(src: Calls, si: usize, cx: *Cx, enc: Enc, focus: CallTree.Call, first: []const Hop, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator) Err!void { + var tree: CallTree = .{ + .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth), + .si = si, + .started_ms = nowMs(), + .budget = budget, + // The walk stops while the answer's writer has room for the rest. + .byte_cap = if (cx.fixed_out) (cx.out.buffer.len - cx.out.end) -| (1 << 20) else std.math.maxInt(usize), + }; + const count = try collectCallers(src, cx.arena, focus, first, &tree, 0); + if (tree.narrated) post(si, .always, "Callstack: {d} callers", .{tree.collected}); + if (count == 0) try cx.out.writeAll("No callers reported\n"); + try renderCallers(cx, enc, &tree, tree.roots.items, 0); + if (tree.out_of_time) { + try cx.out.writeAll("… the language server ran out of time; continue from a function above with Callstack\n"); + } else if (tree.out_of_memory) { + try cx.out.writeAll("… stopped at the query's memory limit; continue from a function above with Callstack\n"); + } else if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); + tr.note("callstack: {d} callers", .{tree.rendered}); +} + +/// No caller count and no overall deadline: the walk narrates itself on the +/// message row after a second, and it stops when a request goes unanswered +/// or the answer is full (what was collected is shown, its last row saying +/// so), or when the shell cancels it for a newer query. +fn collectCallers(src: Calls, arena: std.mem.Allocator, focus: CallTree.Call, hops: []const Hop, tree: *CallTree, depth: usize) Err!usize { + var count: usize = 0; + for (hops) |hop| { + if (tree.budget) |b| if (b.buffer.len - b.end_index < callstack_reserve) { + tree.out_of_memory = true; + }; + if (tree.rows >= tree.row_cap or tree.bytes >= tree.byte_cap) tree.out_of_memory = true; + if (tree.out_of_time or tree.out_of_memory) break; + const cycle = sameCall(focus, hop.call) or for (tree.path[0..depth]) |ancestor| { + if (sameCall(ancestor.call, hop.call)) break true; + } else false; + tree.path[depth] = hop; + count += 1; + tree.collected += 1; + if (nowMs() - tree.started_ms >= 1000) { + tree.narrated = true; + post(tree.si, .chatty, "Callstack: {d} callers\u{2026}", .{tree.collected}); + } + var children: usize = 0; + if (!cycle) { + if (depth + 1 == tree.depth_limit) { + tree.limited = true; + } else if (src == .index) { + children = try collectCallers(src, arena, focus, try indexHops(arena, src.index, hop.symbol), tree, depth + 1); + } else { + const parse = src.server.parse; + const mark = if (parse) |fixed| fixed.end_index else 0; + defer if (parse) |fixed| { + fixed.end_index = mark; + }; + const a = if (parse) |fixed| fixed.allocator() else arena; + const ancestors = hierarchyResult(src.server.c, src.server.io, a, hop.item.?, "callHierarchy/incomingCalls", nowMs() + req_ms) catch |e| switch (e) { + error.Timeout => blk: { + tree.out_of_time = true; + break :blk null; + }, + // A response bigger than the parse region: this caller + // stops here, the walk with it. + error.OutOfMemory => blk: { + tree.out_of_memory = true; + break :blk null; + }, + else => return e, + }; + if (!tree.out_of_time and !tree.out_of_memory) children = try collectCallers(src, arena, focus, try serverHops(a, ancestors), tree, depth + 1); + } + } + if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); + } + return count; +} + +/// Test callers sink below the rest; each group keeps the usual order. +// ponytail: substring heuristic, "latest.zig" or "contest" count as tests too +fn testCaller(caller: CallTree.Call) bool { + return std.ascii.findIgnoreCase(caller.name, "test") != null or + std.ascii.findIgnoreCase(std.Io.Dir.path.basenamePosix(caller.uri), "test") != null; +} + +fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { + const left = tree.nodes.items[a].call; + const right = tree.nodes.items[b].call; + if (testCaller(left) != testCaller(right)) return testCaller(right); + const uri_order = std.mem.order(u8, left.uri, right.uri); + if (uri_order != .eq) return uri_order == .lt; + return rangeLess(left.at, right.at); +} + +fn rangeLess(left: Range, right: Range) bool { + return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc); +} + +fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void { + std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess); + for (children, 0..) |id, index| { + // emitRange's row ceiling and the writer's room, met here before a + // prefix is half written + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { + tree.limited = true; + return; + } + const node = &tree.nodes.items[id]; + const more = index + 1 < children.len; + try callPrefix(cx.out, tree, depth); + const has_children = node.children.items.len > 0 or node.ranges.items.len > 0; + try cx.out.writeAll(if (more) "├" else "╰"); + try cx.out.writeAll(if (has_children) "──┬ " else "─── "); + const name = flat(cx.arena, node.call.name); + const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name; + try emitAt(cx, enc, node.call.uri, node.call.at, label); + tree.rendered += 1; + tree.siblings[depth] = more; + std.mem.sort(CallTree.Site, node.ranges.items, {}, struct { + fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool { + return rangeLess(a.range, b.range); + } + }.less); + for (node.ranges.items, 0..) |site, site_index| { + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { + tree.limited = true; + return; + } + if (site.focus) try cx.out.writeAll(lsp.callstack_match); + try callPrefix(cx.out, tree, depth + 1); + try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else "╰─ "); + try emitAt(cx, enc, node.call.uri, site.range, ""); + } + try renderCallers(cx, enc, tree, node.children.items, depth + 1); + } +} + +const Hier = enum { incoming, outgoing, supers, subs }; + +/// Depth of a parsed json value, saturating just past `at`'s caller's cap — +/// the guard that keeps server-controlled nesting away from Stringify's +/// fixed-depth assertion. +fn jsonDepth(v: std.json.Value, at: u32) u32 { + if (at > 96) return at; + return switch (v) { + .object => |o| blk: { + var deepest = at; + var it = o.iterator(); + while (it.next()) |e| deepest = @max(deepest, jsonDepth(e.value_ptr.*, at + 1)); + break :blk deepest; + }, + .array => |a| blk: { + var deepest = at; + for (a.items) |e| deepest = @max(deepest, jsonDepth(e, at + 1)); + break :blk deepest; + }, + else => at, + }; +} + +// ---------------------------------------------------------------- the index + +/// A symbol's name to show: its display name, else its string's last +/// descriptor (`... lib/add().` is `add`). +fn displayName(ix: *const Scip.Index, symbol: u32) []const u8 { + if (Scip.field(ix.infos.items[symbol], 6)) |f| return f.bytes; + const s = std.mem.trimEnd(u8, ix.symbols.items[symbol], "().#/:!"); + return s[if (std.mem.lastIndexOfAny(u8, s, " /#.")) |cut| cut + 1 else 0..]; +} + +fn indexPath(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u8 { + return std.fmt.allocPrint(a, "{s}/{s}", .{ ix.root(), ix.documents[doc].path }); +} + +fn indexUri(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u8 { + var b: std.ArrayList(u8) = .empty; + try uriOf(&b, a, try indexPath(a, ix, doc)); + return b.items; +} + +// ------------------------------------------------------------ row rendering + +/// Files read while answering ONE query, so a references list over a handful +/// of files reads each once, not once per row. The current buffer never needs +/// reading: `req.source` IS its text, unsaved edits included. +const Cx = struct { + io: std.Io, + arena: std.mem.Allocator, + base: []const u8, + cur_path: []const u8, + cur_src: []const u8, + out: *std.Io.Writer, + /// `out` is the query's fixed answer buffer, whose room is checked. + fixed_out: bool = false, + /// Rows without their source text (Callstack: the core reads it). + no_text: bool = false, + rows: usize = 0, + relative_parents: bool = false, + files: std.ArrayList(struct { path: []const u8, text: []const u8 }) = .empty, + + fn text(cx: *Cx, path: []const u8) ?[]const u8 { + if (std.mem.eql(u8, path, cx.cur_path)) return cx.cur_src; + for (cx.files.items) |f| if (std.mem.eql(u8, f.path, path)) return f.text; + if (cx.files.items.len >= 32) return null; + const file = std.Io.Dir.cwd().openFile(cx.io, path, .{}) catch return null; + defer file.close(cx.io); + var chunk: [64 * 1024]u8 = undefined; + var file_reader = file.reader(cx.io, &chunk); + var buf: std.ArrayList(u8) = .empty; + // A file past max_doc_bytes is its first max_doc_bytes. + file_reader.interface.appendRemaining(cx.arena, &buf, .limited(max_doc_bytes)) catch |err| switch (err) { + error.StreamTooLong => {}, + else => return null, + }; + cx.files.append(cx.arena, .{ .path = path, .text = buf.items }) catch return null; + return buf.items; + } +}; + +/// One row from an LSP (uri, Range). The uri becomes a real path (percent- +/// decoded, `rel`'d against the asking window), utf-16 columns become byte +/// columns, and a single-line range becomes the `path:LINE:COL-ENDCOL` form a +/// look SELECTS. `note` overrides the source line as the row's text. +fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: []const u8) Err!void { + return emitAt(cx, enc, uri, rangeOf(range) orelse return, note); +} + +/// `file:///a/b%20c` -> `/a/b c`. Rows carry real paths; look.zig opens them +/// and `%20` is not a filename. A decoded CONTROL byte rejects the whole uri: +/// a `%0A` in a path would split one location into two physical rows — a +/// server-forged extra row in the results buffer — and no path worth opening +/// has a newline, tab or NUL in it. +fn pathOf(arena: std.mem.Allocator, uri: []const u8) ?[]const u8 { + var rest = uri; + if (std.mem.startsWith(u8, rest, "file://")) { + rest = rest["file://".len..]; + if (rest.len > 0 and rest[0] != '/') return null; // an authority we cannot open + } else if (std.mem.indexOf(u8, rest, "://") != null) return null; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < rest.len) { + var byte: u8 = rest[i]; + if (rest[i] == '%' and i + 2 < rest.len) { + if (std.fmt.parseInt(u8, rest[i + 1 .. i + 3], 16)) |b| { + byte = b; + i += 3; + } else |_| i += 1; + } else i += 1; + if (byte < 0x20) return null; + out.append(arena, byte) catch return null; + } + return out.items; +} + +fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void { + return emitPath(cx, enc, pathOf(cx.arena, uri) orelse return, r, note); +} + +fn emitPath(cx: *Cx, enc: Enc, path: []const u8, r: Range, note: []const u8) Err!void { + if (cx.rows >= max_rows) return; + if (path.len == 0 or path[0] != '/') return; // rows promise absolute-or-rel-from-base + // Without sources (Callstack) the asking file is still known: its rows' + // columns convert from utf-16 as ever. + const src = if (cx.no_text and !std.mem.eql(u8, path, cx.cur_path)) null else cx.text(path); + + var bol: usize = 0; + var eol: usize = 0; + if (src) |t| { + var n: u32 = 0; + while (n < r.sl) : (n += 1) { + bol = (std.mem.indexOfScalarPos(u8, t, bol, '\n') orelse { + bol = t.len; + break; + }) + 1; + } + eol = std.mem.indexOfScalarPos(u8, t, @min(bol, t.len), '\n') orelse t.len; + } + const lntext: []const u8 = if (src) |t| t[@min(bol, t.len)..@min(eol, t.len)] else ""; + + const col = colBytes(lntext, r.sc, enc); + const shown = if (cx.relative_parents) blk: { + const relative = std.Io.Dir.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path; + break :blk if (relative.len < path.len) relative else path; + } else lsp.rel(cx.base, path); + // A same-line exclusive end byte offset is also the displayed inclusive + // one-based column. Multi-line ranges display only their starting address. + const end_col = if (r.el == r.sl and r.ec > r.sc) colBytes(lntext, r.ec, enc) else col; + if (note.len == 0) { + try lsp.sourceSpanRow(cx.out, shown, r.sl, col, r.el, end_col, lntext); + } else { + try lsp.spanRow(cx.out, shown, r.sl, col, r.el, end_col, note); + } + cx.rows += 1; +} + +/// utf-16 code units -> byte column within one line; identity for utf-8. +fn colBytes(lntext: []const u8, ch: u32, enc: Enc) usize { + if (enc == .utf8 or lntext.len == 0) return ch; + var units: u32 = 0; + var i: usize = 0; + while (i < lntext.len and units < ch) { + const l = std.unicode.utf8ByteSequenceLength(lntext[i]) catch 1; + units += if (l == 4 and enc == .utf16) 2 else 1; + i += l; + } + return i; +} + +/// Prose squashed onto the one line a row is: newlines and tabs to spaces, +/// cut to a width a pane can show. +fn flat(arena: std.mem.Allocator, s: []const u8) []const u8 { + var buf: std.ArrayList(u8) = .empty; + var sp = false; + for (s) |ch| { + if (ch == '\n' or ch == '\r' or ch == '\t' or ch == 0) { + if (!sp and buf.items.len > 0) buf.append(arena, ' ') catch break; + sp = true; + } else { + buf.append(arena, ch) catch break; + sp = false; + } + if (buf.items.len >= 200) break; + } + return std.mem.trim(u8, buf.items, " "); +} + +fn setCloexec(fd: c_int) void { + const FD_CLOEXEC: c_int = 1; + _ = libc.fcntl(fd, libc.F.SETFD, FD_CLOEXEC); +} + +// Darwin needs fcntl after socketpair; another concurrent fork can inherit the pair in that window. +fn transportPair(sv: *[2]libc.fd_t) bool { + const sock_type = if (comptime builtin.os.tag.isDarwin()) + libc.SOCK.STREAM + else + libc.SOCK.STREAM | libc.SOCK.CLOEXEC; + if (libc.socketpair(libc.AF.UNIX, sock_type, 0, sv) != 0) return false; + if (comptime builtin.os.tag.isDarwin()) { + setCloexec(sv[0]); + // The child dup2s this onto 0 and 1, and dup2 CLEARS close-on-exec on + // the copy, so the server still gets the socket; this marks only the + // number itself, which the child's 3..1024 sweep closes anyway. + setCloexec(sv[1]); + const one: c_int = 1; + _ = libc.setsockopt(sv[0], libc.SOL.SOCKET, libc.SO.NOSIGPIPE, @ptrCast(&one), @sizeOf(c_int)); + } + return true; +} + +// ----------------------------------------------------------- the connection + +/// Where the project starts: helix's find_root rule. Walk UP from `dir`; the +/// TOP-MOST directory holding a language marker wins (a cargo workspace's +/// root Cargo.toml beats the member crate's), the CLOSEST `.git` is the +/// fallback, the asking directory the last resort. +fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 { + if (dir.len == 0 or dir[0] != '/') return "/"; + var top_marker: ?[]const u8 = null; + var git: ?[]const u8 = null; + var d = dir; + var buf: [4096:0]u8 = undefined; + while (true) { + for (markers) |marker| { + const p = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d, marker }, 0) catch continue; + if (libc.access(p.ptr, libc.F_OK) == 0) { + top_marker = d; + break; + } + } + if (git == null) { + if (std.fmt.bufPrintSentinel(&buf, "{s}/.git", .{d}, 0)) |p| { + if (libc.access(p.ptr, libc.F_OK) == 0) git = d; + } else |_| {} + } + d = std.Io.Dir.path.dirname(d) orelse break; + if (d.len <= 1) break; + } + return top_marker orelse git orelse dir; +} + +/// The spec's binary: the env override when set, else `bin`, PATH-searched +/// unless it names a path, then the standard per-user bin directory. +fn binOf(spec: *const Spec, buf: *[4096:0]u8) ?[:0]const u8 { + const name = if (libc.getenv(spec.env)) |v| std.mem.span(v) else spec.bin; + const path = if (libc.getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin"; + const home = if (libc.getenv("HOME")) |p| std.mem.span(p) else ""; + return findBin(name, path, home, buf); +} + +fn findBin(name: []const u8, path: []const u8, home: []const u8, buf: *[4096:0]u8) ?[:0]const u8 { + if (name.len == 0) return null; + if (std.mem.indexOfScalar(u8, name, '/') != null) { + const z = std.fmt.bufPrintSentinel(buf, "{s}", .{name}, 0) catch return null; + return if (libc.access(z.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(z.ptr)) z else null; + } + var it = std.mem.tokenizeScalar(u8, path, ':'); + while (it.next()) |dir| { + const cand = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch continue; + if (libc.access(cand.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(cand.ptr)) return cand; + } + // Desktop launchers often omit ~/.local/bin even when shells include it. + if (std.fs.path.isAbsolute(home)) { + const cand = std.fmt.bufPrintSentinel(buf, "{s}/.local/bin/{s}", .{ home, name }, 0) catch return null; + if (libc.access(cand.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(cand.ptr)) return cand; + } + return null; +} + +/// Spawn-or-return, and tell an existing server about a new project root. +/// Returns the generation the caller's whole query is bound to. +fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { + c.si = si; + if (c.state == .disabled) { + tr.note("STOP: {s} is disabled for this session (no binary; set {s})", .{ specs[si].name, specs[si].env }); + return error.NoServer; + } + if (c.alive()) { + const root = rootOf(req.root, specs[si].markers); + if (!std.mem.eql(u8, root, c.root)) { + var known = false; + for (c.extra_roots.items) |r| if (std.mem.eql(u8, r, root)) { + known = true; + break; + }; + if (!known and c.caps.folders) { + var b: std.ArrayList(u8) = .empty; + try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"workspace/didChangeWorkspaceFolders\",\"params\":{\"event\":{\"added\":[{\"name\":\"root\",\"uri\":\""); + try uriOf(&b, arena, root); + try b.appendSlice(arena, "\"}],\"removed\":[]}}}"); + try send(c, io, b.items, nowMs() + wedge_ms); + const owned = try sa.dupe(u8, root); + c.extra_roots.append(sa, owned) catch sa.free(owned); + } + } + return c.gen; + } + + // A recent failed spawn/handshake holds the fork back; the message row + // already said when the next try is due. + if (nowMs() < c.retry_after_ms) { + tr.note("STOP: {s} failed recently; retry due in {d}ms", .{ specs[si].name, c.retry_after_ms - nowMs() }); + return error.Backoff; + } + + // Look before forking; a missing binary must cost one probe and one + // message, not a doomed fork per keystroke. + var exe_buf: [4096:0]u8 = undefined; + const exe = binOf(&specs[si], &exe_buf) orelse { + c.state = .disabled; + post(si, .always, "{s} not found — install it or set {s}", .{ specs[si].name, specs[si].env }); + tr.note("STOP: no {s} binary on PATH (override: {s})", .{ specs[si].bin, specs[si].env }); + return error.NoServer; + }; + + const root = rootOf(req.root, specs[si].markers); + var root_buf: [4096:0]u8 = undefined; + const root_z = std.fmt.bufPrintSentinel(&root_buf, "{s}", .{root}, 0) catch return error.NoServer; + // Owned BEFORE anything spawns: the reader thread is the socket's only + // closer once it exists, so nothing fallible may sit between fork and + // reader-spawn — an abort there would strand the fd. + const owned_root = try sa.dupe(u8, root); + + var sv: [2]libc.fd_t = undefined; + if (!transportPair(&sv)) { + sa.free(owned_root); + tr.note("STOP: socketpair for {s} failed", .{specs[si].name}); + return error.NoServer; + } + if (!exit_hook.swap(true, .acq_rel)) _ = atexit(killAllAtExit); + // ponytail: hand-rolled, not std.process.spawn: 0.17's has no setsid + // (only setpgid), no signal mask/disposition reset and no fd sweep. + const pid = libc.fork(); + if (pid < 0) { + _ = libc.close(sv[0]); + _ = libc.close(sv[1]); + sa.free(owned_root); + tr.note("STOP: fork for {s} failed", .{specs[si].name}); + return error.NoServer; + } + if (pid == 0) { + // Between fork and exec, in a process with threads: only async- + // 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(); + _ = libc.dup2(sv[1], 0); + _ = libc.dup2(sv[1], 1); + const devnull = libc.open("/dev/null", .{ .ACCMODE = .WRONLY }); + if (devnull >= 0) _ = libc.dup2(devnull, 2); + var fd: c_int = 3; + while (fd < 1024) : (fd += 1) _ = libc.close(fd); + _ = libc.chdir(root_z.ptr); + var argv: [8:null]?[*:0]const u8 = @splat(null); + argv[0] = exe.ptr; + // args are comptime literals; the buffers live until execv + var argbufs: [6][64:0]u8 = undefined; + for (specs[si].args, 0..) |a, i| { + if (i >= argbufs.len) break; + const z = std.fmt.bufPrintSentinel(&argbufs[i], "{s}", .{a}, 0) catch break; + argv[1 + i] = z.ptr; + } + _ = execv(exe.ptr, &argv); + libc._exit(127); + } + _ = libc.close(sv[1]); + + // the slate the old generation may have left (a self-died server skips + // shutdownIf) must not leak into the new one: a stale doc entry would + // suppress the didOpen the new server never got + c.gen +%= 1; + const g = c.gen; + c.pid = pid; + c.sock = sv[0]; + c.state = .starting; + c.caps = .{}; + c.next_id = 1; + c.want_id = 0; + if (c.resp) |r| sa.free(r); + c.resp = null; + c.progress = 0; + c.loading = false; + c.timeouts = 0; + forgetDocs(c); + if (c.root.len > 0) sa.free(c.root); + c.root = owned_root; + + const th = std.Thread.spawn(.{}, reader, .{ io, si, g, sv[0] }) catch { + // no reader means nobody would ever close the fd our way; do it here, + // before anything else can see the conn + _ = libc.close(sv[0]); + _ = libc.kill(pid, .KILL); + _ = libc.waitpid(pid, null, 0); + c.state = .dead; + c.sock = -1; + return error.NoServer; + }; + th.detach(); + + post(si, .always, "{s} starting — {s}", .{ specs[si].name, root }); + tr.note("spawned {s} (pid {d}) at {s}", .{ specs[si].name, pid, root }); + + // A start runs to the end however soon the query that began it is + // canceled: killing a half-started server would only make the next + // query start it again. The cancel lands at the next wait instead. + const protection = io.swapCancelProtection(.blocked); + const started = handshake(c, io, arena, root); + _ = io.swapCancelProtection(protection); + started catch |e| { + shutdownIf(c, io, g); + // NOT a session disable. A handshake that misses the deadline is + // routinely environmental — a rustup shim deciding to download the + // project's pinned toolchain before launching the real server was + // the case that taught this — and it heals by itself. What must not + // happen is a fork per keystroke while it heals, so failures back + // off on backoffMs's schedule, reset by the next success. + c.handshake_fails +|= 1; + const wait = backoffMs(c.handshake_fails); + c.retry_after_ms = nowMs() + wait; + post(si, .always, "{s} not answering — retrying in {d}s", .{ + specs[si].name, @divTrunc(wait, 1000), + }); + return switch (e) { + error.OutOfMemory => error.OutOfMemory, + else => error.NoServer, + }; + }; + c.handshake_fails = 0; + c.retry_after_ms = 0; + c.ready_at_ms = nowMs(); + c.state = .ready; + post(si, .always, "{s} ready — {s}", .{ specs[si].name, root }); + return g; +} + +fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) Err!void { + var b: std.ArrayList(u8) = .empty; + try b.print(arena, "\"processId\":{d},\"clientInfo\":{{\"name\":\"pardes\"}},\"rootUri\":\"", .{@as(u32, @bitCast(libc.getpid()))}); + try uriOf(&b, arena, root); + try b.appendSlice(arena, "\",\"workspaceFolders\":[{\"name\":\"root\",\"uri\":\""); + try uriOf(&b, arena, root); + try b.appendSlice(arena, "\""); + try b.appendSlice(arena, + \\}],"capabilities":{"general":{"positionEncodings":["utf-8","utf-16"]}, + \\"window":{"workDoneProgress":true}, + \\"workspace":{"configuration":true,"workspaceFolders":true,"symbol":{}, + \\"diagnostics":{"refreshSupport":false}}, + \\"textDocument":{"synchronization":{"dynamicRegistration":false,"willSave":false,"didSave":false}, + \\"publishDiagnostics":{"relatedInformation":false}, + \\"diagnostic":{"dynamicRegistration":false,"relatedDocumentSupport":false}, + \\"hover":{"contentFormat":["plaintext","markdown"]}, + \\"definition":{"linkSupport":true},"declaration":{"linkSupport":true}, + \\"typeDefinition":{"linkSupport":true},"implementation":{"linkSupport":true}, + \\"references":{},"documentHighlight":{}, + \\"documentSymbol":{"hierarchicalDocumentSymbolSupport":true}, + \\"formatting":{},"rename":{"prepareSupport":false}, + \\"completion":{"completionItem":{"snippetSupport":false,"documentationFormat":["plaintext"]}}, + \\"callHierarchy":{},"typeHierarchy":{}, + \\"codeAction":{"codeActionLiteralSupport":{"codeActionKind":{"valueSet":[]}}}}, + \\"experimental":{"serverStatusNotification":true}} + ); + // strip the literal's newlines: legal JSON either way, but the frame + // length must match what is sent + var body: std.ArrayList(u8) = .empty; + for (b.items) |ch| if (ch != '\n') try body.append(arena, ch); + + const deadline = nowMs() + init_ms; + const reply = (try call(c, io, arena, "initialize", body.items, deadline)) orelse return error.Protocol; + + const caps = get(reply, "capabilities"); + c.caps.enc = if (std.mem.eql(u8, str(get(caps, "positionEncoding")) orelse "utf-16", "utf-8")) .utf8 else .utf16; + if (get(caps, "diagnosticProvider")) |dp| { + c.caps.pull = provider(dp); + c.caps.pull_workspace = if (get(dp, "workspaceDiagnostics")) |w| w == .bool and w.bool else false; + } + c.caps.call_hier = provider(get(caps, "callHierarchyProvider")); + c.caps.type_hier = provider(get(caps, "typeHierarchyProvider")); + c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false; + + try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); +} + +/// A server capability that may be `true`, an options object, or absent. +fn provider(v: ?std.json.Value) bool { + const o = v orelse return false; + return switch (o) { + .bool => |b| b, + .object => true, + else => false, + }; +} + +/// Send a request and wait on the mailbox. Returns the parsed `result`, or +/// null for an error response / null result — both are legal "no answer". +/// Runs with the conn mutex held; the mutex is released inside the wait. +fn call(c: *Conn, io: std.Io, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { + const g = c.gen; + const id = c.next_id; + c.next_id +%= 1; + + var b: std.ArrayList(u8) = .empty; + try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"id\":{d},\"method\":\"{s}\",\"params\":{{", .{ id, method }); + try b.appendSlice(arena, params); + try b.appendSlice(arena, "}}"); + + if (c.resp) |r| sa.free(r); + c.resp = null; + c.want_id = id; + defer c.want_id = 0; + + try send(c, io, b.items, if (c.state == .ready) nowMs() + wedge_ms else deadline); + + // The handshake (still `.starting`) has its deadline. A ready server is + // waited for until it answers or the shell cancels this query for a + // newer one, so the first query after a start is answered, not lost: + // past `deadline` the message row says it is still working, and only + // silent and idle for wedge_ms is it not answering. + var said = false; + var busy_at = nowMs(); + while (c.resp == null and c.gen == g and c.alive()) { + const ready = c.state == .ready; + const waiting = timedWait(c, io, if (ready) nowMs() + 500 else deadline) catch |e| { + cancelRequest(c, io, arena, id); + return e; + }; + if (!ready) { + if (waiting) continue; + break; + } + if (c.progress > 0) busy_at = nowMs(); + if (!said and nowMs() >= deadline) { + said = true; + post(c.si, .always, "{s} is still working on it\u{2026}", .{specs[c.si].name}); + } + if (nowMs() - busy_at >= wedge_ms) break; + } + if (said and c.resp != null) post(c.si, .always, "{s} answered", .{specs[c.si].name}); + if (c.gen != g or !c.alive()) return error.Dead; + const raw = c.resp orelse { + cancelRequest(c, io, arena, id); + return error.Timeout; + }; + c.resp = null; + defer sa.free(raw); + const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return error.Protocol; + const result = get(v, "result") orelse return null; + if (result == .null) return null; + return result; +} +/// Give the server leave to abandon the work we stopped waiting for. +fn cancelRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, id: u32) void { + var cb: std.ArrayList(u8) = .empty; + cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return; + send(c, io, cb.items, nowMs() + reply_ms) catch {}; +} + +/// One bounded cond wait, and a cancelation point: a worker the shell +/// cancels for a newer query stops here. False when the deadline has passed. +fn timedWait(c: *Conn, io: std.Io, deadline: i64) error{Canceled}!bool { + const left = deadline - nowMs(); + if (left <= 0) return false; + const wait_ms = @min(left, 500); // tick so gen/state changes are noticed + c.cond.waitTimeout(io, &c.mu, .{ .duration = .{ .raw = .fromMilliseconds(wait_ms), .clock = .awake } }) catch |e| switch (e) { + error.Timeout => {}, + error.Canceled => return error.Canceled, + }; + return true; +} + +/// Forget a server, but only the generation the caller actually used — a +/// respawn that happened during the caller's wait must not be killed for its +/// predecessor's crimes. Mutex held. The reader closes the fd; this only +/// shuts the transport down and reaps the child. +fn shutdownIf(c: *Conn, io: std.Io, g: u32) void { + if (c.gen != g or c.sock < 0) return; + _ = libc.shutdown(c.sock, 2); // SHUT_RDWR: the reader sees EOF and closes + reap(c.pid); + c.sock = -1; + c.pid = -1; + if (c.state != .disabled) c.state = .dead; + forgetDocs(c); + if (c.resp) |r| sa.free(r); + c.resp = null; + c.cond.broadcast(io); +} + +/// TERM, a bounded grace, then KILL, to the server's whole process group +/// (it is its group's leader, setsid at spawn): what it started -- zls's +/// `zig build --build-runner` -- goes with it, never left an orphan. Never +/// blocks unboundedly: a reaped or foreign pid answers -1 immediately. +fn reap(pid: libc.pid_t) void { + if (pid <= 0) return; + _ = libc.kill(-pid, .TERM); + var tries: u8 = 0; + while (tries < 20) : (tries += 1) { + const w = libc.waitpid(pid, null, libc.W.NOHANG); + if (w == pid or w < 0) { + // Its children may still be finishing their TERM. + _ = libc.kill(-pid, .KILL); + return; + } + _ = usleep(10_000); + } + _ = libc.kill(-pid, .KILL); + _ = libc.waitpid(pid, null, 0); +} + +/// At this process's exit, every server's group is killed: a server busy +/// in a build (zls at a cold start) would not notice its socket close, and +/// lived on with its children after the editor. Registered once, at the +/// first spawn; signals only, no locks (other threads may hold them). +fn killAllAtExit() callconv(.c) void { + for (&conns) |*c| if (c.pid > 0) { + _ = libc.kill(-c.pid, .KILL); + }; +} +var exit_hook = std.atomic.Value(bool).init(false); + +/// Free every per-document accumulation. Mutex held. +fn forgetDocs(c: *Conn) void { + for (c.extra_roots.items) |r| sa.free(r); + c.extra_roots.clearRetainingCapacity(); + for (c.docs.items) |d| sa.free(d.uri); + c.docs.clearRetainingCapacity(); + for (c.diags.items) |d| { + sa.free(d.uri); + sa.free(d.body); + } + c.diags.clearRetainingCapacity(); + c.diag_bytes = 0; +} + +// ------------------------------------------------------------ reader thread + +/// Owns the read side of one socket for one generation, and is the only +/// closer of that fd. Routes responses to the mailbox, answers server +/// requests, feeds the diagnostics store, narrates progress. +fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void { + const c = &conns[si]; + var buf = sa.alloc(u8, 256 * 1024) catch { + readerExit(c, io, si, g, sock); + return; + }; + defer sa.free(buf); + var len: usize = 0; + var parse_arena: std.heap.ArenaAllocator = .init(sa); + defer parse_arena.deinit(); + + outer: while (true) { + // drain every complete frame already buffered + drain: while (true) switch (frameNext(buf[0..len])) { + .frame => |m| { + dispatch(c, io, si, g, sock, buf[m.body_start..m.body_end], &parse_arena); + std.mem.copyForwards(u8, buf[0 .. len - m.consumed], buf[m.consumed..len]); + len -= m.consumed; + }, + .incomplete => break :drain, + // a complete header that is not a frame we can speak: nothing + // after it can ever re-synchronize, so the connection is over — + // this must NOT read as "incomplete", which would buffer the + // poison forever while every request quietly times out + .poison => break :outer, + }; + // grow when a frame is bigger than the space that is left + if (len == buf.len) { + if (buf.len >= 64 << 20) break :outer; + const bigger = sa.realloc(buf, buf.len * 2) catch break :outer; + buf = bigger; + } + var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.IN, .revents = 0 }}; + const pr = libc.poll(&pfd, 1, 1000); + if (pr < 0) { + if (libc.errno(pr) == .INTR) continue; + break :outer; + } + if (pr == 0) { + // tick: a respawn while the server was silent leaves this thread + // reading a corpse; notice and go + c.mu.lockUncancelable(io); + const stale = c.gen != g; + c.mu.unlock(io); + if (stale) break :outer; + continue; + } + const got = libc.recv(sock, buf.ptr + len, buf.len - len, 0); + if (got < 0) { + const e = libc.errno(got); + if (e == .INTR or e == .AGAIN) continue; + break :outer; + } + if (got == 0) break :outer; // the server exited or shutdownIf spoke + len += @intCast(got); + } + readerExit(c, io, si, g, sock); +} + +fn readerExit(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int) void { + c.mu.lockUncancelable(io); + if (c.gen == g and c.alive()) { + // the server died on its own — shutdownIf never saw it, so the corpse + // is ours to reap and the conn's transport fields are ours to clear + c.state = .dead; + reap(c.pid); + c.pid = -1; + c.sock = -1; + // A server that keeps crashing right after its handshake would + // otherwise respawn on every keystroke — the handshake SUCCEEDING + // resets the backoff, so the crash has to count as the failure it + // is. A long-lived server that dies gets one free respawn. + if (nowMs() - c.ready_at_ms < 30_000) { + c.handshake_fails +|= 1; + const wait = backoffMs(c.handshake_fails); + c.retry_after_ms = nowMs() + wait; + post(si, .always, "{s} crashed — retrying in {d}s", .{ specs[si].name, @divTrunc(wait, 1000) }); + } else { + post(si, .always, "{s} exited — restarts on the next query", .{specs[si].name}); + } + c.cond.broadcast(io); + } + c.mu.unlock(io); + // A query writes with the mutex let go (send): the fd stays its until + // that write is done, and shutdown(2) has already made it fail fast. + c.write_mu.lockUncancelable(io); + _ = libc.close(sock); + c.write_mu.unlock(io); +} + +/// 10s doubling to 2min: the fork-per-keystroke guard's schedule. +fn backoffMs(fails: u8) i64 { + const shift: u5 = @min(fails -| 1, 4); + return @as(i64, 10_000) << shift; +} + +const Framed = struct { body_start: usize, body_end: usize, consumed: usize }; + +const FrameStep = union(enum) { + /// keep reading; the head of the buffer may still become a frame + incomplete, + /// a complete, valid frame + frame: Framed, + /// a complete header that cannot be a frame (no/invalid/oversized + /// Content-Length): the stream can never re-synchronize + poison, +}; + +/// One Content-Length-framed message at the head of `data`. Pure — this is +/// the whole wire format, and it is testable without a socket. +fn frameNext(data: []const u8) FrameStep { + const sep = std.mem.indexOf(u8, data, "\r\n\r\n") orelse return .incomplete; + var clen: ?usize = null; + var it = std.mem.splitSequence(u8, data[0..sep], "\r\n"); + while (it.next()) |line| { + const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue; + if (!std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " "), "content-length")) continue; + clen = std.fmt.parseInt(usize, std.mem.trim(u8, line[colon + 1 ..], " "), 10) catch null; + } + const n = clen orelse return .poison; + const start = sep + 4; + if (n > 64 << 20) return .poison; + if (data.len < start + n) return .incomplete; + return .{ .frame = .{ .body_start = start, .body_end = start + n, .consumed = start + n } }; +} + +/// One message from the server. Parses into a throwaway arena; touches conn +/// state only under the mutex; replies never hold it (bounded writes must not +/// stall the mailbox). +fn dispatch(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int, raw: []const u8, arena_state: *std.heap.ArenaAllocator) void { + // The reader's one parse arena, reset per message: no mapping per + // `$/progress` report, and no more than parse_kept kept between them. + defer _ = arena_state.reset(.{ .retain_with_limit = parse_kept }); + const arena = arena_state.allocator(); + const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return; + if (v != .object) return; + + if (str(get(v, "method"))) |method| { + if (get(v, "id")) |id| return serverRequest(c, io, arena, sock, method, id, get(v, "params")); + return notification(c, io, si, g, raw, method, get(v, "params")); + } + + // a response: deliver to the one waiting query, if it is still waiting + const id = num(get(v, "id")) orelse return; + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); + if (c.gen == g and c.want_id != 0 and id == c.want_id and c.resp == null) { + c.resp = sa.dupe(u8, raw) catch null; + c.cond.broadcast(io); + } +} + +/// The server asked US something. Everything optional was declined in the +/// handshake, so a null-ish answer is always legal — but it must ARRIVE, or +/// the server blocks forever on its own question. +fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { + var b: std.ArrayList(u8) = .empty; + b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"id\":") catch return; + switch (id) { + .integer => |n| b.print(arena, "{d}", .{n}) catch return, + .string => |t| jstr(&b, arena, t) catch return, + else => b.appendSlice(arena, "null") catch return, + } + if (std.mem.eql(u8, method, "workspace/configuration")) { + // one null per asked item — a bare null here is a protocol violation + // some servers punish with a parse loop + const n = items(get(params, "items")).len; + b.appendSlice(arena, ",\"result\":[") catch return; + for (0..n) |i| b.appendSlice(arena, if (i == 0) "null" else ",null") catch return; + b.appendSlice(arena, "]}") catch return; + } else if (std.mem.eql(u8, method, "workspace/applyEdit")) { + b.appendSlice(arena, ",\"result\":{\"applied\":false}}") catch return; + } else { + b.appendSlice(arena, ",\"result\":null}") catch return; + } + answerServer(c, io, sock, b.items); +} + +fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { + const Method = enum { @"textDocument/publishDiagnostics", @"$/progress", @"window/showMessage", @"experimental/serverStatus" }; + switch (std.meta.stringToEnum(Method, method) orelse return) { + .@"textDocument/publishDiagnostics" => { + const uri = str(get(params, "uri")) orelse return; + // keep the raw MESSAGE (params included); re-parsing it per query + // beats owning a parsed tree past this arena's life + const body = sa.dupe(u8, raw) catch return; + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); + if (c.gen != g) { + sa.free(body); + return; + } + for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { + d.stale = false; + break; + }; + var slot: ?*DiagSet = null; + for (c.diags.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { + slot = d; + break; + }; + // Bounded in files and bytes: a new set that does not fit pushes + // out the oldest files' (the server sends a file's again when it + // changes); one bigger than the whole store is not kept. + if (body.len > max_diag_bytes) { + sa.free(body); + return; + } + if (slot) |d| { + c.diag_bytes -= d.body.len; + sa.free(d.body); + d.body = body; + c.diag_bytes += body.len; + } else { + while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { + const old = c.diags.orderedRemove(0); + c.diag_bytes -= old.body.len; + sa.free(old.uri); + sa.free(old.body); + } + const owned = sa.dupe(u8, uri) catch { + sa.free(body); + return; + }; + c.diags.append(sa, .{ .uri = owned, .body = body }) catch { + sa.free(owned); + sa.free(body); + return; + }; + c.diag_bytes += body.len; + } + c.cond.broadcast(io); // waitFresh watches this + }, + .@"$/progress" => { + const value = get(params, "value") orelse return; + const pkind = str(get(value, "kind")) orelse return; + const msg = str(get(value, "message")) orelse ""; + c.mu.lockUncancelable(io); + if (c.gen != g) { + c.mu.unlock(io); + return; + } + if (std.mem.eql(u8, pkind, "begin")) { + c.progress += 1; + c.cond.broadcast(io); + const title = str(get(value, "title")) orelse ""; + c.title_len = @intCast(@min(title.len, c.title.len)); + @memcpy(c.title[0..c.title_len], title[0..c.title_len]); + var tbuf: [48]u8 = undefined; + const t = tbuf[0..c.title_len]; + @memcpy(t, c.title[0..c.title_len]); + c.mu.unlock(io); + post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); + return; + } + if (std.mem.eql(u8, pkind, "report")) { + var tbuf: [48]u8 = undefined; + const t = tbuf[0..c.title_len]; + @memcpy(t, c.title[0..c.title_len]); + const pct = num(get(value, "percentage")); + c.mu.unlock(io); + if (pct) |p| + post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) + else + post(si, .chatty, "{s}: {s} {s}", .{ specs[si].name, t, msg }); + return; + } + // end + c.progress -= 1; + const idle = c.progress <= 0; + if (idle) c.progress = 0; + c.cond.broadcast(io); + c.mu.unlock(io); + // the setpoint every burst of progress ends on; `.always` + the + // dedupe above means it lands exactly once however the reports raced + if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); + }, + .@"window/showMessage" => { + const t = num(get(params, "type")) orelse 3; + if (t > 2) return; // info/log are the server's diary, not the user's + post(si, .always, "{s}: {s}", .{ specs[si].name, str(get(params, "message")) orelse "" }); + }, + // rust-analyzer's precise quiescence signal, opted into via + // experimental.serverStatusNotification + .@"experimental/serverStatus" => { + const health = str(get(params, "health")) orelse "ok"; + const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; + c.mu.lockUncancelable(io); + if (c.gen == g) { + c.loading = !quiescent; + c.cond.broadcast(io); + } + c.mu.unlock(io); + if (!std.mem.eql(u8, health, "ok")) + post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) + else if (quiescent) + post(si, .always, "{s}: ready", .{specs[si].name}); + }, + } +} + +// ------------------------------------------------------------- introspection + +// ------------------------------------------------------------------ plumbing + +/// `"textDocument":{"uri":U}` — the params every request about a file +/// starts with. +fn docParams(arena: std.mem.Allocator, uri: []const u8) Err!std.ArrayList(u8) { + var b: std.ArrayList(u8) = .empty; + try b.appendSlice(arena, "\"textDocument\":{\"uri\":"); + try jstr(&b, arena, uri); + try b.appendSlice(arena, "}"); + return b; +} + +/// `"textDocument":{"uri":U},"position":{...}` — the params shared by every +/// position request. +fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList(u8) { + var b = try docParams(arena, uri); + try b.print(arena, ",\"position\":{{\"line\":{d},\"character\":{d}}}", .{ pos.line, pos.ch }); + return b; +} + +/// A message to the server from a query, the conn's mutex let go while it is +/// written: the reader goes on taking the server's output meanwhile, which a +/// server may be waiting to write before it reads more of ours. +fn send(c: *Conn, io: std.Io, body: []const u8, deadline: i64) Err!void { + const sock = c.sock; + c.mu.unlock(io); + defer c.mu.lockUncancelable(io); + return frame(c, io, sock, body, deadline); +} + +fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err!void { + if (sock < 0) return error.Dead; + c.write_mu.lockUncancelable(io); + defer releaseWrite(c, io, sock); + var hdr: [64]u8 = undefined; + const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return error.Protocol; + var started = false; + try sockWrite(io, sock, h, deadline, &started); + try sockWrite(io, sock, body, deadline, &started); +} + +/// The reader's answer to a server request: written now if the socket is +/// free, else queued for the query writing (bounded; one that does not fit is +/// dropped, and the server's request goes unanswered). +fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void { + var hdr: [64]u8 = undefined; + const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch unreachable; // a usize's 20 digits and a short header fit 64 + c.replies_mu.lockUncancelable(io); + const half = &c.replies[c.filling]; + const len = &c.replies_len[c.filling]; + if (len.* + h.len + body.len <= half.len) { + @memcpy(half[len.*..][0..h.len], h); + @memcpy(half[len.* + h.len ..][0..body.len], body); + len.* += h.len + body.len; + } + c.replies_mu.unlock(io); + if (c.write_mu.tryLock()) releaseWrite(c, io, sock); +} + +/// Lets the socket go, first sending what the reader queued meanwhile, and +/// again for what it queues while that goes out. +fn releaseWrite(c: *Conn, io: std.Io, sock: c_int) void { + while (true) { + c.replies_mu.lockUncancelable(io); + const sent = c.filling; + const n = c.replies_len[sent]; + if (n > 0) c.filling ^= 1; + c.replies_mu.unlock(io); + if (n > 0) { + var started = false; + sockWrite(null, sock, c.replies[sent][0..n], nowMs() + reply_ms, &started) catch {}; + c.replies_len[sent] = 0; + } + c.write_mu.unlock(io); + c.replies_mu.lockUncancelable(io); + const more = c.replies_len[c.filling] > 0; + c.replies_mu.unlock(io); + if (!more or !c.write_mu.tryLock()) return; + } +} + +/// Writes `bytes`, `started` once any byte of their message is out. Before +/// then, the deadline and a cancel stop it; after, the message is finished +/// however long the server takes to read it (bounded by wedge_ms), since +/// half of one ends the server's reading of every message after it. +fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started: *bool) Err!void { + var off: usize = 0; + while (off < bytes.len) { + if (!started.*) { + if (deadline - nowMs() <= 0) return error.Timeout; + if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled; + } else if (nowMs() - deadline > wedge_ms) return error.Dead; + var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.OUT, .revents = 0 }}; + const pr = libc.poll(&pfd, 1, 500); + if (pr < 0) { + if (libc.errno(pr) == .INTR) continue; + return error.Dead; + } + if (pr == 0) continue; + const n = libc.send(sock, bytes.ptr + off, bytes.len - off, msg_nosignal); + if (n < 0) { + const e = libc.errno(n); + if (e == .INTR or e == .AGAIN) continue; + return error.Dead; + } + if (n == 0) return error.Dead; + started.* = true; + off += @intCast(n); + } +} + +fn nowMs() i64 { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.MONOTONIC, &ts); + return @as(i64, @intCast(ts.sec)) * 1000 + @divTrunc(@as(i64, @intCast(ts.nsec)), 1_000_000); +} + +/// A path as a `file://` URI, raw (no JSON quotes). Everything outside the +/// unreserved set is percent-encoded; `/` stays a separator. +fn uriOf(b: *std.ArrayList(u8), arena: std.mem.Allocator, path: []const u8) Err!void { + try b.appendSlice(arena, "file://"); + for (path) |ch| { + if (std.ascii.isAlphanumeric(ch) or ch == '/' or ch == '-' or ch == '_' or ch == '.' or ch == '~') { + try b.append(arena, ch); + } else { + try b.print(arena, "%{X:0>2}", .{ch}); + } + } +} + +/// A JSON string. Invalid UTF-8 becomes `?` one byte at a time rather than +/// U+FFFD: a buffer being typed into may be invalid mid-keystroke, and a +/// replacement that changed byte lengths would move every offset after it. +fn jstr(b: *std.ArrayList(u8), arena: std.mem.Allocator, s: []const u8) Err!void { + try b.append(arena, '"'); + var i: usize = 0; + while (i < s.len) { + const ch = s[i]; + if (ch < 0x80) { + switch (ch) { + '"' => try b.appendSlice(arena, "\\\""), + '\\' => try b.appendSlice(arena, "\\\\"), + '\n' => try b.appendSlice(arena, "\\n"), + '\r' => try b.appendSlice(arena, "\\r"), + '\t' => try b.appendSlice(arena, "\\t"), + else => if (ch < 0x20) + try b.print(arena, "\\u{x:0>4}", .{ch}) + else + try b.append(arena, ch), + } + i += 1; + continue; + } + const l = std.unicode.utf8ByteSequenceLength(ch) catch { + try b.append(arena, '?'); + i += 1; + continue; + }; + if (i + l > s.len or !std.unicode.utf8ValidateSlice(s[i .. i + l])) { + try b.append(arena, '?'); + i += 1; + continue; + } + try b.appendSlice(arena, s[i .. i + l]); + i += l; + } + try b.append(arena, '"'); +} + +const Pos = struct { line: u32, ch: u32 }; + +// std.json.Value navigation: optional-in, optional-out, so a missing field +// and a wrongly-typed one read the same and neither can panic on a server +// that sends the unexpected. + +fn get(v: ?std.json.Value, key: []const u8) ?std.json.Value { + const o = v orelse return null; + if (o != .object) return null; + return o.object.get(key); +} + +fn str(v: ?std.json.Value) ?[]const u8 { + const o = v orelse return null; + return if (o == .string) o.string else null; +} + +fn num(v: ?std.json.Value) ?i64 { + const o = v orelse return null; + return if (o == .integer) o.integer else null; +} + +fn items(v: ?std.json.Value) []std.json.Value { + const o = v orelse return &.{}; + return if (o == .array) o.array.items else &.{}; +} + +const Range = Scip.Range; + +fn rangeOf(range: ?std.json.Value) ?Range { + const st = get(range, "start") orelse return null; + const en = get(range, "end") orelse return null; + return .{ + .sl = coord(get(st, "line")) orelse return null, + .sc = coord(get(st, "character")) orelse return null, + .el = coord(get(en, "line")) orelse return null, + .ec = coord(get(en, "character")) orelse return null, + }; +} + +/// One protocol coordinate, VALIDATED rather than clamped: a negative line is +/// not "line zero", it is a malformed response, and a value past u32 would +/// panic the @intCast that follows. Server bytes are not trusted bytes. +fn coord(v: ?std.json.Value) ?u32 { + const n = num(v) orelse return null; + if (n < 0 or n > std.math.maxInt(u32)) return null; + return @intCast(n); +} + +// ----------------------------------------------------------------- tests + +test "caller trees reverse incoming paths and merge shared callers and sites" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"left\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}]},{\"from\":{\"name\":\"right\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":2,\"character\":0},\"end\":{\"line\":2,\"character\":4}}]},{\"from\":{\"name\":\"main\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}]}]", .{}); + const entries = try serverHops(arena, fixture); + var tree: CallTree = .{}; + try tree.addPath(arena, &.{ entries[0], entries[2], entries[4] }, false); + try tree.addPath(arena, &.{ entries[1], entries[3], entries[4] }, false); + try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len); + try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len); + const root = tree.nodes.items[tree.roots.items[0]]; + try std.testing.expectEqualStrings("main", root.call.name); + try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len); + const page = tree.nodes.items[root.children.items[0]]; + try std.testing.expectEqual(@as(usize, 2), page.children.items.len); + try std.testing.expectEqual(@as(usize, 2), page.ranges.items.len); + try std.testing.expect(!root.ranges.items[0].focus); + for (page.ranges.items) |site| try std.testing.expect(!site.focus); + for (page.children.items) |id| try std.testing.expect(tree.nodes.items[id].ranges.items[0].focus); + var out: std.Io.Writer.Allocating = .init(arena); + var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer }; + try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); + const text = out.written(); + try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, lsp.callstack_match)); + const main_at = std.mem.indexOf(u8, text, " main\n").?; + const page_at = std.mem.indexOf(u8, text, " page\n").?; + const left_at = std.mem.indexOf(u8, text, " left\n").?; + const right_at = std.mem.indexOf(u8, text, " right\n").?; + try std.testing.expect(main_at < page_at and page_at < left_at and left_at < right_at); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "main_call();")); + try std.testing.expect(std.mem.indexOf(u8, text, "page_left();").? < std.mem.indexOf(u8, text, "page_right();").?); + try std.testing.expect(std.mem.indexOf(u8, text, "├──┬ test.c:4:") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "╰──┬ test.c:1:") != null); + var recursive: CallTree = .{}; + try recursive.addPath(arena, &.{ entries[0], entries[0] }, true); + try std.testing.expect(!recursive.nodes.items[recursive.roots.items[0]].cycle); + try std.testing.expect(recursive.nodes.items[1].cycle); +} + +test "test callers sort after the rest, each group by place" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"test b\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"z\",\"uri\":\"file:///b.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"x\",\"uri\":\"file:///a_test.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"y\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":5,\"character\":0},\"end\":{\"line\":5,\"character\":1}}}}]", .{}); + var tree: CallTree = .{}; + for (try serverHops(arena, fixture)) |hop| try tree.nodes.append(arena, .{ .call = hop.call }); + var order = [_]usize{ 0, 1, 2, 3 }; + std.mem.sort(usize, &order, @as(*const CallTree, &tree), callerLess); + try std.testing.expectEqualSlices(usize, &.{ 3, 1, 0, 2 }, &order); +} + +test "a mailbox wait is a cancelation point: a canceled worker stops waiting" { + const io = std.testing.io; + var c: Conn = .{}; + const Waiter = struct { + fn run(conn: *Conn, wio: std.Io) error{Canceled}!void { + conn.mu.lockUncancelable(wio); + defer conn.mu.unlock(wio); + while (true) _ = try timedWait(conn, wio, nowMs() + 60_000); + } + }; + var future = try io.concurrent(Waiter.run, .{ &c, io }); + try std.testing.expectError(error.Canceled, future.cancel(io)); +} + +test "callstack cross-crate paths remain resolvable without absolute path clutter" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const range = try std.json.parseFromSliceLeaky(std.json.Value, arena, + \\{"start":{"line":1,"character":3},"end":{"line":1,"character":6}} + , .{}); + var out: std.Io.Writer.Allocating = .init(arena); + var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true }; + try emitRange(&cx, .utf8, "file:///workspace/entry/src/entry.rs", range, "fn run()"); + try std.testing.expectEqualStrings("../../entry/src/entry.rs:2:4-6 fn run()\n", out.written()); +} + +test "LSP client rename and format propagate incomplete edit encoding" { + const gpa = std.testing.allocator; + const uri = "file:///file.c"; + const parsed = try std.json.parseFromSlice(std.json.Value, gpa, + \\{"changes":{"file:///file.c":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":3}},"newText":"A%\n"},{"range":{"start":{"line":0,"character":4},"end":{"line":0,"character":7}},"newText":"B"}]}} + , .{}); + defer parsed.deinit(); + const expected = "@put 0 3 A%25%0A\n@put 4 7 B\n"; + for ([_]bool{ true, false }) |rename| { + var buffer: [128]u8 = undefined; + for (0..expected.len + 1) |capacity| { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var out: std.Io.Writer = .fixed(buffer[0..capacity]); + var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = "abc xyz", .out = &out }; + const result = if (rename) + renameEdits(&cx, .utf8, uri, parsed.value, cx.cur_src, "abc", &.{}) + else + formatEdits(&cx, .utf8, get(get(parsed.value, "changes"), uri).?, cx.cur_src); + if (capacity < expected.len) { + try std.testing.expectError(error.WriteFailed, result); + } else { + try result; + try std.testing.expectEqualStrings(expected, out.buffered()); + } + } + } +} + +test "a rename answered for this file alone, while another open file says the old name, previews and names it" { + const gpa = std.testing.allocator; + const parsed = try std.json.parseFromSlice(std.json.Value, gpa, + \\{"changes":{"file:///w/util.zig":[{"range":{"start":{"line":0,"character":7},"end":{"line":0,"character":10}},"newText":"sum"}]}} + , .{}); + defer parsed.deinit(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var buffer: [512]u8 = undefined; + var out: std.Io.Writer = .fixed(&buffer); + var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/w", .cur_path = "/w/util.zig", .cur_src = "pub fn add() void {}", .out = &out }; + try renameEdits(&cx, .utf8, "file:///w/util.zig", parsed.value, cx.cur_src, "add", &.{"/w/main.zig"}); + try std.testing.expectEqualStrings("util.zig:1:8-10 sum\nmain.zig: also says add, which the server did not rename\n", out.buffered()); + try std.testing.expectEqualStrings("add", identAt("x = add(1);", 6)); + try std.testing.expect(holdsWord("util.add(1)", "add") and !holdsWord("addNumbers", "add")); +} + +test "frameNext distinguishes incomplete, valid and poison frames" { + try std.testing.expectEqual(FrameStep.incomplete, frameNext("Content-Length: 5\r\n")); + try std.testing.expectEqual(FrameStep.incomplete, frameNext("Content-Length: 5\r\n\r\nhel")); + const one = frameNext("Content-Length: 5\r\n\r\nhello").frame; + try std.testing.expectEqualStrings("hello", "Content-Length: 5\r\n\r\nhello"[one.body_start..one.body_end]); + const two = "content-length: 2\r\nX-Other: y\r\n\r\nab" ++ "Content-Length: 1\r\n\r\nz"; + const first = frameNext(two).frame; + try std.testing.expectEqualStrings("ab", two[first.body_start..first.body_end]); + const second = frameNext(two[first.consumed..]).frame; + try std.testing.expectEqualStrings("z", two[first.consumed..][second.body_start..second.body_end]); + // complete-but-unusable headers can never re-synchronize: poison, not + // "keep buffering" — the wedge a review found and this line pins + try std.testing.expectEqual(FrameStep.poison, frameNext("Content-Length: nope\r\n\r\n")); + try std.testing.expectEqual(FrameStep.poison, frameNext("X-Only: y\r\n\r\n")); + try std.testing.expectEqual(FrameStep.poison, frameNext("Content-Length: 67108865\r\n\r\n")); +} + +test "server coordinates are validated, not clamped" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const bad = [_][]const u8{ + \\{"start":{"line":-1,"character":0},"end":{"line":0,"character":1}} + , + \\{"start":{"line":0,"character":0},"end":{"line":0,"character":4294967296}} + , + \\{"start":{"line":0,"character":0},"end":{"line":0}} + }; + for (bad) |json| { + const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}); + try std.testing.expect(rangeOf(v) == null); + } + // strict offsets: past-EOL and past-EOF are refusals, EOL itself is real + const src = "ab\ncd"; + try std.testing.expectEqual(@as(?usize, 2), strictOffset(src, 0, 2, .utf8)); + try std.testing.expect(strictOffset(src, 0, 3, .utf8) == null); + try std.testing.expect(strictOffset(src, 2, 0, .utf8) == null); + try std.testing.expectEqual(@as(?usize, 5), strictOffset(src, 1, 2, .utf8)); +} + +test "uri round-trips spaces and utf-8" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var b: std.ArrayList(u8) = .empty; + try uriOf(&b, arena, "/a dir/naïve.rs"); + try std.testing.expectEqualStrings("file:///a%20dir/na%C3%AFve.rs", b.items); + try std.testing.expectEqualStrings("/a dir/naïve.rs", pathOf(arena, b.items).?); + try std.testing.expect(pathOf(arena, "file://host/x") == null); + // a %0A would split one location into two rows: rejected wholesale + try std.testing.expect(pathOf(arena, "file:///tmp/a%0A/tmp/b:1:1") == null); + try std.testing.expect(pathOf(arena, "file:///tmp/a%00b") == null); + try std.testing.expect(pathOf(arena, "https://x/y") == null); +} + +test "posOf and strictOffset invert each other under both encodings" { + const src = "aé𝕏b\ncd\n"; // é: 2 bytes/1 unit, 𝕏: 4 bytes/2 units + inline for (.{ Enc.utf8, Enc.utf16 }) |enc| { + const off: u32 = 7; // the 'b' + const p = posOf(src, off, enc); + try std.testing.expectEqual(@as(u32, 0), p.line); + try std.testing.expectEqual(@as(?usize, off), strictOffset(src, p.line, p.ch, enc)); + } + const p2 = posOf("aé𝕏b\ncd\n", 10, .utf16); // the 'd' + try std.testing.expectEqual(@as(u32, 1), p2.line); + try std.testing.expectEqual(@as(u32, 1), p2.ch); +} + +test "rootOf takes the top-most marker and falls back to git then dir" { + // libc mkdtemp under /tmp rather than std.testing.tmpDir: rootOf probes + // with access(2) on ABSOLUTE paths, and /tmp has no ancestor markers to + // muddy the fallback assertions the way the repo's own .zig-cache does. + var tpl: [64:0]u8 = undefined; + _ = std.fmt.bufPrintSentinel(&tpl, "/tmp/pardes-rootof-XXXXXX", .{}, 0) catch unreachable; + const base_z = mkdtemp(&tpl) orelse return error.TestUnexpectedResult; + const base = std.mem.span(base_z); + defer { + var cmd: [128:0]u8 = undefined; + if (std.fmt.bufPrintSentinel(&cmd, "rm -rf {s}", .{base}, 0)) |z| _ = system(z.ptr) else |_| {} + } + var pb: [128:0]u8 = undefined; + for ([_][]const u8{ "/ws", "/ws/member", "/ws/member/src" }) |d| { + const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, d }, 0); + try std.testing.expect(libc.mkdir(z.ptr, 0o700) == 0); + } + for ([_][]const u8{ "/ws/Cargo.toml", "/ws/member/Cargo.toml" }) |f| { + const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, f }, 0); + const fd = libc.open(z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true }, @as(libc.mode_t, 0o600)); + try std.testing.expect(fd >= 0); + _ = libc.close(fd); + } + const deep = try std.fmt.bufPrintSentinel(&pb, "{s}/ws/member/src", .{base}, 0); + const markers = [_][]const u8{"Cargo.toml"}; + const root = rootOf(deep, &markers); + try std.testing.expect(std.mem.endsWith(u8, root, "/ws")); + // no language marker and no .git anywhere under /tmp: the asking dir wins + const nothing = rootOf(deep, &.{"no-such-marker"}); + try std.testing.expect(std.mem.startsWith(u8, deep, nothing)); +} + +test "language server discovery honours PATH and overrides before the user bin directory" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + try tmp.dir.createDirPath(io, ".local/bin"); + try tmp.dir.createDirPath(io, "path-bin"); + for ([_][]const u8{ ".local/bin/zls", "path-bin/zls" }) |path| { + const file = try tmp.dir.createFile(io, path, .{ .permissions = .fromMode(0o700) }); + file.close(io); + } + var home_buf: [4096]u8 = undefined; + const home = home_buf[0..try tmp.dir.realPath(io, &home_buf)]; + var path_buf: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/path-bin", .{home}); + var out: [4096:0]u8 = undefined; + try std.testing.expect(std.mem.endsWith(u8, findBin("zls", path, home, &out).?, "/path-bin/zls")); + try std.testing.expect(std.mem.endsWith(u8, findBin("zls", "/no-such-bin", home, &out).?, "/.local/bin/zls")); + try std.testing.expect(findBin("", path, home, &out) == null); + try std.testing.expect(findBin("/no-such-bin/zls", path, home, &out) == null); + try std.testing.expect(findBin("zls", "", "", &out) == null); + try std.testing.expect(findBin(path, "", home, &out) == null); // a directory is not executable code +} + +test "specFor routes extensions and honours the disable env" { + try std.testing.expect(specFor("/x/main.rs") != null); + try std.testing.expect(specFor("/x/README.md") == null); + try std.testing.expectEqualStrings("rust-analyzer", specs[specFor("/x/main.rs").?].name); + if (libc.getenv("PARDES_LSP_ZIG") == null) try std.testing.expectEqualStrings("zls", specs[specFor("/x/main.zig").?].name); +} + +test "the transport this host actually gives us is a pair, and both ends are close-on-exec" { + // The spawn's FIRST fallible step, and for one release on macOS its last: + // `SOCK.CLOEXEC` is spelled for darwin in zig's libc bindings and rejected + // by darwin's socketpair(2), so this returned EPROTONOSUPPORT and no + // language server was ever forked on that platform. Nothing above the + // transport can notice — `ensure` reports the same `NoServer` a missing + // binary does — so the check belongs here, on the real function, in a test + // that runs on the host rather than on the linux target the snapshot + // suite cross-compiles to. + var sv: [2]libc.fd_t = undefined; + try std.testing.expect(transportPair(&sv)); + defer { + _ = libc.close(sv[0]); + _ = libc.close(sv[1]); + } + + // close-on-exec on both ends, however the platform got there: the flag on + // linux, fcntl on darwin. Without it every pty shell forked afterwards + // inherits the server's socket, which is the bug host_io.zig fixed for the + // pty master. + const FD_CLOEXEC: c_int = 1; + for (sv) |fd| try std.testing.expect(libc.fcntl(fd, libc.F.GETFD, @as(c_int, 0)) & FD_CLOEXEC != 0); + + // and it is a connected PAIR, not two unrelated descriptors + const msg = "ping"; + try std.testing.expectEqual(@as(isize, msg.len), libc.write(sv[0], msg, msg.len)); + var got: [8]u8 = undefined; + try std.testing.expectEqual(@as(isize, msg.len), libc.read(sv[1], &got, got.len)); + try std.testing.expectEqualStrings(msg, got[0..msg.len]); +} + +test "LSP source snippets preserve indentation with UTF16 byte ranges and prose stays trimmed" { + const gpa = std.testing.allocator; + const source = "\t const 𝕏 = target; \t\r\n"; + for ([_]bool{ false, true }) |multiline| { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const json = try std.fmt.allocPrint(arena.allocator(), "{{\"start\":{{\"line\":0,\"character\":14}},\"end\":{{\"line\":{d},\"character\":20}}}}", .{@as(u8, if (multiline) 1 else 0)}); + const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json, .{}); + for ([_]bool{ false, true }) |prose| { + var buffer: [256]u8 = undefined; + var out: std.Io.Writer = .fixed(&buffer); + var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = source, .out = &out }; + try emitRange(&cx, .utf16, "file:///file.c", parsed.value, if (prose) " explanatory label \t" else ""); + const expected = try std.fmt.allocPrint(arena.allocator(), "file.c:1:17{s} {s}\n", .{ + if (multiline) "" else "-22", + if (prose) "explanatory label" else "\t const 𝕏 = target; \t", + }); + try std.testing.expectEqualStrings(expected, out.buffered()); + try std.testing.expectEqual(@as(usize, 1), cx.rows); + } + } +} + +test "a language with no server to start says so, not that it did not answer" { + const si = specFor("/x/a.py") orelse return; + const was = conns[si].state; + conns[si].state = .disabled; + defer conns[si].state = was; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var buf: [256]u8 = undefined; + var out: std.Io.Writer = .fixed(&buf); + try query(std.testing.io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); + try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); +} + +test "Lspinfo before any query says a server is not started yet, not off" { + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try status(std.testing.io, "/x/notes.txt", &out.writer); + try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null); +} + +test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" { + if (libc.getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest; + const io = std.testing.io; + const si = specFor("/x/a.zig").?; + const c = &conns[si]; + c.mu.lockUncancelable(io); + const was = .{ c.state, c.retry_after_ms }; + c.state = .dead; + c.retry_after_ms = nowMs() + 4500; + c.mu.unlock(io); + defer { + c.mu.lockUncancelable(io); + c.state = was[0]; + c.retry_after_ms = was[1]; + c.mu.unlock(io); + } + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + try query(std.testing.io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); + try std.testing.expect(std.mem.indexOf(u8, out.written(), "zls failed recently; retry in 5s") != null); +} + +test "reaping a server takes what it started with it: its process group goes, its children too" { + var fds: [2]libc.fd_t = undefined; + if (libc.pipe(&fds) != 0) return error.SkipZigTest; + const pid = libc.fork(); + if (pid < 0) return error.SkipZigTest; + if (pid == 0) { + _ = libc.setsid(); + const child = libc.fork(); + if (child == 0) { + while (true) _ = usleep(100_000); + } + var word: [4]u8 = @bitCast(@as(i32, child)); + _ = libc.write(fds[1], &word, 4); + while (true) _ = usleep(100_000); + } + _ = libc.close(fds[1]); + var word: [4]u8 = undefined; + try std.testing.expectEqual(@as(isize, 4), libc.read(fds[0], &word, 4)); + _ = libc.close(fds[0]); + const grandchild: libc.pid_t = @bitCast(word); + reap(pid); + // Gone, or a zombie waiting for its new parent to reap it: not running. + var tries: u32 = 0; + const running = while (tries < 200) : (tries += 1) { + var path: [64]u8 = undefined; + const stat_path = try std.fmt.bufPrintSentinel(&path, "/proc/{d}/stat", .{grandchild}, 0); + const fd = libc.open(stat_path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) break false; + var buf: [256]u8 = undefined; + const n = libc.read(fd, &buf, buf.len); + _ = libc.close(fd); + if (n > 0) if (std.mem.lastIndexOfScalar(u8, buf[0..@intCast(n)], ')')) |close| { + if (buf[close + 2] == 'Z') break false; + }; + _ = usleep(10_000); + } else true; + if (running) _ = libc.kill(grandchild, .KILL); + try std.testing.expect(!running); +} diff --git a/dev/macos/Info.plist b/dev/macos/Info.plist new file mode 100644 index 00000000..3cb2e488 --- /dev/null +++ b/dev/macos/Info.plist @@ -0,0 +1,76 @@ + + + + + CFBundleName + pardes + CFBundleIdentifier + cafe.0x4200.pardes + CFBundleExecutable + pardes + CFBundlePackageType + APPL + + CFBundleShortVersionString + 0.0.0 + CFBundleVersion + 3 + + CFBundleIconFile + pardes + NSHighResolutionCapable + + + LSMinimumSystemVersion + 13.0 + LSApplicationCategoryType + public.app-category.developer-tools + NSPrincipalClass + NSApplication + + NSSupportsAutomaticTermination + + NSSupportsSuddenTermination + + + CFBundleDocumentTypes + + + CFBundleTypeName + Text Document + CFBundleTypeRole + Editor + LSHandlerRank + Alternate + LSItemContentTypes + + public.plain-text + + + + CFBundleTypeName + Folder + CFBundleTypeRole + Editor + LSHandlerRank + Alternate + LSItemContentTypes + + public.folder + + + + + diff --git a/dev/macos/Sources/AppDelegate.swift b/dev/macos/Sources/AppDelegate.swift new file mode 100644 index 00000000..dbc0fbc9 --- /dev/null +++ b/dev/macos/Sources/AppDelegate.swift @@ -0,0 +1,704 @@ +import AppKit + +// The macOS host: one window, one view, one core. libpardes owns the state +// machine, the ptys and every worker thread; this file owns the window, the +// menu bar, and the pump that lets the core move at all. +// +// PardesView translates events and calls pardes_key / pardes_mouse / +// pardes_scroll itself, but never pardes_tick — the core only queues what it +// was told and does nothing until it is pumped. Rather than grow the view's +// delegate a third method for "I just fed the core", the view posts +// pardesDidInputNotification after every input call and we answer it with +// pump(). That name is declared once, in PardesView.swift, precisely so the two +// files cannot drift apart on a string literal. + +final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { + private var window: NSWindow! + private var view: PardesView! + // One display-clock chain at a time. Input and pty notifications may all + // call pump(), but none advances animation; they only observe this flag and + // leave the already-scheduled frame alone. + private var pumpScheduled: Bool = false + /// The display's own clock, when the OS will lend us one. + /// + /// The fallback below is a `DispatchQueue.asyncAfter(0.016)` chain re-armed + /// AFTER each frame's tick, drain and draw, so its real period is 16 ms plus + /// all of that — comfortably slower than 60 Hz, and jittery, and never in + /// phase with the refresh. That is what makes an animation look choppy even + /// when nothing is dropping frames. A display link fires once per refresh, + /// phase-locked to vsync, which is the cadence the picture is actually + /// presented at. + /// + /// Cadence is now only a SMOOTHNESS question: `pardes_animation_tick` + /// spends measured elapsed time, so a 120 Hz link does not double-speed an + /// animation and a slow one does not halve it. + /// Held as `AnyObject` because a stored property cannot carry + /// `@available`, and this file still deploys to macOS 13. + private var displayLink: AnyObject? + // The core is a singleton with no "is it alive" query, and Finder can hand + // us documents before applicationDidFinishLaunching runs. Every entry point + // that would call into libpardes from outside the launch sequence checks + // this first; opens that arrive early queue below instead of crashing in a + // core that has not been constructed. + private var coreIsUp: Bool = false + private var pendingOpens: [URL] = [] + + func applicationDidFinishLaunching(_ notification: Notification) { + // Captured before the chdir below, because `pardes ./foo.zig` from a + // terminal means foo.zig in the shell's directory, not in $HOME. + let launchDirectory = FileManager.default.currentDirectoryPath + + // A bundle launched from Finder, the Dock or `open(1)` inherits cwd `/` + // — launchd's, not any shell's — so the first pane's shell would start + // at the root of the disk and every relative path the user types would + // resolve there. A binary run from a terminal inherits that terminal's + // directory, which is already what was meant, so only the `/` case is + // corrected: anything else is somebody's deliberate choice. + if launchDirectory == "/" { + FileManager.default.changeCurrentDirectoryPath(NSHomeDirectory()) + } + + installMainMenu() + + // Initial body size. PardesView owns later Ctrl+/Ctrl- changes and + // rebuilds both body and tagline metrics before publishing the resize. + view = PardesView(fontSize: defaultFontSize) + + let want = NSSize(width: 1000, height: 700) + window = NSWindow( + contentRect: NSRect(origin: .zero, size: want), + styleMask: [.titled, .closable, .miniaturizable, .resizable], + backing: .buffered, + defer: false) + window.title = "pardes" + // We hold this window strongly for the life of the app. Leaving + // isReleasedWhenClosed on would have AppKit release it out from under + // that reference the moment the close button is pressed. + window.isReleasedWhenClosed = false + let container = NSView(frame: NSRect(origin: .zero, size: want)) + container.autoresizesSubviews = true + view.frame = container.bounds + view.autoresizingMask = [.width, .height] + container.addSubview(view) + window.contentView = container + + // Trim the content box down to whole cells: a partial column or row is + // dead space the core can never draw into. + window.setContentSize(NSSize( + width: (want.width / view.cellWidth).rounded(.down) * view.cellWidth, + height: (want.height / view.cellHeight).rounded(.down) * view.cellHeight)) + // Autosave after the snap, never before: on a first run there is no + // saved frame and the window must still open at the snapped default, + // and registering the name first would have AppKit write the unsnapped + // 1000x700 out as the remembered geometry. + window.setFrameAutosaveName("pardes") + // setFrameAutosaveName only arms the saving half; the restore is this + // call, and it reports whether there was anything to restore. Both must + // happen before pardes_init, because the grid we boot the core with has + // to be the grid the window actually ends up at. + if !window.setFrameUsingName("pardes") { + window.center() + } + // Resize in whole cells. Increments are measured from the window's + // current size rather than from zero, which is why the snap above still + // matters: without it every drag would land a half-column short of the + // frame, and the view would draw a strip it can never put a glyph in. + window.contentResizeIncrements = NSSize(width: view.cellWidth, height: view.cellHeight) + // One core per process, so a second tab would be an empty window with + // no grid behind it. macOS offers tabs on any titled resizable window + // unless told otherwise. + window.tabbingMode = .disallowed + // What the core is wearing, not a constant agreed by hand — two things + // draw and both have to say the same thing: the view fills its own + // bounds, and AppKit fills the titlebar and every pixel of a live + // resize the view has not caught up with yet. Without that agreement + // the gap flashes on every drag. It also owns window.appearance: a dark + // window with a light-mode titlebar reads as a bug, and so does the + // reverse the moment someone wears `acme`. + applyTheme() + // On screen before pardes_init, so that the backingScaleFactor read + // when seeding the cell metrics below is the one of the screen the + // window actually landed on. Drawing before the core exists costs an + // empty frame; metrics seeded at 1x would stay wrong forever, because + // a scale change moves no bounds and so fires no resize. + window.makeKeyAndOrderFront(nil) + // AppKit may promote a content view that accepts first responder on its + // own, but "may" is not something to bet every keystroke on, and there + // is no click-to-focus path here that would recover it. + window.makeFirstResponder(view) + // activate(ignoringOtherApps:) is deprecated in favour of activate() on + // the 14 SDK, but activate() does not exist at our 13.0 deployment + // target and the deprecation does not fire below it. This is the call + // to change the day macos_min_version reaches 14. + NSApp.activate(ignoringOtherApps: true) + + var runtime = pardes_runtime_s( + userdata: Unmanaged.passUnretained(self).toOpaque(), + wakeup: { ud in + // A pty reader thread. Every other function in pardes.h is + // main-thread-only, so this hop is the entire body — touching + // any core state here would be the race the hop exists to + // avoid. + let host = Unmanaged.fromOpaque(ud!).takeUnretainedValue() + DispatchQueue.main.async { host.pump() } + }, + set_clipboard: { _, text, len in + // Main thread, from inside pardes_tick. `text` is borrowed for + // the length of the call, so the String has to be a copy. + var yank: String = "" + if let text = text, len > 0 { + let bytes = UnsafeRawBufferPointer(start: UnsafeRawPointer(text), count: len) + yank = String(decoding: bytes, as: UTF8.self) + } + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + _ = pasteboard.setString(yank, forType: .string) + }, + read_clipboard: { _ in + // Also the main thread, also inside pardes_tick — but this one + // answers immediately: NSPasteboard reads are synchronous, so + // the paste lands back in the core before this call returns. + // No pump, deliberately: the tick that emitted the effect is + // still draining and picks up whatever the paste queued. + guard let text = NSPasteboard.general.string(forType: .string) else { return } + AppDelegate.paste(text) + }) + + // The real grid, never a placeholder: the core holds each shell's + // greeting until it has seen a size, so a correction sent afterwards + // arrives with the first prompt already wrapped to the wrong width. + let grid = view.gridSize + let rc = pardes_init(&runtime, grid.cols, grid.rows) + if rc != 0 { + NSLog("pardes: the core failed to boot at \(grid.cols)x\(grid.rows), pardes_init returned \(rc)") + // Not NSApp.terminate — that runs applicationWillTerminate, which + // would call pardes_deinit on a core that never came up. + exit(1) + } + coreIsUp = true + + // Only now, after init. setContentSize above resized the view, and a + // pardesViewDidResize landing before pardes_init would have pushed a + // resize into a core that did not exist yet. + view.delegate = self + NotificationCenter.default.addObserver( + self, selector: #selector(inputArrived(_:)), name: pardesDidInputNotification, object: nil) + + // pardes_init takes no cell metrics, so the core's PDF placement would + // have none until the user first dragged the window. This seeds them, + // and pumps. Repeating the size init just saw is safe by design: the + // core compares the effective pixel viewport, not the resize event, so + // duplicate SIGWINCH-shaped notifications are already a no-op. + pardesViewDidResize(view) + // That pump also consumes a Font from startup config, if present. Only + // now is the face on screen final enough to seed Config's effective + // name and point size; later adopts and zooms report from wear(). + view.reportEffectiveFont() + + // Positional paths, after the first frame's worth of state exists. + // Anything starting with `-` is skipped rather than opened: the core + // has no flags yet, and Finder itself passes `-psn_0_...` on some + // launch paths, which would otherwise become a Look for a file that + // does not exist. + for argument in CommandLine.arguments.dropFirst() where !argument.hasPrefix("-") { + look(absolutePath(of: argument, relativeTo: launchDirectory)) + } + + // Documents that Finder handed us before the core existed. + let queued = pendingOpens + pendingOpens = [] + for url in queued { + look(url.path) + } + } + + // Finder double-click, Dock drop, `open -a pardes file`, and "Open With". + // The URL-array form rather than application(_:openFile:), which has been + // deprecated since 10.13 and only ever reports one path at a time. + func application(_ application: NSApplication, open urls: [URL]) { + // A non-file URL would arrive here only through a URL scheme we do not + // register, but Look wants a path and would treat the scheme prefix as + // part of one. + let files = urls.filter { $0.isFileURL } + guard coreIsUp else { + // Finder sends these between applicationWillFinishLaunching and + // applicationDidFinishLaunching, so they arrive before the core is + // constructed and are replayed at the end of launch. They land + // after the argv paths, which costs nothing: each path is an + // independent Look and only the last one takes focus. + pendingOpens.append(contentsOf: files) + return + } + for url in files { + look(url.path) + } + } + + // ---------------------------------------------------------------- menu + + // Built in code rather than loaded from a nib. There is no Xcode project + // here (see docs/macos.md), so a MainMenu.xib would be a binary blob nobody + // in this tree can edit; the menu is thirty lines of Swift instead. + // + // Every item that reaches the core goes through run(), which is + // pardes_command — the core's own `command` event, the same channel a + // pardes nested inside another one speaks over. So a menu item is exactly + // the text you could have typed into a tag and executed, and there is no + // second vocabulary to keep in step with builtins.zig. + // + // The cost of having a menu at all is that these chords are now the menu's + // and the core can never see them: Cmd+Q, Cmd+H, Opt+Cmd+H, Cmd+O, Cmd+N, + // Cmd+S, Cmd+W, Cmd+V, Cmd+M and Cmd+?. AppKit offers a key equivalent to + // the main menu before the event ever reaches the key window. Every other + // Cmd chord still dies in PardesView, which swallows them because the ABI's + // modifier mask has ctrl, alt and shift and no super bit — a Cmd chord + // handed to the core would arrive as its unmodified letter and type itself + // into the buffer. + private func installMainMenu() { + let appName = ProcessInfo.processInfo.processName + let main = NSMenu() + + // AppKit treats the first top-level item as the application menu + // whatever it is titled, and substitutes the bundle name in bold. + let app = submenu(appName, of: main) + app.addItem(withTitle: "About \(appName)", + action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), + keyEquivalent: "") + app.addItem(.separator()) + app.addItem(withTitle: "Hide \(appName)", + action: #selector(NSApplication.hide(_:)), keyEquivalent: "h") + let hideOthers = app.addItem(withTitle: "Hide Others", + action: #selector(NSApplication.hideOtherApplications(_:)), + keyEquivalent: "h") + hideOthers.keyEquivalentModifierMask = [.command, .option] + app.addItem(withTitle: "Show All", + action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "") + app.addItem(.separator()) + app.addItem(withTitle: "Quit \(appName)", + action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") + + let file = submenu("File", of: main) + file.addItem(command("Open\u{2026}", #selector(menuOpen(_:)), "o")) + file.addItem(command("New", #selector(menuNew(_:)), "n")) + file.addItem(command("Save", #selector(menuSave(_:)), "s")) + file.addItem(.separator()) + // performClose: goes to the key window through the responder chain, so + // it keeps working if this app ever grows a panel. + file.addItem(withTitle: "Close Window", + action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") + + // The workspace tag row's commands, in the place macOS keeps window + // commands. The build hands that row to this menu bar (see + // docs/macos.md): the words are the same builtins the tag carried, + // spelled exactly as a tag Exec would type them, and nothing here is + // editable — the menu is the tag's buttons, not the tag. + let builtins = submenu("Builtins", of: main) + for word in ["Newcol", "Joincol", "Find", "Grep", "Changelog", + "Dump", "NextColor", "Debug", "Kill"] { + builtins.addItem(command(word, #selector(menuBuiltin(_:)), "")) + } + let edit = submenu("Edit", of: main) + // Paste and nothing else. Copy, Cut, Undo and Select All have no + // builtin behind them — the core yanks into the clipboard on its own + // selection gestures and has no undo command to call — and a greyed or + // silently dead menu item teaches the user the menu lies. When the core + // grows those commands they belong here, spelled as run("...") like + // everything else. + edit.addItem(command("Paste", #selector(menuPaste(_:)), "v")) + + // The only menu whose items are not core commands: the font size is a + // property of this shell and nothing else. `Font` picks the FACE and + // lives in the topbar with the other builtins; the size is where the + // window is, so it is where macOS keeps it. + let viewMenu = submenu("View", of: main) + // Cmd+= rather than Cmd++: the key is unshifted `=` on every layout + // that has a `+` above it, and AppKit matches the character, not the + // engraving. The item is titled with the plus users look for. + viewMenu.addItem(command("Zoom In", #selector(menuZoomIn(_:)), "=")) + viewMenu.addItem(command("Zoom Out", #selector(menuZoomOut(_:)), "-")) + viewMenu.addItem(command("Actual Size", #selector(menuZoomReset(_:)), "0")) + + let windowMenu = submenu("Window", of: main) + windowMenu.addItem(withTitle: "Minimize", + action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m") + windowMenu.addItem(withTitle: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "") + + let help = submenu("Help", of: main) + // Cmd+? is the system-wide help chord; AppKit draws it as the shift of + // Cmd+/ without being told about the shift. + help.addItem(command("\(appName) Help", #selector(menuHelp(_:)), "?")) + help.addItem(command("Tutorial", #selector(menuTutor(_:)), "")) + + NSApp.mainMenu = main + // Handing AppKit these two makes it keep the window list up to date and + // put the Help search field at the top of the Help menu. Both must come + // after mainMenu is assigned, or AppKit has nothing to attach them to. + NSApp.windowsMenu = windowMenu + NSApp.helpMenu = help + } + + private func submenu(_ title: String, of parent: NSMenu) -> NSMenu { + let holder = NSMenuItem(title: title, action: nil, keyEquivalent: "") + // The submenu's own title is what AppKit shows in the menu bar for the + // Window and Help menus, which it looks up by title rather than by the + // item that holds them. + let menu = NSMenu(title: title) + holder.submenu = menu + parent.addItem(holder) + return menu + } + + // An item that runs one of our own actions. Explicitly targeted at self + // rather than left to the responder chain: PardesView is the first + // responder and answers none of these, and an untargeted item that finds no + // handler renders greyed out. + private func command(_ title: String, _ action: Selector, _ key: String) -> NSMenuItem { + let item = NSMenuItem(title: title, action: action, keyEquivalent: key) + item.target = self + return item + } + + @objc private func menuOpen(_ sender: Any?) { + let panel = NSOpenPanel() + panel.canChooseFiles = true + // Directories are first-class Look targets — the core opens one as a + // directory pane, which is how you navigate in acme — so refusing them + // here would hide half of what Look does. + panel.canChooseDirectories = true + panel.allowsMultipleSelection = true + for url in panel.urls where url.isFileURL { + look(url.path) + } + } + + /// Any workspace-tag word. The title is the builtin's own spelling, so + /// this is the same `run` a tag Exec performs and there is no second + /// vocabulary to keep in step. + @objc private func menuBuiltin(_ sender: NSMenuItem) { run(sender.title) } + + + @objc private func menuNew(_ sender: Any?) { run("New") } + @objc private func menuSave(_ sender: Any?) { run("Save") } + @objc private func menuHelp(_ sender: Any?) { run("Help") } + @objc private func menuTutor(_ sender: Any?) { run("Tutor") } + + // Deliberately the view's paste path and not a second one: Cmd+V from the + // menu and Cmd+V in the view must put the same bytes in through + // pardes_paste, or the two would diverge the first time either grows a + // filter. + @objc private func menuPaste(_ sender: Any?) { + guard coreIsUp else { return } + pardesViewRequestsPaste(view) + } + + // Zoom does not go through the core at all: it changes the cell, the view + // reports the new grid, and the core reflows to it exactly as it does for + // a window drag. Guarded on coreIsUp only because the resize callback it + // triggers calls into libpardes. + @objc private func menuZoomIn(_ sender: Any?) { + guard coreIsUp else { return } + view.zoom(by: 1) + } + + @objc private func menuZoomOut(_ sender: Any?) { + guard coreIsUp else { return } + view.zoom(by: -1) + } + + @objc private func menuZoomReset(_ sender: Any?) { + guard coreIsUp else { return } + view.zoomReset() + } + + // ---------------------------------------------------------------- core + + // One builtin command line, run as if it had been typed into a tag and + // executed. `command` is bridged to a temporary NUL-terminated UTF-8 buffer + // that lives exactly as long as the call, which is exactly as long as the + // core borrows it. + private func run(_ command: String) { + guard coreIsUp else { return } + pardes_command(command, command.utf8.count) + pump() + } + + // Look's operand is the whole tail of the line (executeBuiltinLine in + // src/pardes.zig splits on the first space and trims the rest), so a path + // with spaces in it needs no quoting and must not get any — quotes would + // become part of the filename. + private func look(_ path: String) { run("Look \(path)") } + + // argv paths are whatever the shell handed us. The core resolves a relative + // Look against the pane's directory, not the process's, so `pardes + // ./foo.zig` would open the wrong foo.zig — or nothing — unless it is made + // absolute here against the directory the process was launched from. + private func absolutePath(of argument: String, relativeTo directory: String) -> String { + let expanded = (argument as NSString).expandingTildeInPath + guard !(expanded as NSString).isAbsolutePath else { + return (expanded as NSString).standardizingPath + } + return ((directory as NSString).appendingPathComponent(expanded) as NSString).standardizingPath + } + + /// Dress the WINDOW in what the core is wearing: the background AppKit + /// paints where the view does not (the titlebar, and the strip a live + /// resize outruns). + /// + /// Cheap enough to call every pump: the view compares before it dirties + /// itself, and the window properties are written only when the answer + /// moved. `dressed` is what makes the FIRST call unconditional — a boot + /// theme whose background happened to equal the view's starting guess + /// would otherwise leave the window in AppKit's default clothes forever. + private var dressed = false + + private func applyTheme() { + // Both reads happen every pump, and neither may be short-circuited by + // the other: `changed` has to be the OR of two adoptions, not the first + // one that answered true, or a Theme and a WindowOpacity in the same + // tick would leave one of them unworn. + let themeChanged = view.adoptThemeBG(pardes_theme_bg()) + let opacityChanged = view.adoptWindowOpacity(pardes_window_opacity()) + guard themeChanged || opacityChanged || !dressed else { return } + dressed = true + if let rgb = view.themeBG { + window.isOpaque = view.backgroundAlpha >= 1 + window.backgroundColor = view.backgroundAlpha < 1 ? .clear : NSColor( + srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, + green: CGFloat((rgb >> 8) & 0xFF) / 255, + blue: CGFloat(rgb & 0xFF) / 255, + alpha: view.backgroundAlpha) + // ...and follow the theme into light mode, so the titlebar, the + // traffic lights and the resize cursor stop belonging to a + // different application than the grid under them. Luminance off + // the same sRGB channels the grid is drawn with. + let luma = (0.2126 * CGFloat((rgb >> 16) & 0xFF) + + 0.7152 * CGFloat((rgb >> 8) & 0xFF) + + 0.0722 * CGFloat(rgb & 0xFF)) / 255 + window.appearance = NSAppearance(named: luma > 0.5 ? .aqua : .darkAqua) + } else { + // Transparent: the window stops painting anything of its own. + // isOpaque false lets the desktop show through at all — a titled + // window is opaque by default and would composite over it. + window.isOpaque = false + window.backgroundColor = .clear + window.appearance = NSAppearance(named: .darkAqua) + } + } + + /// The focused pane, in the titlebar: the proxy icon macOS lets you drag + /// and Cmd-click for the path, and the dot in the close button that means + /// unsaved. + /// + /// A pure read-out — the window says what the core already decided, and + /// nothing here can change it. There is no document ARCHITECTURE behind it + /// and deliberately so: no NSDocument, no save panel, no "do you want to + /// save" on close. Save is a builtin, the pane's tag says so, and this is + /// the same two facts spelled where a Mac user looks for them. + /// + /// Cached, because setting representedURL makes AppKit hit the filesystem + /// for the icon and this runs on every pump. + private var shownPath: String? + private var shownDirty = false + + private func applyDocument() { + let path = pardes_active_path().map { String(cString: $0) } + if path != shownPath { + shownPath = path + // A terminal or an output buffer is not a document: no path means + // no proxy icon, rather than a stale one from the last file pane. + window.representedURL = path.map { URL(fileURLWithPath: $0) } + // ...and the title goes with it. A proxy icon beside a title that + // names something else reads as a bug, and AppKit will not fill the + // title in for us while `title` has been set by hand. The window is + // a SESSION and not a document, so it falls back to the app's own + // name the moment focus lands somewhere with no file behind it. + window.title = path.map { ($0 as NSString).lastPathComponent } ?? "pardes" + } + let dirty = pardes_active_dirty() + if dirty != shownDirty { + shownDirty = dirty + window.isDocumentEdited = dirty + } + } + + @objc private func inputArrived(_ notification: Notification) { + pump() + } + + // Every path into the core ends here. pardes_tick drains the ptys and runs + // the effects the core queued, so nothing the user did takes hold until it + // runs. + private func pump() { + // Unconditionally dirty, and NOT `if pardes_tick()`. That return value + // answers "did I do any IO" — it is true when a pty produced bytes or + // an effect was performed, and false for everything the core changes on + // its own. A cursor moved with j, a selection, a mode change and a + // scroll all queue nothing and perform nothing, so gating the repaint + // on it leaves the screen showing the state before the keystroke until + // some unrelated event happens to force a frame. Measured: four `j` + // presses in a file pane produced a byte-identical screenshot. + // + // The waste is bounded and small. AppKit coalesces needsDisplay within + // a runloop pass, so a burst of pty output is still one frame, and an + // idle wakeup cannot happen — a reader only wakes the host after it has + // read bytes. + _ = pardes_tick() + view.needsDisplay = true + // TaglineSize is host-owned raster state just like Font, but unlike a + // body face change it does not resize the grid. Polling the one-byte + // core setting keeps startup config and live commands on one path. + view.adoptTaglinePercent(pardes_gui_tagline_font_percent()) + // After the tick, because a `Theme` command runs inside it and the + // window has to follow the grid in the same frame rather than at the + // next launch. + applyTheme() + applyDocument() + + // Two verbs, two patterns, because they are two different answers: + // Exec did something, so it gets .generic, the definite tap of a + // committed action; Look went somewhere, so it gets .alignment, the + // lighter detent AppKit uses when a dragged guide snaps into place. + // Same distinction the core draws in Haptic (src/pardes.zig). + // + // No capability check on purpose. perform() is a silent no-op on a Mac + // with no Force Touch trackpad and when the user has turned feedback + // off in System Settings, so a check here would only be a second place + // to get the answer wrong — and it would be wrong the moment an + // external trackpad is plugged in mid-session. + let pulse = pardes_take_haptic() + if pulse == PARDES_HAPTIC_EXEC { + NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now) + } else if pulse == PARDES_HAPTIC_LOOK { + NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now) + } + + // Beside the haptic, and for the same reason: the `Font` builtin ran + // synchronously inside whatever input reached the core, so its answer + // is already waiting by the time the tick returns. The view re-measures + // and calls back through pardesViewDidResize, so the grid the core is + // holding follows the cell that just changed size. + var fontSize: UInt16 = 0 + if let wanted = pardes_font_take(&fontSize) { + view.adoptFont(path: String(cString: wanted), sizeHundredths: fontSize) + } + + if pardes_should_quit() { + NSApp.terminate(nil) + return + } + // Input and pty pumps only drain work. A frame-count animation advances + // on this 16 ms clock, and only after the sample dirtied above was + // actually presented. A burst of input cannot make it run fast, while + // an occluded/coalesced AppKit view cannot consume invisible samples. + scheduleAnimationFrame() + } + + private func scheduleAnimationFrame() { + guard pardes_animating() else { + stopDisplayLink() + return + } + if #available(macOS 14.0, *) { + // One link for the whole animating run, not one callback armed per + // frame: re-arming after the work is what put the period at 16 ms + // PLUS the work, and no amount of tuning that constant fixes a + // clock that is not the display's. + if displayLink == nil { + let link = view.displayLink(target: self, selector: #selector(displayLinkFired)) + link.add(to: .main, forMode: .common) + displayLink = link + } + return + } + // macOS 13 has no NSView display link. Keep the old chain, which is now + // only a cadence compromise rather than a correctness one — the tick + // spends measured time either way. + guard !pumpScheduled else { return } + let awaitingPresentation = view.presentationSerial + pumpScheduled = true + DispatchQueue.main.asyncAfter(deadline: .now() + 0.016) { + self.pumpScheduled = false + self.animationFrame(after: awaitingPresentation) + } + } + + private func stopDisplayLink() { + if #available(macOS 14.0, *) { (displayLink as? CADisplayLink)?.invalidate() } + displayLink = nil + } + + @objc private func displayLinkFired() { + guard coreIsUp else { return } + animationFrame(after: pendingPresentation) + } + + /// The presentation serial the last dirtied sample is waiting on. Held + /// across display-link callbacks because the link, unlike the old chain, + /// does not carry it in a closure. + private var pendingPresentation: UInt64 = 0 + + private func animationFrame(after awaitingPresentation: UInt64) { + guard view.presentationSerial != awaitingPresentation else { + // Keep the dirty sample pending. AppKit may have coalesced this + // draw or the window may be occluded; retry on the next refresh + // without advancing, until draw(_:) supplies the presentation + // permit. On the link that costs ONE refresh; the old chain paid a + // fresh 16 ms for it, which is where the visible hitching came from. + view.needsDisplay = true + if #available(macOS 14.0, *) {} else { scheduleAnimationFrame() } + return + } + _ = pardes_animation_tick() + pendingPresentation = view.presentationSerial + pump() + } + + func pardesViewDidResize(_ view: PardesView) { + let grid = view.gridSize + // cell_w/cell_h are physical pixels. The core hands them to the native + // PDF placement path, and a point is two pixels on a Retina display, so + // passing points would place every page at half size. + let scale: CGFloat = window.backingScaleFactor + pardes_resize( + grid.cols, grid.rows, + UInt16((view.cellWidth * scale).rounded()), + UInt16((view.cellHeight * scale).rounded())) + pardes_row_metrics(UInt16(max(1,(view.cellWidth*scale).rounded())), UInt16(max(1,(view.cellHeight*scale).rounded())), + UInt16(max(1,(view.taglineCellWidth*scale).rounded())), UInt16(max(1,(view.taglineBandHeight*scale).rounded()))) + pump() + } + + func pardesViewRequestsPaste(_ view: PardesView) { + guard let text = NSPasteboard.general.string(forType: .string) else { return } + AppDelegate.paste(text) + pump() + } + + // Swift lends a temporary NUL-terminated UTF-8 buffer for the duration of + // the call, which is exactly as long as the core borrows it. Static, and + // pumping is the caller's business: the read_clipboard callback is a C + // function pointer that can capture nothing and is already inside a tick, + // where the gesture path is not. + private static func paste(_ text: String) { + pardes_paste(text, text.utf8.count) + } + + // ponytail: one window, no tabs — the core has no multi-window notion, so + // the last window closing really is the end of the process. + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + // Nothing in this app's UI state can be restored: the window is one view + // over a core that has to replay its own session, and the frame is already + // handled by setFrameAutosaveName. Answering true opts into the secure + // coder AppKit wants; leaving the method out makes macOS 14 and later log a + // deprecation warning on every launch. + func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } + + func applicationWillTerminate(_ notification: Notification) { + pardes_deinit() + } +} diff --git a/dev/macos/Sources/FileWatcher.swift b/dev/macos/Sources/FileWatcher.swift new file mode 100644 index 00000000..1fee2fd8 --- /dev/null +++ b/dev/macos/Sources/FileWatcher.swift @@ -0,0 +1,122 @@ +// Per-path live reload for the native app. One source watches the file for +// in-place writes; another watches its parent because editors normally save by +// renaming a new inode over the old one. The file source is rearmed after a +// quiet edge so it follows that replacement rather than the unlinked old inode. + +import Darwin +import Dispatch +import Foundation + +private final class WatchedPath { + let pane: UInt8 + let generation: UInt32 + private let path: String + private let directorySource: DispatchSourceFileSystemObject + private var fileSource: DispatchSourceFileSystemObject? + private var active = true + private var eventSerial: UInt64 = 0 + + init?(pane: UInt8, generation: UInt32, path: String) { + let directory = URL(fileURLWithPath: path) + .deletingLastPathComponent().path + let descriptor = directory.withCString { + Darwin.open($0, O_EVTONLY | O_CLOEXEC) + } + guard descriptor >= 0 else { return nil } + + self.pane = pane + self.generation = generation + self.path = path + directorySource = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: descriptor, + eventMask: [.write, .delete, .rename, .extend, .attrib, .link, .revoke], + queue: .main) + directorySource.setCancelHandler { _ = Darwin.close(descriptor) } + directorySource.setEventHandler { [weak self] in self?.pathChanged() } + reopenFileSource() + directorySource.activate() + } + + /// The directory source catches rename-over saves, while the file source + /// catches programs which truncate/write the existing inode. Reopen the + /// latter after every quiet edge because an atomic save leaves it attached + /// to the unlinked old inode forever otherwise. + private func reopenFileSource() { + if let old = fileSource { old.cancel() } + fileSource = nil + guard active else { return } + let descriptor = path.withCString { Darwin.open($0, O_EVTONLY | O_CLOEXEC) } + guard descriptor >= 0 else { return } + let next = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: descriptor, + eventMask: [.write, .delete, .rename, .extend, .attrib, .link, .revoke], + queue: .main) + next.setCancelHandler { _ = Darwin.close(descriptor) } + next.setEventHandler { [weak self] in self?.pathChanged() } + fileSource = next + next.activate() + } + + /// Vnode sources can emit several edges for one save. Reset a small quiet + /// period on every edge; generation plus exact Zig-side identity checks + /// remain authoritative, so this delay is latency control rather than + /// correctness state. + private func pathChanged() { + guard active else { return } + eventSerial &+= 1 + let scheduled = eventSerial + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(45)) { [weak self] in + guard let self, self.active, self.eventSerial == scheduled else { return } + self.reopenFileSource() + pardes_watch_changed(self.pane, self.generation) + } + } + + func cancel() { + guard active else { return } + active = false + eventSerial &+= 1 + if let old = fileSource { old.cancel() } + fileSource = nil + directorySource.cancel() + } + + deinit { cancel() } +} + +private final class FileWatchRegistry { + static let shared = FileWatchRegistry() + private var slots: [UInt8: WatchedPath] = [:] + + func set(pane: UInt8, generation: UInt32, path: String?) { + if let old = slots.removeValue(forKey: pane) { old.cancel() } + guard let path, + let watched = WatchedPath( + pane: pane, generation: generation, path: path) + else { return } + slots[pane] = watched + } +} + +/// Called only by libpardes's main-thread effect drain. A nil pointer stops the +/// slot. The byte count avoids a second sentinel copy in Zig; Foundation paths +/// are Unicode, so malformed UTF-8 is rejected rather than watched under a +/// replacement spelling that could name a different file. +@_cdecl("pardes_host_watch_file") +func pardesHostWatchFile( + _ pane: UInt8, + _ generation: UInt32, + _ path: UnsafePointer?, + _ pathLength: Int +) { + guard let path, pathLength > 0 else { + FileWatchRegistry.shared.set(pane: pane, generation: generation, path: nil) + return + } + let bytes = UnsafeBufferPointer(start: path, count: pathLength) + guard let value = String(bytes: bytes, encoding: .utf8) else { + FileWatchRegistry.shared.set(pane: pane, generation: generation, path: nil) + return + } + FileWatchRegistry.shared.set(pane: pane, generation: generation, path: value) +} diff --git a/dev/macos/Sources/PardesView.swift b/dev/macos/Sources/PardesView.swift new file mode 100644 index 00000000..23cd0f78 --- /dev/null +++ b/dev/macos/Sources/PardesView.swift @@ -0,0 +1,2728 @@ +// The AppKit half of the macOS backend: NSEvent in, pardes_* out, one +// CoreGraphics pass per frame back. +// +// This file keeps no model of the screen. The core owns the grid and hands it +// over whole through src/macos/pardes.h, so everything here is translation, and +// the only state worth holding is the font metrics — expensive to measure and +// replaced only by Font/TaglineSize/zoom — plus the gesture state remembered +// between events: which button a click started with, and how hard it is being +// pressed. +// +// Every NSEvent override decodes and then calls one of the post-decode entry +// points below (press/release/drag/click/scroll/rotate/typeKey). That split is +// not decoration: NSTouch, pressure stages and rotation have no public +// constructors, so a test can never synthesize them, and the only way the +// trackpad behaviour is reachable by anything but a finger is for the decision +// to live one call below the event. test/macos_e2e.swift drives exactly those +// entry points. +// +// Every C constant below is wrapped in an explicit conversion (UInt16(...), +// UInt32(...)) rather than used bare. A macro's imported Swift type is decided +// by the importer, not by us, and this file should not have an opinion about it. + +import AppKit +import CoreText + +/// Posted after every call this view makes into the core, and answered by +/// AppDelegate.pump(). The core only queues what it was told and does nothing +/// until it is pumped, so an input without one of these is an input that +/// visibly did nothing. Declared here, where the posts are. +let pardesDidInputNotification = Notification.Name("pardesDidInput") + +/// A cell, already clamped to the frame the core last rendered. +struct GridPoint { + var col: UInt16 + var row: UInt16 +} + +protocol PardesViewDelegate: AnyObject { + func pardesViewDidResize(_ view: PardesView) + func pardesViewRequestsPaste(_ view: PardesView) +} + +/// What a click means, from the fingers resting on the trackpad and the button +/// stream AppKit chose to deliver it on. Pure on purpose: NSTouch cannot be +/// constructed, so this is the part of the gesture a test can reach. +/// +/// acme's three buttons are the whole vocabulary — 1 selects, 2 executes, +/// 3 looks — and a trackpad has one surface. More than one finger is Exec, +/// because running something is what a hand does over and over and it gets +/// the gesture that costs nothing; Look is the deep press, one deliberate +/// push past the click for the verb that goes somewhere. +/// +/// Two and three fingers are the same verb here, and that is the hardware +/// talking rather than a shrug. macOS's secondary click is "click or tap with +/// TWO OR MORE fingers": with it on — the default — a three-finger click is +/// delivered as rightMouseDown exactly like a two-finger one, and a view that +/// trusts the stream calls both of them Look. Measured on real hardware, which +/// is the only way this was ever going to be found: +/// `rightMouseDown: resting=3`. So the count is what keeps a multi-finger +/// click off Look, and the stream cannot be trusted to do it. +/// +/// The stream is only the fallback, for when there are no fingers to count: +/// a real mouse's right button is Look and its middle button is Exec, and both +/// arrive with an empty touch set. +enum Trackpad { + static func button(stream: pardes_mouse_button_e, fingers: Int) -> pardes_mouse_button_e { + switch fingers { + case 2...: return PARDES_MOUSE_MIDDLE + // One finger, or none to count: the stream is the answer. A trackpad + // single click comes in on the left stream and stays left; a real + // mouse's right and middle buttons keep their acme meanings. + default: return stream + } + } + + /// A force click is a deliberate second gesture on top of an ordinary one, + /// so it gets the verb that goes somewhere rather than the one that runs + /// something: press harder and you Look. + static let forceClickButton: pardes_mouse_button_e = PARDES_MOUSE_RIGHT +} + +// Matches bg_default/fg_default in src/gui/gui.zig. Two shells render the +// same core; if these drift, comparing +// a screenshot across backends stops meaning anything. +let pardesDefaultFG: UInt32 = 0xCC_CC_CC +let pardesDefaultBG: UInt32 = 0x12_12_12 + +/// Pinned sRGB for rasterized attachments, so a PDF page's bytes mean the same +/// thing here as they do in the SDL shell. DeviceRGB is the fallback rather +/// than a crash: a machine with no sRGB profile is not a reason to stop +/// drawing pages. +private let sRGB: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB() + +// UNVERIFIED: kCTFontAttributeName bridged through NSAttributedString.Key. It is +// the same string as .font, but spelling the CoreText key means the value stays +// a CTFont instead of being bridged to NSFont on the way in. +private let fontAttribute = NSAttributedString.Key(kCTFontAttributeName as String) + +// The named sixteen, then xterm's 6x6x6 cube, then the 24-step grey ramp. These +// sixteen are app.mjs's, not gui.zig's: gui.zig borrows ghostty's palette +// because it already links it, and the two disagree on the base colors. +private let ansi16: [UInt32] = [ + 0x00_00_00, 0xCC_00_00, 0x4E_9A_06, 0xC4_A0_00, + 0x34_65_A4, 0x75_50_7B, 0x06_98_9A, 0xD3_D7_CF, + 0x55_57_53, 0xEF_29_29, 0x8A_E2_34, 0xFC_E9_4F, + 0x72_9F_CF, 0xAD_7F_A8, 0x34_E2_E2, 0xEE_EE_EC, +] + +private func paletteColor(_ index: UInt8) -> UInt32 { + if index < 16 { return ansi16[Int(index)] } + if index >= 232 { + let grey = UInt32(8 + (Int(index) - 232) * 10) + return grey << 16 | grey << 8 | grey + } + let n = Int(index) - 16 + func level(_ part: Int) -> UInt32 { part == 0 ? 0 : UInt32(55 + part * 40) } + return level(n / 36) << 16 | level(n / 6 % 6) << 8 | level(n % 6) +} + +private func decodeColor(_ encoded: UInt32, _ fallback: UInt32) -> UInt32 { + if encoded == UInt32(PARDES_COLOR_DEFAULT) { return fallback } + if encoded & UInt32(PARDES_COLOR_TAG_MASK) == UInt32(PARDES_COLOR_INDEXED) { + return paletteColor(UInt8(encoded & 0xFF)) + } + return encoded & UInt32(PARDES_COLOR_RGB_MASK) +} + +/// The four faces, indexed by the two attribute bits that pick one. Also the +/// glyph cache's first key, which is why it is an ordinal and not four fields. +private enum Face: Int, CaseIterable { + case regular = 0, bold = 1, italic = 2, boldItalic = 3 + + init(bold: Bool, italic: Bool) { + self = Face(rawValue: (bold ? 1 : 0) | (italic ? 2 : 0))! + } +} + +/// A background run that must not be painted at all, so the window's own +/// backdrop shows through. Outside the 24-bit RGB range, so it can never +/// collide with a real colour, and distinct from the `.max` the run loop +/// flushes on. +let bgClear: UInt32 = 0x0100_0000 + +/// `block` means the filled cursor sits on this cell. `ground` is what a +/// DEFAULT background resolves to, and `clearGround` asks for those cells to +/// come back as `bgClear` instead of a colour. +private func resolve( + _ cell: pardes_cell_s, + block: Bool, + ground: UInt32, + clearGround: Bool +) -> (fg: UInt32, bg: UInt32, alpha: CGFloat, visible: Bool) { + // The core never painted this cell, which is most of the screen most of the + // time, so this branch is the one that has to stay cheap. + if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { + return block + ? (ground, pardesDefaultFG, 1, false) + : (pardesDefaultFG, clearGround ? bgClear : ground, 1, false) + } + let bgDefault = cell.bg == UInt32(PARDES_COLOR_DEFAULT) + var fg = decodeColor(cell.fg, pardesDefaultFG) + var bg = decodeColor(cell.bg, ground) + // The block cursor is a second reverse, so a cell that is already reversed + // cancels back to normal underneath it. Same rule as emitInstance in + // src/gui/gui.zig; the two must not drift. + var reverse = block + if cell.attrs & UInt16(PARDES_ATTR_REVERSE) != 0 { reverse = !reverse } + if reverse { swap(&fg, &bg) } + // ponytail: PARDES_ATTR_BLINK is decoded into nothing. Honouring it costs a + // timer plus a repaint budget for a bit nothing in pardes emits today; drive + // setNeedsDisplay from an NSTimer here when something does. + let visible = cell.attrs & UInt16(PARDES_ATTR_INVISIBLE) == 0 && cell.len > 0 + // The other shells scale the channels by 6/10. Over a dark background alpha + // lands in the same place and costs one blend instead of three multiplies. + let alpha: CGFloat = cell.attrs & UInt16(PARDES_ATTR_DIM) != 0 ? 0.6 : 1 + // Only an UNREVERSED default background is the ground. A reverse puts the + // text colour there, and text is a real colour that paints. + if clearGround && bgDefault && !reverse { bg = bgClear } + return (fg, bg, alpha, visible) +} + +private func advance(_ font: CTFont, _ character: UniChar) -> CGFloat { + var input = character + var glyph = CGGlyph(0) + guard CTFontGetGlyphsForCharacters(font, &input, &glyph, 1) else { return 0 } + var size = CGSize.zero + CTFontGetAdvancesForGlyphs(font, .horizontal, &glyph, &size, 1) + return size.width +} + +/// The size the window opens at and Cmd+0 returns to. Named here rather than +/// passed in because zoomReset has to know it too, and two spellings of one +/// number is how "actual size" stops being the size it actually opened at. +let defaultFontSize: CGFloat = 14 + +/// The faces CoreText should reach for when the grid face has no glyph. +/// +/// The SDL shell loads a chain of fallback faces itself and rasterizes from +/// whichever one has the codepoint. This shell draws its non-ASCII through +/// CTLine, which already walks a cascade — but the SYSTEM cascade, and the +/// system cascade has never heard of a Nerd Font. Measured on a machine with +/// Mononoki Nerd Font installed: U+E0B0, U+E5FF, U+E700 and U+F015 all resolved +/// to `LastResort`, which is the tofu box. Braille, emoji and CJK resolved +/// fine, which is exactly why this went unnoticed — everything Unicode has an +/// opinion about already worked, and only the Private Use Area did not. +/// +/// Two sources, in this order: +/// +/// 1. `fonts.fallback_names` over the C ABI, so the PREFERENCE ORDER is the +/// one the SDL shell uses and lives in one file. +/// 2. Installed Nerd Font families, found by name and then CONFIRMED BY +/// COVERAGE. Both halves are load-bearing. Coverage alone is not enough: a +/// scan of all 250 families here put `Hannotate TC` and `HanziPen TC` at +/// 4 of 6 probes, because CJK faces map the PUA for their own purposes and +/// would answer a powerline request with an unrelated ideograph. A name +/// alone is not enough either, because "Nerd Font" in a family name is a +/// convention, not a guarantee. So the name decides what a codepoint MEANS +/// and coverage decides whether the face can actually draw it. +/// +/// Computed once. The result is a list of descriptors, which carry no size, so +/// a zoom or a `Font` command reuses it; only installing a font invalidates it, +/// and that is a relaunch. +private enum FontFallbacks { + /// Representative codepoints, one per Nerd Font block that matters: + /// powerline separators, Seti file icons, devicons, Font Awesome. A face + /// answering all four is patched; a face answering one is a coincidence. + private static let nerdProbes: [UInt32] = [0xE0B0, 0xE5FF, 0xE700, 0xF015] + + static let descriptors: [CTFontDescriptor] = build() + + private static func build() -> [CTFontDescriptor] { + var out: [CTFontDescriptor] = [] + var seen = Set() + + func take(_ family: String, _ descriptor: CTFontDescriptor) { + guard seen.insert(family).inserted else { return } + out.append(descriptor) + } + + // 1. The shared preference order. + for index in 0.. 0 else { continue } + let name = String(decoding: UnsafeRawBufferPointer(start: bytes, count: Int(length)), as: UTF8.self) + guard let found = resolve(name) else { continue } + take(found.family, found.descriptor) + } + + // 2. Nerd Fonts that are installed AND cover the blocks. `Mono` cuts + // first: this is a fixed grid, and the propo/variable cuts of the + // same family are drawn to different advances. + let families = (CTFontManagerCopyAvailableFontFamilyNames() as? [String]) ?? [] + let nerd = families.filter { $0.range(of: "nerd font", options: .caseInsensitive) != nil } + for family in nerd.sorted(by: { rank($0) < rank($1) }) { + let descriptor = CTFontDescriptorCreateWithAttributes( + [kCTFontFamilyNameAttribute: family] as CFDictionary) + guard coverage(descriptor, nerdProbes) == nerdProbes.count else { continue } + take(family, descriptor) + } + return out + } + + /// "Mono" before "Propo" before the proportional cut. + private static func rank(_ family: String) -> Int { + if family.range(of: "nerd font mono", options: .caseInsensitive) != nil { return 0 } + if family.range(of: "nerd font propo", options: .caseInsensitive) != nil { return 2 } + return 1 + } + + /// A descriptor that really is the font asked for. CoreText SUBSTITUTES + /// rather than failing — asking it for an uninstalled `SymbolsNerdFont- + /// Regular` hands back Helvetica, and a cascade seeded with Helvetica is a + /// cascade that answers every missing glyph with the wrong one. + private static func resolve(_ name: String) -> (family: String, descriptor: CTFontDescriptor)? { + for attribute in [kCTFontNameAttribute, kCTFontFamilyNameAttribute] { + let query = CTFontDescriptorCreateWithAttributes([attribute: name] as CFDictionary) + guard let match = CTFontDescriptorCreateMatchingFontDescriptor(query, nil) else { continue } + let postScript = CTFontDescriptorCopyAttribute(match, kCTFontNameAttribute) as? String ?? "" + let family = CTFontDescriptorCopyAttribute(match, kCTFontFamilyNameAttribute) as? String ?? "" + guard postScript.compare(name, options: .caseInsensitive) == .orderedSame + || family.compare(name, options: .caseInsensitive) == .orderedSame + else { continue } + return (family.isEmpty ? postScript : family, match) + } + return nil + } + + /// How many of `codepoints` this face can actually draw. Size is irrelevant + /// to coverage, so the probe face is built at a nominal one. + private static func coverage(_ descriptor: CTFontDescriptor, _ codepoints: [UInt32]) -> Int { + let font = CTFontCreateWithFontDescriptor(descriptor, 12, nil) + var hits = 0 + for codepoint in codepoints { + guard let scalar = UnicodeScalar(codepoint) else { continue } + var units = Array(String(scalar).utf16) + var glyphs = [CGGlyph](repeating: 0, count: units.count) + if CTFontGetGlyphsForCharacters(font, &units, &glyphs, units.count) { hits += 1 } + } + return hits + } + + /// `face` with the chain attached. Every face pardes draws with goes through + /// here exactly once, at the base: `CTFontCreateCopyWithSymbolicTraits` and + /// `CTFontCreateCopyWithAttributes` both carry the cascade into the copy, so + /// the bold/italic cuts and the smaller tagline cuts inherit it. + static func attach(to face: CTFont, size: CGFloat) -> CTFont { + guard !descriptors.isEmpty else { return face } + let descriptor = CTFontDescriptorCreateCopyWithAttributes( + CTFontCopyFontDescriptor(face), + [kCTFontCascadeListAttribute: descriptors] as CFDictionary) + return CTFontCreateWithFontDescriptor(descriptor, size, nil) + } +} + +/// Everything that changes when the face or its size does, in one value so +/// that changing either is one assignment and cannot leave half the numbers +/// describing the old font. +/// +/// Built at init and again for a `Font` command or a zoom. The view clears its +/// body/tagline glyph caches beside replacing this value: a CGGlyph is an index +/// into a particular face, so carrying one across a font change is invalid. +private struct Metrics { + let fonts: [CTFont] + /// False only when a non-nil requested file could not produce a fixed-pitch + /// CoreText face. The caller rejects that request and keeps old Metrics. + let acceptedPath: Bool + let ascent: CGFloat + let cellWidth: CGFloat + let cellHeight: CGFloat + let ruleThickness: CGFloat + let underlineOffset: CGFloat + /// ASCII is very nearly the whole screen, so its glyphs are resolved once + /// per face here and never looked up again. + let asciiGlyphs: [[CGGlyph]] + + /// Round `v` onto the backing grid: `scale` is the display's + /// backingScaleFactor, so at 2x this lands on half-points, which are whole + /// device pixels. + private static func snap(_ v: CGFloat, _ scale: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { + (v * scale).rounded(rule) / scale + } + + init(size: CGFloat, path: String?, scale: CGFloat) { + let requested = path.flatMap { Metrics.fromFile($0, size) } + // Attached ONCE, at the base: the trait and size copies below inherit + // the cascade, so every cut and the tagline's smaller cuts reach the + // same fallbacks. Metrics is measured from `face` too, and a cascade + // changes no metric — CoreText measures the primary face and only + // consults the chain for a codepoint it lacks. + let face = FontFallbacks.attach(to: requested ?? Metrics.defaultFace(size: size), size: size) + let scale = max(1, scale) + + // UNVERIFIED: CTFontSymbolicTraits member spelling (.traitBold/.traitItalic). + // A face with no italic cut returns nil here, hence the fallback to `face`. + func variant(_ traits: CTFontSymbolicTraits) -> CTFont { + CTFontCreateCopyWithSymbolicTraits(face, size, nil, traits, traits) ?? face + } + let faces = [face, variant(.traitBold), variant(.traitItalic), variant([.traitBold, .traitItalic])] + + // The grid has to land on WHOLE DEVICE PIXELS, and that is the whole + // constraint — a fractional column boundary makes the background pass + // (which runs with antialiasing off, or touching fills seam) wobble by + // a pixel from column to column, and on a screen made of tag bars and + // selections that stripe is visible. + // + // Whole POINTS is how that used to be spelled, and on a Retina display + // it asks for twice what it needs: half a point IS a whole pixel at 2x. + // The difference is not academic — Monaco advances 8.4014pt at 14, so + // ceiling to 9 spaced every column 7.1% wider than the face was drawn + // for, which is loose, washed-out text that reads as bad rendering. + // Snapped to the backing grid it is 8.5, i.e. +1.2%. + // + // Width rounds to NEAREST — a monospace glyph is drawn to fit its own + // advance, so the half-pixel either way is slack — while height rounds + // UP, because losing a pixel off a descender is clipping. + let snap = Metrics.snap + fonts = faces + acceptedPath = path == nil || requested != nil + // The ascent lands on a pixel for a second reason: it is the baseline's + // offset inside the cell, so the rules hung off it are whole-pixel + // fills rather than one-pixel bars smeared across two rows. + let bodyAscent = max(1 / scale, snap(CTFontGetAscent(face), scale, .toNearestOrAwayFromZero)) + let bodyWidth = max(1 / scale, snap(advance(face, 0x4D), scale, .toNearestOrAwayFromZero)) + let bodyHeight = max(1 / scale, snap(CTFontGetAscent(face) + CTFontGetDescent(face) + CTFontGetLeading(face), scale, .up)) + ascent = bodyAscent + cellWidth = bodyWidth + cellHeight = bodyHeight + ruleThickness = max(1 / scale, snap(CTFontGetUnderlineThickness(face), scale, .toNearestOrAwayFromZero)) + underlineOffset = snap(CTFontGetUnderlinePosition(face), scale, .toNearestOrAwayFromZero) + asciiGlyphs = faces.map { font in + var chars = Array(UniChar(0).. CTFont { + let system = NSFont.monospacedSystemFont(ofSize: size, weight: .regular) + // Through the descriptor, not through CTFontCreateWithName(fontName): + // the system monospace face has a dot-prefixed internal name that a + // by-name lookup can miss entirely, and NSFontDescriptor is toll-free + // bridged, so this cannot resolve to a different font than AppKit just + // handed us. + let face = CTFontCreateWithFontDescriptor(system.fontDescriptor as CTFontDescriptor, size, nil) + // The whole layout is a fixed grid, so a proportional face is not a + // cosmetic problem, it is a broken screen. "M" and "i" disagreeing on + // advance is the cheapest possible proof that we got one. + return Metrics.isFixedPitch(face) ? face : CTFontCreateWithName("Menlo" as CFString, size, nil) + } + + /// A face out of a font FILE, which is what the core hands over — it found + /// the path by walking the font directories itself, so nothing here asks + /// CoreText to resolve a name that a different shell might resolve + /// differently. + /// + /// Nil rather than a substitute for anything wrong with the file, because + /// the caller's fallback is the face already on screen: a font that cannot + /// be measured would otherwise leave a terminal with no way back out. + private static func fromFile(_ path: String, _ size: CGFloat) -> CTFont? { + let url = URL(fileURLWithPath: path) as CFURL + guard let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url) as? [CTFontDescriptor], + !descriptors.isEmpty else { return nil } + // A .ttc holds a family's four cuts in one file. Take the one with + // neither trait set — the regular — because the bold and italic ones + // are derived from it below; falling back to the first face keeps a + // collection whose cuts are all styled from being unusable. + let plain = descriptors.first { descriptor in + let traits = CTFontDescriptorCopyAttribute(descriptor, kCTFontTraitsAttribute) as? [CFString: Any] + let symbolic = (traits?[kCTFontSymbolicTrait] as? UInt32) ?? 0 + return symbolic & UInt32(CTFontSymbolicTraits.traitBold.rawValue | CTFontSymbolicTraits.traitItalic.rawValue) == 0 + } + let chosen = CTFontCreateWithFontDescriptor(plain ?? descriptors[0], size, nil) + // A variable face's descriptor carries no variation, and CoreText + // picks whichever named instance it likes for it — Maple Mono's + // variable file comes up Thin. Pin every axis to its own default: + // the face the file itself calls regular. + var face = chosen + if let axes = CTFontCopyVariationAxes(face) as? [[CFString: Any]] { + var defaults: [CFNumber: Any] = [:] + for axis in axes { + guard let tag = axis[kCTFontVariationAxisIdentifierKey], + let value = axis[kCTFontVariationAxisDefaultValueKey] else { continue } + defaults[tag as! CFNumber] = value + } + if !defaults.isEmpty { + let descriptor = CTFontDescriptorCreateCopyWithAttributes( + CTFontCopyFontDescriptor(face), + [kCTFontVariationAttribute: defaults] as CFDictionary) + face = CTFontCreateWithFontDescriptor(descriptor, size, nil) + } + } + // The core already filtered for fixed pitch by reading the file's own + // advances. This is the same question asked of the face CoreText + // actually built, which is the one that will be drawn with. + return Metrics.isFixedPitch(face) ? face : nil + } + + private static func isFixedPitch(_ face: CTFont) -> Bool { + let em = advance(face, 0x4D) + return em > 0 && abs(em - advance(face, 0x69)) <= 0.01 + } +} + +/// The independently replaceable half of font state. A TaglineSize command +/// rebuilds only this value and its non-ASCII cache; body metrics and therefore +/// the core grid never move. `height` is also the painted tag-band height, not +/// merely a smaller glyph centred inside a body-height colour bar. +private struct TaglineMetrics { + let percent: UInt8 + let fonts: [CTFont] + /// The tagline face's OWN ascent. Deliberately not folded together with the + /// band's top offset the way it used to be: that offset is per-row now, and + /// a baseline carrying one row's offset would pin every band back to centre. + let ascent: CGFloat + /// The tagline face's OWN advance, clamped to the body cell it sits in. + /// A tag row steps by THIS, not by the body cell width: the band behind it + /// is still pane-wide on the body grid, but the text on top of it tracks at + /// the smaller face's own pitch. Centring a smaller glyph inside a + /// body-width cell instead — which is what this shell used to do — leaves + /// the tag text visibly looser than the same session in an SDL window. + let width: CGFloat + let height: CGFloat + let asciiGlyphs: [[CGGlyph]] + /// Kept so the band rules below can work in the physical pixels the core + /// states them in, and hand back points. + private let scale: CGFloat + private let bodyCellHeight: CGFloat + + init(body: Metrics, percent: UInt8, scale rawScale: CGFloat) { + let scale = max(1, rawScale) + func snap(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { + (value * scale).rounded(rule) / scale + } + self.percent = percent + self.scale = scale + bodyCellHeight = body.cellHeight + let size = CTFontGetSize(body.fonts[0]) * CGFloat(percent) / 100 + let faces = body.fonts.map { CTFontCreateCopyWithAttributes($0, size, nil, nil) } + fonts = faces + let face = faces[Face.regular.rawValue] + let measuredHeight = max(1 / scale, snap( + CTFontGetAscent(face) + CTFontGetDescent(face) + CTFontGetLeading(face), .up)) + // Runtime configuration caps the percentage at the body face. Keep the + // clamp here too: a malformed/custom host value must not paint a tag + // over the body row below it. + height = min(body.cellHeight, measuredHeight) + ascent = max(1 / scale, snap(CTFontGetAscent(face), .toNearestOrAwayFromZero)) + width = min(body.cellWidth, max(1 / scale, snap(advance(face, 0x4D), .toNearestOrAwayFromZero))) + asciiGlyphs = faces.map { font in + var chars = Array(UniChar(0).. CGFloat { + CGFloat(pardes_tagline_band_offset( + UInt16(clamping: row), Float(canvasHeight * scale), cellPixels, bandPixels)) / scale + } + + /// Canonical tag cells are physical grip slots; TagLayer positions text. + func glyphX(col: Int, row: Int, bodyCellWidth: CGFloat) -> CGFloat { + // Canonical tag cells are physical grips; TagLayer owns compact text. + CGFloat(col) * bodyCellWidth + } + + /// Thickness of the rule joining the topbar band to the first pane-tag band, + /// zero when the two are meant to join directly. + var borderThickness: CGFloat { + CGFloat(pardes_topbar_pane_border_px(cellPixels, bandPixels)) / scale + } + + /// Top of that rule. Placed the way the SDL shell places it, in WHOLE + /// pixels: half the rule above the topbar/pane boundary, floored, so a + /// one-pixel rule lands on the boundary instead of smeared across two rows. + var borderTop: CGFloat { + let px = pardes_topbar_pane_border_px(cellPixels, bandPixels) + return (CGFloat(cellPixels * UInt32(PARDES_TOPBAR_H)) - CGFloat(px / 2)) / scale + } + + /// One physical pixel, in points. The rules separating discontinuous + /// context rows inside a body layer are a single pixel in the SDL shell, + /// so they are stated there and converted here rather than handing `scale` + /// out and letting the caller reinvent the conversion. + var contextBorderThickness: CGFloat { 1 / scale } +} + +private func modifiers(_ flags: NSEvent.ModifierFlags) -> UInt32 { + var mods: UInt32 = 0 + if flags.contains(.control) { mods |= UInt32(PARDES_MOD_CTRL) } + if flags.contains(.option) { mods |= UInt32(PARDES_MOD_ALT) } + if flags.contains(.shift) { mods |= UInt32(PARDES_MOD_SHIFT) } + if flags.contains(.command) { mods |= UInt32(PARDES_MOD_SUPER) } + return mods +} + +final class PardesView: NSView { + weak var delegate: PardesViewDelegate? + + // The face and the numbers off it, replaced whole by `wear`. + private var metrics: Metrics + private var taglines: TaglineMetrics + /// What `metrics` was built from, so a zoom keeps the face and a font + /// change keeps the size. + private var fontSize: CGFloat + private var fontPath: String? + + var cellWidth: CGFloat { metrics.cellWidth } + var cellHeight: CGFloat { metrics.cellHeight } + + // Glyphs the ASCII table above did not answer for. A stored 0 is .notdef, + // meaning "this face does not have it", which is a cache hit too — the + // CTLine fallback below is far more expensive than the lookup it would + // repeat. Keyed by role, face and codepoint, and thrown away with both + // body and tagline variants whenever the body face changes. + private var bodyGlyphCache: [UInt32: CGGlyph] = [:] + private var taglineGlyphCache: [UInt32: CGGlyph] = [:] + private struct GripGlyph { + let line: CTLine + let ink: CGRect + } + private var gripGlyphCache: [String: GripGlyph] = [:] + // Scratch for one batched run of glyphs. Held rather than made per row so a + // full redraw does not allocate 24 times. + private var runGlyphs: [CGGlyph] = [] + private var runPositions: [CGPoint] = [] + /// Ligature shaping, keyed by face and text. A sequence ligates when + /// shaping it produces fewer glyphs than it has characters — the only + /// answer CoreText gives without interrogating the font's own features. + /// Cleared with the glyph caches, because it belongs to one face. + private var ligatureShaped: [String: Bool] = [:] + /// Columns the current row has already consumed as part of a ligature + /// drawn further left. One row's worth at a time. + private var ligatureCovered: Set = [] + /// Constructed lazily because the ordinary path is still a direct + /// CoreText/CoreGraphics frame. No scene bit and no panel track means no + /// bitmap, no Core Image context and no Metal work. + private lazy var scenePostprocessor: ScenePostprocessor? = ScenePostprocessor() + /// Kernel compilation is permanent for one executable. Runtime allocation + /// and device failures get three consecutive attempts before this session + /// stops advertising effects its GPU path cannot present. + private var postprocessorUnavailable = false + private var postprocessRetries = 0 + /// The scene mapping of the pixels AppKit most recently accepted. Pointer + /// events use this snapshot, not a clock that may already be one tick ahead. + private var lastPresentedScene: pardes_scene_s? + /// Whether the last frame reached the optional Metal owner successfully. + /// Ordinary direct draws and a runtime-kernel failure leave this false. + private(set) var lastFrameUsedPostprocessor = false + /// Monotonic count of frames AppKit actually let this view present. The + /// host animation clock uses it as a permit: no new sample is consumed + /// while an occluded/coalesced frame is still waiting to be drawn. + private(set) var presentationSerial: UInt64 = 0 + + private var reportedCols: UInt16 = 0 + private var reportedRows: UInt16 = 0 + + /// The backingScaleFactor `metrics` was snapped to, so a move between a + /// Retina and a 1x display re-measures the cell instead of leaving the grid + /// aligned to the other screen's pixels. + private var metricsScale: CGFloat = 2 + + /// The active theme's own background, or nil when it declares none — the + /// `*_transparent` themes and the curated `dark`. Nil is not a colour to + /// substitute but a decision: the ground stops being painted at all, the + /// view stops being opaque, and AppDelegate's NSVisualEffectView shows + /// through it. Read off pardes_theme_bg() once per pump, which is also + /// what makes a `Theme` command take hold without a relaunch. + private(set) var themeBG: UInt32? = pardesDefaultBG + + /// Adopt what the core is wearing. Returns whether anything moved, so the + /// host only reconfigures the window when it has to. + @discardableResult + func adoptThemeBG(_ encoded: UInt32) -> Bool { + let wanted: UInt32? = + encoded == UInt32(PARDES_COLOR_DEFAULT) ? nil : encoded & UInt32(PARDES_COLOR_RGB_MASK) + guard wanted != themeBG else { return false } + themeBG = wanted + needsDisplay = true + return true + } + + /// What `WindowOpacity` asked for, as the alpha every BACKGROUND is painted + /// at: the ground, cell and band backgrounds, and the chrome rules over + /// them. Glyph ink is never scaled by it, and neither is the block cursor — + /// it is foreground chrome that merely happens to be carried in a cell's + /// background, and it has to stay visible at `WindowOpacity 0`. + /// + /// The rule is stated once for the SDL shell in shaders/ui.frag.glsl; this + /// is the same rule in CoreGraphics, where painting the ground at this + /// alpha and the glyph over it at its own coverage composites to what that + /// shader writes premultiplied in one pass. + /// + /// Orthogonal to `themeBG`: a theme with no background of its own drops the + /// ground whatever this says, and an opaque theme still honours it. + private(set) var backgroundAlpha: CGFloat = 1 + + /// Adopt the core's percentage. Returns whether anything moved, on the same + /// contract as adoptThemeBG: the host redresses the window only when it has. + @discardableResult + func adoptWindowOpacity(_ percent: UInt8) -> Bool { + let wanted = CGFloat(min(percent, 100)) / 100 + guard wanted != backgroundAlpha else { return false } + backgroundAlpha = wanted + needsDisplay = true + return true + } + + // The button a left-stream click actually started with. mouseDown decides + // it from the fingers on the trackpad, and mouseDragged/mouseUp must use + // the same one: a press of right followed by a release of left leaves the + // core holding a drag nothing will ever end. + private var latchedButton: pardes_mouse_button_e? + private var latchedCell: GridPoint? + /// Last physical point delivered by AppKit and its mapping through the + /// accepted scene. The CRT's barrel moves a source cell under a stationary + /// hand, so successful scene presentations reconcile this point again. + private var pointerPoint: CGPoint? + private var pointerCell: GridPoint? + private var pointerMapped = false + private var pointerModifiers: UInt32 = 0 + // Force-click stage, reset per press. AppKit repeats stage-2 events for as + // long as the finger stays down, and only the transition is the gesture. + private var pressureStage: Int = 0 + // Fingers currently resting on the trackpad, kept from the touch stream. + // + // mouseDown was originally trusted to carry its own touch set, and on this + // hardware it does not always: AppKit routes NSTouch through the four + // touchesXxx callbacks, and the touch set hanging off a *mouse* event can + // come back empty depending on how the click was produced. Empty reads as + // one finger, which is a two-finger Exec silently degrading into a select + // — the exact failure this was supposed to avoid. So the count is + // maintained here and the mouse event's own set is preferred only when it + // has something in it. + private var restingFingers: Int = 0 + + init(fontSize size: CGFloat) { + // No window yet, so no backing scale to ask for: 2x is the guess every + // Mac shipped this decade would give, and viewDidChangeBackingProperties + // below re-measures the moment there is a real answer — including the + // 1x case, which a bare guess would otherwise leave wrong forever. + let built = Metrics(size: size, path: nil, scale: 2) + metrics = built + taglines = TaglineMetrics( + body: built, percent: pardes_gui_tagline_font_percent(), scale: 2) + fontSize = size + fontPath = nil + + // 80x24 only so the window has a size to open at; the AppDelegate reads + // gridSize back and boots the core with whatever it actually got. + super.init(frame: NSRect(x: 0, y: 0, width: built.cellWidth * 80, height: built.cellHeight * 24)) + + runGlyphs.reserveCapacity(256) + runPositions.reserveCapacity(256) + // Files dropped ON the grid. Finder and the Dock already reach the app + // through application(_:open:), but that path cannot say WHERE — and + // where is the whole difference between "a file opened somewhere" and + // acme's "a file opened next to the pane I pointed at". + registerForDraggedTypes([.fileURL]) + // Indirect touches are the trackpad's. Without this the touch set is + // always empty and every click looks like one finger, which is exactly + // the bug that would make two-finger Exec silently never fire. + allowedTouchTypes = [.indirect] + // Without a pressure configuration the deep-press stages are the + // system's business and stage 2 may never be delivered here. + // .primaryDeepClick is the one that means "a harder press is a second + // gesture", which is what it is being used for. + pressureConfiguration = NSPressureConfiguration(pressureBehavior: .primaryDeepClick) + } + + required init?(coder: NSCoder) { fatalError("PardesView is built in code, not a nib") } + + // MARK: - the face + + /// The PostScript name of the face on screen. The only way anything + /// outside this file can find out which font is being drawn with — the + /// core has no font, so a cell-buffer snapshot cannot see one. + var faceName: String { CTFontCopyPostScriptName(metrics.fonts[0]) as String } + var effectivePointSize: CGFloat { CTFontGetSize(metrics.fonts[0]) } + + /// Put on a face, or the same face at a different size, and tell the host + /// the grid moved under it. + /// + /// A cell that changed size means a different number of columns fit the + /// same window, so this is a resize as far as the core is concerned — and + /// the delegate's resize path is already the one that reports both the + /// grid and the physical cell the PDF placement reads. A requested file + /// which cannot produce a fixed-pitch face is rejected before assignment, + /// leaving the screen exactly as it was rather than substituting a face. + private func wear(size: CGFloat, path: String?, resolvesRequest: Bool = false) { + let scale = window?.backingScaleFactor ?? metricsScale + let next = Metrics(size: size, path: path, scale: scale) + guard next.acceptedPath else { + // The requested file never became the fixed-pitch face the grid + // requires. Keep every old metric and resolve the pending request + // as rejected rather than claiming the system fallback is it. + if resolvesRequest { pardes_font_reject() } + return + } + // A CGGlyph is an index into a particular face. Kept across a change + // it would draw a different character, not a missing one. + bodyGlyphCache.removeAll(keepingCapacity: true) + taglineGlyphCache.removeAll(keepingCapacity: true) + gripGlyphCache.removeAll(keepingCapacity: true) + ligatureShaped.removeAll(keepingCapacity: true) + metrics = next + taglines = TaglineMetrics(body: next, percent: taglines.percent, scale: scale) + metricsScale = scale + fontSize = size + fontPath = path + delegate?.pardesViewDidResize(self) + needsDisplay = true + reportEffectiveFont(resolvesRequest: resolvesRequest) + } + + /// Apply the core's live TaglineSize setting without touching body metrics, + /// the window grid, or PDF cell geometry. Called every pump; equality makes + /// the ordinary path one byte comparison. + @discardableResult + func adoptTaglinePercent(_ percent: UInt8) -> Bool { + guard percent != taglines.percent else { return false } + taglines = TaglineMetrics(body: metrics, percent: percent, scale: metricsScale) + taglineGlyphCache.removeAll(keepingCapacity: true) + gripGlyphCache.removeAll(keepingCapacity: true) + pardes_row_metrics(UInt16(max(1,(cellWidth*metricsScale).rounded())),UInt16(max(1,(cellHeight*metricsScale).rounded())), + UInt16(max(1,(taglines.width*metricsScale).rounded())),UInt16(max(1,(taglines.height*metricsScale).rounded()))) + needsDisplay = true + return true + } + + var taglinePercent: UInt8 { taglines.percent } + var taglineBandHeight: CGFloat { taglines.height } + var taglineCellWidth: CGFloat { taglines.width } + + /// Seed runtime Config after init and update it after every successful + /// adopt/zoom. Points are the native owner's unit; the cell's backing-pixel + /// dimensions continue to travel through pardes_resize separately. + func reportEffectiveFont(resolvesRequest: Bool = false) { + let hundredths = UInt16(min( + max((effectivePointSize * 100).rounded(), 1), + CGFloat(UInt16.max))) + let name = faceName + name.withCString { pointer in + if resolvesRequest { + _ = pardes_font_ack(pointer, name.utf8.count, hundredths) + } else { + _ = pardes_font_observe(pointer, name.utf8.count, hundredths) + } + } + } + + /// The file `Font ` resolved to, straight from the core. + func adoptFont(path: String, sizeHundredths: UInt16) { + let size = sizeHundredths == 0 ? fontSize : CGFloat(sizeHundredths) / 100 + wear(size: size, path: path, resolvesRequest: true) + } + + /// Cmd+ and Cmd-. Whole points, because the cell is rounded to whole + /// points anyway: a tenth-of-a-point step would spend several keystrokes + /// landing on the same grid and look like the key had stopped working. + /// The range is what stays legible at the bottom and still fits a useful + /// number of columns at the top. + func zoom(by step: CGFloat) { + let next = min(max(fontSize + step, 6), 72) + guard next != fontSize else { return } + wear(size: next, path: fontPath) + } + + func zoomReset() { + guard fontSize != defaultFontSize else { return } + wear(size: defaultFontSize, path: fontPath) + } + + // Row 0 at the top, so the drawing arithmetic reads like the grid it is. + override var isFlipped: Bool { true } + // Opaque only while the theme brings its own background AND that background + // is painted solid. A transparent theme has none, and an opaque view over a + // visual-effect backdrop is a grey rectangle where the blur should be; + // a WindowOpacity below 100 has the same problem against the desktop. + override var isOpaque: Bool { themeBG != nil && backgroundAlpha >= 1 } + override var acceptsFirstResponder: Bool { true } + // A click that focuses the window should also land in the grid: this is a + // text surface, and having to click twice after switching apps is the kind + // of thing that makes an app feel foreign. + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + var gridSize: (cols: UInt16, rows: UInt16) { + let cols = min(max((bounds.width / cellWidth).rounded(.down), 1), CGFloat(UInt16.max)) + let rows = min(max((bounds.height / cellHeight).rounded(.down), 1), CGFloat(UInt16.max)) + return (UInt16(cols), UInt16(rows)) + } + + // MARK: - drawing + + override func draw(_ dirtyRect: NSRect) { + guard let destination = NSGraphicsContext.current?.cgContext else { return } + lastFrameUsedPostprocessor = false + // ponytail: dirtyRect is ignored. pardes_frame() re-renders the whole grid + // whatever we do, so clipping would save fills and nothing else. Narrow + // the row loops to the dirty band if that ever shows up in a profile. + let count = pardes_frame() + let nextPointer = pointerShape() + if nextPointer != pointer { + pointer = nextPointer + window?.invalidateCursorRects(for: self) + if let window, bounds.contains(convert(window.mouseLocationOutsideOfEventStream, from: nil)) { + cursorFor(pointer).set() + } + } + let scene = pardes_scene() + let trackCount = Int(pardes_frame_panel_tracks()) + let tracks: UnsafeBufferPointer + if trackCount > 0, let list = pardes_frame_panel_track_list() { + tracks = UnsafeBufferPointer(start: list, count: trackCount) + } else { + tracks = UnsafeBufferPointer(start: nil, count: 0) + } + let wantsPostprocess = scene.flags != 0 || !tracks.isEmpty + if wantsPostprocess { + if postprocessorUnavailable { + pardes_postprocessor_unavailable() + } else if let postprocessor = scenePostprocessor { + if let sceneContext = postprocessor.renderContext( + size: bounds.size, scale: window?.backingScaleFactor ?? metricsScale + ) { + drawFrame(sceneContext, count: count, hideCursor: !tracks.isEmpty) + let needsPrevious = tracks.contains { + $0.effect == UInt8(PARDES_PANEL_DISSOLVE) + || $0.effect == UInt8(PARDES_PANEL_VERTICAL) + } + var oldReady = !needsPrevious + let previousCells = pardes_frame_previous_cells() + let changedCells = pardes_frame_changed_cells() + if needsPrevious, let previousCells, changedCells != nil, + let oldContext = postprocessor.previousRenderContext( + size: bounds.size, + scale: window?.backingScaleFactor ?? metricsScale + ) { + drawFrame( + oldContext, count: count, cells: previousCells, + frozenImages: presentedImages, hideCursor: true) + oldReady = true + } + let outcome: ScenePostprocessor.CompositeOutcome = oldReady + ? postprocessor.composite( + scene: scene, tracks: tracks, + changedCells: changedCells, + changedAttachmentRects: changedAttachmentRects(), + gridSize: ( + cols: Int(pardes_frame_cols()), + rows: Int(pardes_frame_rows())), + cellSize: CGSize(width: cellWidth, height: cellHeight), + ground: themeBG, size: bounds.size, into: destination) + : .unavailable + switch outcome { + case .presented: + postprocessRetries = 0 + lastPresentedScene = scene + lastFrameUsedPostprocessor = true + acknowledgePresentation(animatedPanels: !tracks.isEmpty) + return + case .retry: + postprocessRetries += 1 + case .unavailable: + postprocessorUnavailable = true + } + } else { + postprocessRetries += 1 + } + // This draw now falls back to canonical content. Scene effects + // may retry, but a panel must not resume from a later sample + // after its final geometry has already been shown. + if !tracks.isEmpty { pardes_panel_animation_failed() } + if postprocessRetries >= 3 { postprocessorUnavailable = true } + if postprocessorUnavailable { pardes_postprocessor_unavailable() } + } else { + // The source, Metal device, or fixed kernel set was absent at + // lazy construction. None can recover within this process. + postprocessorUnavailable = true + pardes_postprocessor_unavailable() + } + } else { + postprocessRetries = 0 + } + lastPresentedScene = nil + drawFrame(destination, count: count, hideCursor: false) + acknowledgePresentation(animatedPanels: false) + } + + /// A presentation can materialize a Look target under a stationary mouse + /// after AppDelegate already decided whether to run its 60 Hz clock. Wake + /// the ordinary pump only for that null->active edge; repeated frame acks + /// remain inert and cannot create a redraw loop. + private func acknowledgePresentation(animatedPanels: Bool) { + // Only a canonical presentation advances the attachment baseline. + // During a transition deleted panes keep their cropped CGImages alive + // here even after both the core placement and image cache entry vanish. + if !animatedPanels { + presentedImages = frameImages + presentedBodyLayers = snapshotBodyLayers() + presentedTagLayers = snapshotTagLayers() + } + presentationSerial &+= 1 + let animationWoke = pardes_frame_presented(animatedPanels) + let pointerMoved = refreshPresentedPointer() + guard animationWoke || pointerMoved else { return } + DispatchQueue.main.async { + NotificationCenter.default.post(name: pardesDidInputNotification, object: self) + } + } + + /// Re-feed only a changed mapping. Sending motion on every 60 Hz scene + /// frame would keep resetting the core's hover debounce forever. + private func refreshPresentedPointer() -> Bool { + guard let point = pointerPoint else { return false } + guard let at = cellAt(point) else { + guard pointerMapped else { return false } + pointerMapped = false + pardes_pointer_leave() + return true + } + let changed: Bool + if let previous = pointerCell { + changed = !pointerMapped || previous.col != at.col || previous.row != at.row + } else { + changed = true + } + pointerMapped = true + pointerCell = at + guard changed else { return false } + if let button = latchedButton { + latchedCell = at + sendMouse(button, PARDES_MOUSE_DRAG, at.col, at.row, pointerModifiers) + } else { + sendMouse(PARDES_MOUSE_NONE, PARDES_MOUSE_MOTION, + at.col, at.row, pointerModifiers) + } + return true + } + + /// The canonical CoreText frame, independent of where it lands. Scene + /// effects change only the destination: direct view context when off, the + /// postprocessor's same-sized retained bitmap when on. + private func drawFrame( + _ ctx: CGContext, + count: UInt32, + cells suppliedCells: UnsafePointer? = nil, + frozenImages: [FrozenImage]? = nil, + hideCursor: Bool + ) { + let cols = Int(pardes_frame_cols()) + let rows = Int(pardes_frame_rows()) + // The ground, from the core rather than from a constant agreed by hand. + // A transparent theme has none: CLEAR rather than fill, because AppKit + // does not blank a non-opaque view and last frame's pixels would + // otherwise pile up on themselves. + let ground = themeBG ?? pardesDefaultBG + let clearGround = themeBG == nil + // AppKit does not blank a non-opaque view, so anything that leaves the + // ground short of solid has to clear first or last frame's pixels pile + // up on themselves — a translucent ground would darken toward opaque + // over a few frames otherwise. + if clearGround || backgroundAlpha < 1 { ctx.clear(bounds) } + if !clearGround { fillBackground(ctx, bounds, ground, backgroundAlpha) } + if frozenImages == nil { frameImages.removeAll(keepingCapacity: true) } + guard cols > 0, rows > 0, Int(count) == cols * rows, + let cells = suppliedCells ?? pardes_frame_cells() + else { return } + + // -1 when hidden, which never matches a real cell, so hidden and "bar, so + // not a block" collapse into the same comparison. + // A cursor has no pane/phase record. Match SDL and TTY by hiding it for + // the short panel transition instead of guessing whether it should + // move, stay fixed, or cover an overlapping opening pane. + let bar = !hideCursor && pardes_cursor_bar() + let blockX = hideCursor || bar ? -1 : Int(pardes_cursor_x()) + let blockY = hideCursor || bar ? -1 : Int(pardes_cursor_y()) + + // Background first, batched into runs of equal color. A full redraw is + // 80x24 cells at the low end and per-cell fills are exactly what makes + // that feel slow. Antialiasing is off because touching rects share an + // edge, and blending that edge twice draws a visible seam. + ctx.setShouldAntialias(false) + // Band geometry is stated against the whole canvas: the last row's rule + // depends on where the window edge is, not just on the row index. + let canvasHeight = bounds.height + for row in 0.. 0 { + let base = (rows - 1) * cols + for col in 0..() + if frozenImages == nil { + for index in 0..= 0 && x < cols && y >= 0 && y < rows { paneGripCells.insert(y * cols + x) } + } + } else { + for layer in presentedTagLayers where layer.values[1] == 2 { + let x = layer.values[4] - Int(pardes_tag_text_inset()), y = layer.values[5] + if x >= 0 && x < cols && y >= 0 && y < rows { paneGripCells.insert(y * cols + x) } + } + } + for row in 0..= 0, y >= 0, x < cols, y < rows { + // gui.zig paints U+258F here. A rect is the same picture without + // asking the font for a glyph it may not carry. + let cell = cells[y * cols + x] + let fg = resolve(cell, block: false, + ground: themeBG ?? pardesDefaultBG, clearGround: false).fg + let tagline = cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 + let caretY = CGFloat(y) * cellHeight + + (tagline ? taglines.top(row: y, canvasHeight: bounds.height) : 0) + let caretHeight = tagline ? taglines.height : cellHeight + // On the compact grid when the cell is, or the caret sits a + // growing distance to the left of the character it marks as the + // row runs on. The SDL shell puts its cursor bar through the + // same layout for the same reason. + let caretX = tagline + ? taglines.glyphX(col: x, row: y, bodyCellWidth: cellWidth) + : CGFloat(x) * cellWidth + let caretWidth = max(1, ((tagline ? taglines.width : cellWidth) / 8).rounded(.up)) + ctx.setShouldAntialias(false) + fill(ctx, CGRect(x: caretX, y: caretY, + width: caretWidth, height: caretHeight), fg, 1) + } + } + if frozenImages == nil { + drawBodyLayers(ctx, hideCursor:hideCursor) + drawTagLayers(ctx, hideCursor:hideCursor, canonical:cells, cols:cols, rows:rows) + } else { + for layer in presentedTagLayers { + layer.cells.withUnsafeBufferPointer { tagCells in + if let base = tagCells.baseAddress { + drawTagLayer(ctx, values: layer.values, cells: base, hideCursor: true, + canonical: cells, cols: cols) + } + } + drawTagGrip(ctx, values: layer.values, canonical: cells, cols: cols, rows: rows) + } + for layer in presentedBodyLayers { + layer.cells.withUnsafeBufferPointer { cells in + if let base = cells.baseAddress { drawBodyLayer(ctx, values:layer.values, cells:base, hideCursor:true) } + } + } + drawTagRules(ctx, layers: presentedTagLayers.map { $0.values }) + } + drawHoverGlass(ctx, cells: cells, cols: cols, rows: rows) + } + + private var presentedTagLayers: [FrozenBodyLayer] = [] + + private func snapshotTagLayers() -> [FrozenBodyLayer] { + var result: [FrozenBodyLayer] = [] + for index in 0.., cols: Int, rows: Int) { + var layers: [[Int]] = [] + for index in 0.. 0 { + fillBackground(ctx, CGRect(x: 0, y: taglines.borderTop, width: bounds.width, + height: taglines.borderThickness), + pardes_topbar_pane_border_rgb(), backgroundAlpha) + } + } + + private func gripGlyph(_ text: String, face: Face) -> GripGlyph? { + let key = "\(face.rawValue):\(text)" + if let cached = gripGlyphCache[key] { return cached } + let attributed = NSAttributedString(string: text, attributes: [fontAttribute: taglines.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + let line = CTLineCreateWithAttributedString(attributed as CFAttributedString) + let ink = CTLineGetBoundsWithOptions(line, [.useGlyphPathBounds]) + guard !ink.isNull, !ink.isInfinite, !ink.isEmpty else { return nil } + let measured = GripGlyph(line: line, ink: ink) + gripGlyphCache[key] = measured + return measured + } + + private func drawTagGrip(_ ctx: CGContext, values: [Int], canonical: UnsafePointer, cols: Int, rows: Int) { + let x = values[4] - Int(pardes_tag_text_inset()), y = values[5] + if values[1] != 2 || x < 0 || x >= cols || y < 0 || y >= rows { return } + var cell = canonical[y * cols + x] + let text = withUnsafeBytes(of: &cell.text) { String(decoding: $0.prefix(Int(cell.len)), as: UTF8.self) } + if text.isEmpty { return } + let style = resolve(cell, block:false, ground:themeBG ?? pardesDefaultBG, clearGround:false) + // The box drawTagLayer filled is this mark's ground, so the mark + // centres on that same square rather than on the grip columns: one + // rect measures both and the two cannot drift apart. + guard let square = anchorSquare(values: values) else { return } + let centerX = square.midX, centerY = square.midY + if text != " " { + let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) + guard style.visible, let measured = gripGlyph(text, face: face) else { return } + let originX = ((centerX - measured.ink.midX) * metricsScale).rounded() / metricsScale + let baseline = ((bounds.height - centerY - measured.ink.midY) * metricsScale).rounded() / metricsScale + ctx.saveGState() + ctx.clip(to: square) + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + ctx.textMatrix = .identity + ctx.textPosition = CGPoint(x: originX, y: baseline) + setFill(ctx, style.fg, style.alpha) + CTLineDraw(measured.line, ctx) + ctx.restoreGState() + return + } + if taglines.height < 6 || taglines.width < 3 { return } + let halfWidth = max(1, min(3, cellWidth - 2)) + fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY-2), width:2*halfWidth, height:1), style.fg, 1) + fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY+1), width:2*halfWidth, height:1), style.fg, 1) + } + + private func drawTagLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer, + hideCursor: Bool, canonical: UnsafePointer, cols: Int) { + let left = CGFloat(values[4]) * cellWidth + let y = CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height) + // SDL gives the tag a full body-row background; only its glyphs + // and per-cell highlights use the compact band. The band spans the + // row's whole extent, not just its text: the grip and the mode box + // live in the inset columns to the left of `values[4]`, and their + // own fills cover only the compact band — a row background that + // stops at the text leaves holes of ground under those anchors. + // The rule in drawTagRules spans exactly this left-to-right range. + let rowLeft = CGFloat(max(0, values[4] - Int(pardes_tag_text_inset()))) * cellWidth + let rowRight = CGFloat(values[4] + values[6]) * cellWidth + let viewport = CGRect(x: rowLeft, y: CGFloat(values[5]) * cellHeight, + width: rowRight - rowLeft, height: cellHeight) + ctx.saveGState() + ctx.clip(to: viewport) + fillBackground(ctx, viewport, UInt32(values[10]), backgroundAlpha) + // The anchor (grip, mode box) lives in the inset columns that fill + // just covered, so its own box goes back on top: one solid fill in + // the box colour the anchor cell wears, with drawTagGrip's mark + // drawn over it afterwards. + if let square = anchorSquare(values: values) { + let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) + let cell = canonical[values[5] * cols + anchorX] + let style = resolve(cell, block: false, + ground: UInt32(values[10]), clearGround: false) + if style.visible { fillBackground(ctx, square.integral, style.bg, backgroundAlpha) } + } + + for pass in 0...1 { + for col in 0.. CGRect? { + let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) + guard anchorX < values[4] else { return nil } + let pad = (cellHeight - taglines.height) / 2 + return CGRect(x: CGFloat(anchorX) * cellWidth + pad, + y: CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height), + width: taglines.height, height: taglines.height) + } + + /// The look-hover affordance as liquid glass: the core marks the word's + /// cells (PARDES_CELL_HOVER), and this composes a real material over the + /// run — the drawn frame snapshot refracted through CoreImage (a small + /// blur, then a lens scale about the pill's centre, which is what makes + /// the edges swim), the theme's selection colour as a faint tint, a + /// specular sheen from the top edge, and a light rim — with the word's + /// own glyphs drawn back on top, crisp, the way text sits on a real + /// material rather than behind one. + private func drawHoverGlass(_ ctx: CGContext, cells: UnsafePointer, cols: Int, rows: Int) { + var drew = false + for row in 0..= 0 { + let rect = CGRect(x: CGFloat(start) * cellWidth, y: CGFloat(row) * cellHeight, + width: CGFloat(col - start) * cellWidth, height: cellHeight) + drawLiquidGlass(ctx, rect, tint: tint) + redrawHoverRun(ctx, cells, cols: cols, row: row, start: start, end: col) + drew = true + start = -1 + } + } + } + // No affordance this frame: the held snapshot describes a frame + // that no longer exists, and the next hover must take a fresh one. + if !drew { glassShot = nil } + } + + /// A CoreImage context for the glass refraction, created once. + private lazy var glassContext = CIContext() + /// The snapshot behind the current pill. Refraction reads the already + /// drawn frame, and re-reading it every pump would blur a moving pill + /// out of its own budget, so the shot is taken when the rect changes. + private var glassShot: (rect: CGRect, image: CGImage)? + + private func drawLiquidGlass(_ ctx: CGContext, _ rect: CGRect, tint: UInt32) { + let radius = min(rect.height / 4, 6) + let pill = CGPath(roundedRect: rect.insetBy(dx: 1, dy: 1.5), + cornerWidth: radius, cornerHeight: radius, transform: nil) + // The refraction: the frame as drawn, blurred a little and scaled + // about the pill's centre, so the rim bends what surrounds it. The + // shot extends past the pill for exactly this — the lens needs + // pixels from outside the glass to pull in. + let lens = rect.insetBy(dx: -10, dy: -10) + if refract(ctx, pill: pill, rect: rect, lens: lens, tint: tint) { + // Specular: light caught at the top edge, fading as it falls. + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + let shine = [CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.22), + CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.0)] as CFArray + if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), + colors: shine, locations: [0, 0.55]) { + ctx.drawLinearGradient(gradient, + start: CGPoint(x: rect.minX, y: rect.minY), + end: CGPoint(x: rect.minX, y: rect.maxY), options: []) + } + ctx.restoreGState() + } else { + // No refraction without a snapshot: the tint alone, faint. + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, + green: CGFloat((tint >> 8) & 0xFF) / 255, + blue: CGFloat(tint & 0xFF) / 255, + alpha: 0.18)) + ctx.fill(rect) + ctx.restoreGState() + } + // The lens edge: a light rim and a darker bottom hairline, the way a + // real material catches its own edge. + ctx.addPath(pill) + ctx.setStrokeColor(CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.35)) + ctx.setLineWidth(1) + ctx.strokePath() + ctx.addPath(pill) + ctx.setStrokeColor(CGColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.25)) + ctx.setLineWidth(0.5) + ctx.clip() + ctx.stroke(CGRect(x: rect.minX, y: rect.maxY - 2, width: rect.width, height: 1.5)) + } + + /// True when the refraction composited. The snapshot is taken when the + /// pill moves and reused while it sits still. + private func refract(_ ctx: CGContext, pill: CGPath, rect: CGRect, lens: CGRect, tint: UInt32) -> Bool { + guard let shot = snapshotFor(ctx, lens: lens) else { return false } + var image = CIImage(cgImage: shot) + // The blur is grown slightly past the crop and the whole thing is + // pulled toward the centre by a few percent: the rim bends what + // surrounds it, which is the refraction the eye reads as glass. + let blur = image.applyingGaussianBlur(sigma: 2 * metricsScale) + let grown = blur.extent.insetBy(dx: -8 * metricsScale, dy: -8 * metricsScale) + let centre = CGPoint(x: grown.midX, y: grown.midY) + let scale = 1.06 + let lensTransform = CGAffineTransform(translationX: centre.x * (1 - scale), + y: centre.y * (1 - scale)).scaledBy(x: scale, y: scale) + image = blur.transformed(by: lensTransform) + guard let filtered = glassContext.createCGImage(image, from: grown) else { return false } + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + ctx.draw(filtered, in: rect) + // The glass's own body colour: the theme's selection, faint — the + // refraction and the sheen carry the material, not opacity. + ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, + green: CGFloat((tint >> 8) & 0xFF) / 255, + blue: CGFloat(tint & 0xFF) / 255, + alpha: 0.15)) + ctx.fill(rect) + ctx.restoreGState() + return true + } + + private func snapshotFor(_ ctx: CGContext, lens: CGRect) -> CGImage? { + if let held = glassShot, held.rect == lens { return held.image } + guard let whole = ctx.makeImage() else { return nil } + // makeImage hands back backing pixels; the lens is in view points. + let region = CGRect(x: lens.minX * metricsScale, y: lens.minY * metricsScale, + width: lens.width * metricsScale, height: lens.height * metricsScale) + guard let cropped = whole.cropping(to: region) else { return nil } + glassShot = (lens, cropped) + return cropped + } + + /// The hovered word's glyphs, back on top of the material, crisp: text + /// sits on liquid glass, not behind it. + private func redrawHoverRun(_ ctx: CGContext, _ cells: UnsafePointer, + cols: Int, row: Int, start: Int, end: Int) { + ctx.saveGState() + ctx.textMatrix = .identity + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + let baseline = bounds.height - (CGFloat(row) * cellHeight + metrics.ascent) + for col in start.. [FrozenBodyLayer] { + var result: [FrozenBodyLayer] = [] + for index in 0.., hideCursor: Bool) { + func value(_ field: Int) -> Int { values[field] } + let rows = value(0), cols = value(1), contexts = value(2) + let left = CGFloat(value(3)) * cellWidth, top = CGFloat(value(4)) * cellHeight + let viewport = CGRect(x: left, y: top, width: CGFloat(value(5))*cellWidth, + height: CGFloat(value(6))*cellHeight) + ctx.saveGState() + ctx.clip(to: viewport) + fillBackground(ctx, viewport, themeBG ?? bgClear, backgroundAlpha) + for row in 0..= viewport.maxY { break } + let rowStyle = resolve(cells[row*cols], block: false, ground: themeBG ?? pardesDefaultBG, clearGround: themeBG == nil) + fillBackground(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, backgroundAlpha) + for pass in 0...1 { + for col in 0.. 0, let list = pardes_frame_image_list() else { + // Nothing on screen owns pixels any more: the pages a closed pane + // rendered would otherwise sit in here for the rest of the session. + if !imageCache.isEmpty { imageCache.removeAll(keepingCapacity: true) } + return + } + + // The core computed every rectangle in PHYSICAL pixels, because that is + // what pardes_resize handed it. The view draws in points. + let scale = max(1, metricsScale) + var live = Set() + live.reserveCapacity(count) + + ctx.setShouldAntialias(true) + for i in 0.. live.count { + imageCache = imageCache.filter { live.contains($0.key) } + } + } + + private func drawFrozenImages(_ ctx: CGContext, _ images: [FrozenImage]) { + ctx.setShouldAntialias(true) + for image in images { drawFrozenImage(ctx, image) } + } + + /// Native attachments do not occupy Cell graphemes, so the core's semantic + /// text/style mask cannot see a page appearing, disappearing, rerasterizing + /// or moving. Add only those changed placements to the shader mask; an + /// identical key and geometry remains immediate like any unchanged cell. + private func changedAttachmentRects() -> [CGRect] { + var oldByKey: [ImageKey: FrozenImage] = [:] + for image in presentedImages { oldByKey[image.key] = image } + var changed: [CGRect] = [] + changed.reserveCapacity(frameImages.count + presentedImages.count) + for image in frameImages { + guard let old = oldByKey.removeValue(forKey: image.key) else { + changed.append(image.destination.intersection(image.body)) + continue + } + if old.source != image.source + || old.body != image.body || old.destination != image.destination { + changed.append(old.destination.intersection(old.body)) + changed.append(image.destination.intersection(image.body)) + } + } + for old in oldByKey.values { + changed.append(old.destination.intersection(old.body)) + } + return changed.filter { !$0.isNull && !$0.isEmpty } + } + + private func drawFrozenImage(_ ctx: CGContext, _ placed: FrozenImage) { + ctx.saveGState() + ctx.clip(to: placed.body) + // isFlipped gives us a y-down CTM and CGImage draws +y up, so flip + // about this destination rather than changing the grid arithmetic. + let isPDF = placed.paperBG != UInt32(PARDES_COLOR_DEFAULT) + if isPDF { + fillBackground(ctx, placed.destination, placed.paperBG, backgroundAlpha) + } + ctx.translateBy(x: placed.destination.minX, y: placed.destination.maxY) + ctx.scaleBy(x: 1, y: -1) + ctx.interpolationQuality = .high + let rect = CGRect(x: 0, y: 0, + width: placed.destination.width, height: placed.destination.height) + if isPDF { + // Paper was painted at WindowOpacity. Content keeps the PDF's own + // coverage, so glyphs, photos and paths stay legible at zero opacity. + ctx.setAlpha(1) + ctx.setBlendMode(.normal) + ctx.draw(placed.image, in: rect) + ctx.restoreGState() + return + } + // Match image.frag.glsl/backgroundLayerBlend: source coverage removes + // the destination independently of WindowOpacity, then the source is + // added at that opacity. Ordinary source-over would compound alpha; + // copy would discard the background under transparent image pixels. + ctx.setAlpha(1) + ctx.setBlendMode(.destinationOut) + ctx.draw(placed.image, in: rect) + ctx.setAlpha(backgroundAlpha) + ctx.setBlendMode(.plusLighter) + ctx.draw(placed.image, in: rect) + ctx.restoreGState() + } + + /// The decoded raster for one attachment, made once per generation. + private func image(for place: pardes_image_s, key: ImageKey) -> CGImage? { + if let cached = imageCache[key] { return cached } + let bytes = Int(place.iw) * Int(place.ih) * 4 + guard bytes > 0, let rgba = place.rgba else { return nil } + // Copied, not referenced: the core lends these bytes until the next + // pardes_frame and this image outlives many of them. + guard let data = CFDataCreate(nil, rgba, bytes), + let provider = CGDataProvider(data: data) + else { return nil } + // Straight alpha, R,G,B,A in memory — the same bytes the SDL shell + // uploads as R8G8B8A8_UNORM and blends with ONE_MINUS_SRC_ALPHA. + let made = CGImage( + width: Int(place.iw), height: Int(place.ih), + bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(place.iw) * 4, + space: sRGB, + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue | CGBitmapInfo.byteOrder32Big.rawValue), + provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) + if let made { imageCache[key] = made } + return made + } + + /// One row of glyphs, batched. Consecutive cells that share a face and a + /// colour go to CoreText as a single call with a position array: a row of + /// plain text is then one draw instead of eighty, which is the difference + /// between a full redraw being free and being felt. + private func drawRow( + _ ctx: CGContext, + _ cells: UnsafePointer, + base: Int, + cols: Int, + /// This row's grid index. Needed per cell rather than per row for the + /// compact tagline anchor: a column split puts two panes' tags side by + /// side on ONE row, so the origin is a question about the cell. + row: Int, + baseline: CGFloat, + /// Where this row's tagline band starts, from the row's top. Passed in + /// rather than recomputed per cell: it is one answer per row, and the + /// glyph has to sit in the band the background pass painted. + taglineTop: CGFloat, + blockCol: Int, + paneGripCells: Set + ) { + var runFace = Face.regular + var runTagline = false + var runColor: UInt32 = 0 + var runAlpha: CGFloat = 1 + runGlyphs.removeAll(keepingCapacity: true) + runPositions.removeAll(keepingCapacity: true) + ligatureCovered.removeAll(keepingCapacity: true) + + func flush() { + guard !runGlyphs.isEmpty else { return } + setFill(ctx, runColor, runAlpha) + let font = runTagline + ? taglines.fonts[runFace.rawValue] + : metrics.fonts[runFace.rawValue] + CTFontDrawGlyphs(font, runGlyphs, runPositions, runGlyphs.count, ctx) + runGlyphs.removeAll(keepingCapacity: true) + runPositions.removeAll(keepingCapacity: true) + } + + for col in 0..> UInt16(PARDES_ATTR_UL_SHIFT) != 0 + || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { + flush() + drawRules(ctx, cell, style, x: x, width: advanceWidth, baseline: cellBaseline) + } + guard style.visible else { continue } + + // UNVERIFIED: withUnsafeBytes over an imported C fixed-size array, which + // Swift models as an 8-tuple. String(decoding:) substitutes U+FFFD rather + // than trapping, and the core has shipped invalid UTF-8 through here + // before — the renderer must not be the thing that dies over it. prefix + // clamps, so a bogus len cannot walk off the eight bytes either. + let text = withUnsafeBytes(of: cell.text) { raw in + String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) + } + guard !text.isEmpty, text != " " else { continue } + + let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) + if paneGripCells.contains(base + col) && gripGlyph(text, face: face) != nil { + // The layer pass centers this symbol by its actual ink bounds. + continue + } + let units = text.utf16 + let known = units.count == 1 ? glyph(face, units.first!, tagline: tagline) : 0 + if known != 0 { + // Ligatures: consecutive cells shaped together when the face + // collapses them into fewer glyphs. A monospace coding + // ligature advances by the same whole cells its characters + // did, so the grid cannot drift and only the ink changes. + if !tagline, let ligature = ligatureSpan(cells, base: base, cols: cols, col: col, + face: face, fg: style.fg, alpha: style.alpha, + blockCol: blockCol, paneGripCells: paneGripCells) { + flush() + setFill(ctx, style.fg, style.alpha) + let attributed = NSAttributedString(string: ligature.text, + attributes: [fontAttribute: metrics.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + ctx.textPosition = CGPoint(x: x, y: cellBaseline) + CTLineDraw(CTLineCreateWithAttributedString(attributed as CFAttributedString), ctx) + ctx.textMatrix = .identity + for covered in 1.. CGGlyph { + if character < 128 { + let ascii = tagline ? taglines.asciiGlyphs : metrics.asciiGlyphs + return ascii[face.rawValue][Int(character)] + } + let key = UInt32(face.rawValue) << 16 | UInt32(character) + if tagline, let cached = taglineGlyphCache[key] { return cached } + if !tagline, let cached = bodyGlyphCache[key] { return cached } + var input = character + var found = CGGlyph(0) + let font = tagline ? taglines.fonts[face.rawValue] : metrics.fonts[face.rawValue] + _ = CTFontGetGlyphsForCharacters(font, &input, &found, 1) + if tagline { + taglineGlyphCache[key] = found + } else { + bodyGlyphCache[key] = found + } + return found + } + + /// Ligature-prone character heads: a coding ligature always begins with + /// one of these, and refusing everything else keeps the per-frame cost of + /// ligature detection a set lookup rather than a shape. + private static let ligatureHeads: Set = [ + "<", ">", "=", "!", "&", "|", "-", "/", ":", ".", "#", "*", "+", "~", "^", "%", + ] + + private func ligates(_ face: Face, _ text: String) -> Bool { + let key = "\(face.rawValue):\(text)" + if let cached = ligatureShaped[key] { return cached } + let attributed = NSAttributedString(string: text, attributes: [fontAttribute: metrics.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + let shaped = CTLineCreateWithAttributedString(attributed as CFAttributedString) + var glyphs: [CGGlyph] = [] + for run in (CTLineGetGlyphRuns(shaped) as? [CTRun]) ?? [] { + let count = CTRunGetGlyphCount(run) + var runGlyphs = [CGGlyph](repeating: 0, count: count) + CTRunGetGlyphs(run, CFRange(location: 0, length: count), &runGlyphs) + glyphs.append(contentsOf: runGlyphs) + } + // A ligature is any divergence from per-character mapping. A font may + // collapse the pair into one glyph (JetBrains Mono) or swap each + // character for a joining half kept at the same count (Maple Mono) — + // either way the sequence must be shaped, not mapped. + let singles = text.utf16.map { glyph(face, $0, tagline: false) } + let result = glyphs.count != singles.count + || zip(glyphs, singles).contains { $0 != $1 } + ligatureShaped[key] = result + return result + } + + /// When the cells at `col` ligate under `face`, the text to shape and how + /// many cells the ligature covers. Nil when they do not. Ligature cells + /// must carry the same face, colour and alpha and no rules of their own — + /// a ligature is one glyph of one style, not a style transition. + private func ligatureSpan(_ cells: UnsafePointer, base: Int, cols: Int, col: Int, + face: Face, fg: UInt32, alpha: CGFloat, + blockCol: Int, paneGripCells: Set) -> (text: String, covered: Int)? { + func eligible(_ index: Int) -> String? { + let cell = cells[base + index] + if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { return nil } + if cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 { return nil } + if cell.attrs >> UInt16(PARDES_ATTR_UL_SHIFT) != 0 + || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { return nil } + if paneGripCells.contains(base + index) { return nil } + let text = withUnsafeBytes(of: cell.text) { raw in + String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) + } + guard text.utf16.count == 1 else { return nil } + let other = resolve(cell, block: blockCol == index, + ground: themeBG ?? pardesDefaultBG, clearGround: false) + guard other.visible, other.fg == fg, other.alpha == alpha, + Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) == face else { return nil } + return text + } + guard let head = eligible(col), PardesView.ligatureHeads.contains(head.first!) else { return nil } + guard col + 1 < cols, let second = eligible(col + 1) else { return nil } + let pair = head + second + if col + 2 < cols, let third = eligible(col + 2) { + let triple = pair + third + if ligates(face, triple) { return (triple, 3) } + } + if ligates(face, pair) { return (pair, 2) } + return nil + } + + private func drawRules( + _ ctx: CGContext, + _ cell: pardes_cell_s, + _ style: (fg: UInt32, bg: UInt32, alpha: CGFloat, visible: Bool), + x: CGFloat, + /// The cell's advance: the body cell, or the narrower tagline one. A + /// rule is as wide as the character it belongs to, and on a tag row + /// that stopped being the body cell when the text compacted. + width: CGFloat, + baseline: CGFloat + ) { + let underline = Int(cell.attrs >> PARDES_ATTR_UL_SHIFT) & 7 + if underline != Int(PARDES_UL_OFF) { + let y = baseline + metrics.underlineOffset + fill(ctx, CGRect(x: x, y: y, width: width, height: metrics.ruleThickness), style.fg, style.alpha) + // ponytail: curly, dotted and dashed all come out solid; only double + // earns its second rule. ctx.setLineDash for two of them and a sine + // path for the third is the upgrade, once anyone notices. + if underline == Int(PARDES_UL_DOUBLE) { + fill(ctx, CGRect(x: x, y: y - metrics.ruleThickness * 2, width: width, height: metrics.ruleThickness), + style.fg, style.alpha) + } + } + if cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { + // Rounded like every other rule offset: a third of the ascent is a + // fraction, and a fractional one-pixel bar is a two-pixel smear. + fill(ctx, CGRect(x: x, y: baseline + (metrics.ascent * 0.3).rounded(), width: width, height: metrics.ruleThickness), + style.fg, style.alpha) + } + } + + private func setFill(_ ctx: CGContext, _ rgb: UInt32, _ alpha: CGFloat) { + // Theme channels, like PDF raster bytes, are sRGB. Device RGB can + // brighten them when AppKit's backing bitmap uses another profile. + ctx.setFillColor(CGColor(srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, + green: CGFloat((rgb >> 8) & 0xFF) / 255, + blue: CGFloat(rgb & 0xFF) / 255, + alpha: alpha)) + } + + /// One surface pixel has one background opacity, even when a compact + /// layer covers a canonical cell. Source-over would turn 71% into 92%, + /// then 98%, as the ground, row and cell are painted over each other. + private func fillBackground(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { + ctx.saveGState() + ctx.setShouldAntialias(false) + if rgb == bgClear { + ctx.clear(rect) + } else { + ctx.setBlendMode(.copy) + fill(ctx, rect, rgb, alpha) + } + ctx.restoreGState() + } + + private func fill(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { + setFill(ctx, rgb, alpha) + ctx.fill(rect) + } + + // MARK: - the core, and the pump + + /// Everything below ends here. Posting the notification in one place is + /// what guarantees no entry point can feed the core and forget to ask for + /// the tick that performs it. + private func fed() { + NotificationCenter.default.post(name: pardesDidInputNotification, object: self) + } + + /// A point inside the NSView can still be outside the CRT's curved tube. + /// For input that is the same as leaving the grid: discard a pending hover + /// preview, but do not manufacture a clamped click or wheel gesture. + private func leftGrid() { + pardes_pointer_leave() + fed() + } + + func typeKey(_ cp: UInt32, text: String, mods: UInt32) { + // The pointer is borrowed for the call and nowhere else, which is the only + // thing the header promises about it. + text.withCString { pardes_key(cp, $0, text.utf8.count, mods) } + fed() + } + + // `mods` defaults to none because a synthesized gesture carries no + // keyboard state; the NSEvent overrides always pass the real mask. Ctrl is + // the one the core actually consults — a left press with it held is + // goto-definition — so dropping it here would silently delete a feature. + private var sampledBodyPointer: CGPoint? + + private func sendMouse(_ button: pardes_mouse_button_e, _ kind: pardes_mouse_kind_e, + _ col: UInt16, _ row: UInt16, _ mods: UInt32) { + guard let point = sampledBodyPointer else { + pardes_mouse(button, kind, col, row, mods) + return + } + let scale = metricsScale + pardes_mouse_pixel(button, kind, col, row, mods, Float(point.x*scale), Float(point.y*scale), + Float(cellWidth*scale), Float(cellHeight*scale), Float(taglines.width*scale), Float(taglines.height*scale)) + } + + func press(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_PRESS, cell.col, cell.row, mods) + fed() + } + + func release(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_RELEASE, cell.col, cell.row, mods) + fed() + } + + func drag(_ button: pardes_mouse_button_e, to cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_DRAG, cell.col, cell.row, mods) + fed() + } + + func motion(to cell: GridPoint, mods: UInt32 = 0) { + sendMouse(PARDES_MOUSE_NONE, PARDES_MOUSE_MOTION, cell.col, cell.row, mods) + fed() + } + + /// A press and its release with nothing in between, which is what every + /// synthesized click is: a trackpad gesture we recognised rather than a + /// button the user held. + func click(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + press(button, at: cell, mods: mods) + release(button, at: cell, mods: mods) + } + + /// One discrete wheel notch, as opposed to the continuous travel below. + func wheel(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_PRESS, cell.col, cell.row, mods) + fed() + } + + func scroll(rows: CGFloat, cols: CGFloat = 0, at cell: GridPoint) { + guard rows != 0 || cols != 0 else { return } + pardes_scroll(Float(rows), Float(cols), cell.col, cell.row) + fed() + } + + /// Fingers down and fingers up on a precise scroll. Entry points of their + /// own for the same reason rotateEnd is one: NSEvent phases have no public + /// constructor, and a fling nothing can synthesize is a fling nothing can + /// assert. + func scrollBegin() { + pardes_scroll_begin() + fed() + } + + func scrollEnd() { + pardes_scroll_end() + fed() + } + + func rotate(degrees: CGFloat) { + guard degrees != 0 else { return } + pardes_rotate(Float(degrees)) + fed() + } + + /// The fingers came off the trackpad. A post-decode entry point of its own + /// so the e2e harness can throw the dial: NSEvent phases have no public + /// constructor, and a fling nothing can synthesize is a fling nothing can + /// assert. + func rotateEnd() { + pardes_rotate_end() + fed() + } + + // MARK: - keyboard + + override func keyDown(with event: NSEvent) { + let flags = event.modifierFlags + // Same reason as the trackpad trace below: whether AppKit delivered a + // keystroke at all is not something this process can otherwise answer, + // and "Escape does nothing" has two entirely different causes + // depending on whether this line prints. + trace("key: code=\(event.keyCode) mods=\(flags.rawValue) chars=" + + (event.charactersIgnoringModifiers?.unicodeScalars + .map { String($0.value, radix: 16) }.joined(separator: ",") ?? "-")) + // The ABI has no super bit, so a Command chord cannot be expressed at all. + // Anything the main menu claims never reaches here; the rest is swallowed + // rather than delivered as the bare keystroke the core would insert. + if flags.contains(.command) { + if event.charactersIgnoringModifiers?.lowercased() == "v" { + delegate?.pardesViewRequestsPaste(self) + } + return + } + + let control = flags.contains(.control) + let option = flags.contains(.option) + // With ctrl or option down, `characters` is already the composed result — + // Ctrl-A is U+0001, Option-A is "å". The core wants the base key and no + // text, which is what app.mjs does with the same two bits. + let composed = (control || option ? event.charactersIgnoringModifiers : event.characters) ?? "" + guard let scalar = composed.unicodeScalars.first else { return } + + var codepoint = scalar.value + // 0xF700..0xF8FF is AppKit's private-use block for function keys. The nine + // the core names get translated; the rest (F1-F12, Insert, the keypad) are + // dropped, because passing one through paints a stray glyph. + // These constants come from an unnamed C enum, so which width Swift picks + // for them is not something this file should depend on: wrapping each in + // UInt32() compiles whether they import as Int, Int32 or UInt32. + if scalar.value >= 0xF700 && scalar.value <= 0xF8FF { + switch scalar.value { + case UInt32(NSUpArrowFunctionKey): codepoint = UInt32(PARDES_KEY_UP) + case UInt32(NSDownArrowFunctionKey): codepoint = UInt32(PARDES_KEY_DOWN) + case UInt32(NSLeftArrowFunctionKey): codepoint = UInt32(PARDES_KEY_LEFT) + case UInt32(NSRightArrowFunctionKey): codepoint = UInt32(PARDES_KEY_RIGHT) + case UInt32(NSHomeFunctionKey): codepoint = UInt32(PARDES_KEY_HOME) + case UInt32(NSEndFunctionKey): codepoint = UInt32(PARDES_KEY_END) + case UInt32(NSPageUpFunctionKey): codepoint = UInt32(PARDES_KEY_PAGE_UP) + case UInt32(NSPageDownFunctionKey): codepoint = UInt32(PARDES_KEY_PAGE_DOWN) + case UInt32(NSDeleteFunctionKey): codepoint = UInt32(PARDES_KEY_DELETE) + default: return + } + } + + // Enter, Tab, Escape and Backspace already arrive as the ASCII controls the + // header names. Two keys do not: the keypad's Enter is U+0003 and Shift-Tab + // is U+0019, neither of which is in the function-key block above, so without + // this both reach the core as a control it has no binding for and do + // nothing. The browser shell resolves them from the DOM key name and this + // is what keeps the two hosts saying the same thing. + if codepoint == 0x03 { codepoint = UInt32(PARDES_KEY_ENTER) } + if codepoint == 0x19 { codepoint = UInt32(PARDES_KEY_TAB) } + + // A control character is functional, and functional keys must not also + // carry text. + let functional = codepoint < 0x20 || codepoint == 0x7F || codepoint >= 0xF0000 + let text = functional || control || option ? "" : composed + // Typing is the moment the pointer stops being interesting and starts + // sitting on top of the words. It comes back on the next mouse move. + NSCursor.setHiddenUntilMouseMoves(true) + typeKey(codepoint, text: text, mods: modifiers(flags)) + } + + // MARK: - trackpad + + // NSTouch arrives through these four and nowhere else. They are the only + // reliable source of "how many fingers are down right now": the touch set + // on a mouse event is an accident of how the click was produced, and an + // empty one is indistinguishable from one finger. + override func touchesBegan(with event: NSEvent) { countTouches(event) } + override func touchesMoved(with event: NSEvent) { countTouches(event) } + override func touchesEnded(with event: NSEvent) { countTouches(event) } + override func touchesCancelled(with event: NSEvent) { countTouches(event) } + + private func countTouches(_ event: NSEvent) { + restingFingers = event.touches(matching: .touching, in: nil).count + trace("touch: resting=\(restingFingers)") + } + + // MARK: - mouse + + // All three button streams land in the same three functions, because which + // stream a trackpad click arrives on is not something the app gets to know + // in advance: with macOS's secondary click on, two AND three fingers both + // come in as rightMouseDown. The button is therefore decided once, at the + // press, from the fingers plus the stream, and then LATCHED — the core is + // tracking a drag keyed by button, and answering a press of 3 with a + // release of 1 leaves it holding a sweep nothing will ever end. + // + // The count itself is maintained by the touchesXxx callbacks above; see + // beginClick for why it can only come from there. + private func beginClick(_ stream: pardes_mouse_button_e, _ event: NSEvent) { + guard let at = cell(for: event) else { + leftGrid() + return + } + pressureStage = 0 + // The count comes from the touch stream and NEVER from the mouse event. + // Asking a mouse event for its touches is not merely unreliable, it + // raises: -[NSEvent touchesMatchingPhase:inView:] is defined for + // gesture and touch events, and on anything else AppKit throws, catches + // it inside its own event dispatch, and abandons the rest of this + // method. Nothing crashes and nothing is logged — every click just + // silently stops working, a plain drag included, while rotation and + // scrolling carry on as if the backend were fine. That is exactly how + // this presented, and it is why restingFingers exists. + let button = Trackpad.button(stream: stream, fingers: restingFingers) + trace("press: stream=\(stream.rawValue) fingers=\(restingFingers) -> button=\(button.rawValue)") + latchedButton = button + latchedCell = at + press(button, at: at, mods: modifiers(event.modifierFlags)) + } + + private func continueClick(_ event: NSEvent) { + guard let button = latchedButton else { return } + guard let at = cell(for: event) else { + // The drag is still latched, but the curved CRT edge displays no + // source cell here. Keep its last real endpoint for mouseUp and + // clear hover/seam state without clamping into the grid. + leftGrid() + return + } + latchedCell = at + drag(button, to: at, mods: modifiers(event.modifierFlags)) + } + + private func endClick(_ event: NSEvent) { + pressureStage = 0 + // Already nil when the force click below converted this press: it + // released the button itself and there is nothing left to end. + guard let button = latchedButton else { return } + latchedButton = nil + if let at = cell(for: event) { + latchedCell = nil + release(button, at: at, mods: modifiers(event.modifierFlags)) + return + } + // A release must balance its press even when the hand ends in a black + // CRT corner. The last mapped drag point is an observed source cell, + // not a clamp of the unmappable release point. Send both state changes + // before one pump notification so no frame can observe a held button + // whose pointer is already outside the displayed scene. + if let last = latchedCell { + sendMouse(button, PARDES_MOUSE_RELEASE, last.col, last.row, + modifiers(event.modifierFlags)) + } + latchedCell = nil + pardes_pointer_leave() + fed() + } + + override func mouseDown(with event: NSEvent) { beginClick(PARDES_MOUSE_LEFT, event) } + override func mouseDragged(with event: NSEvent) { continueClick(event) } + override func mouseUp(with event: NSEvent) { endClick(event) } + // Where a two-finger click lands with macOS's own secondary click on, and + // where a three-finger one lands too — hence the finger count in + // Trackpad.button rather than a hardcoded RIGHT here. + override func rightMouseDown(with event: NSEvent) { beginClick(PARDES_MOUSE_RIGHT, event) } + override func rightMouseDragged(with event: NSEvent) { continueClick(event) } + override func rightMouseUp(with event: NSEvent) { endClick(event) } + // Thumb navigation has its own stream so it cannot replace a held + // selection button or inherit a resting trackpad's finger count. + override func otherMouseDown(with event: NSEvent) { + if event.buttonNumber == 2 { beginClick(PARDES_MOUSE_MIDDLE, event); return } + guard event.buttonNumber == 3 || event.buttonNumber == 4, + let at = cell(for: event) else { return } + press(event.buttonNumber == 3 ? PARDES_MOUSE_BACK : PARDES_MOUSE_FORWARD, + at: at, mods: pointerModifiers) + } + override func otherMouseDragged(with event: NSEvent) { + if event.buttonNumber == 2 { continueClick(event) } + } + override func otherMouseUp(with event: NSEvent) { + if event.buttonNumber == 2 { endClick(event); return } + guard event.buttonNumber == 3 || event.buttonNumber == 4, + let at = cell(for: event) else { return } + release(event.buttonNumber == 3 ? PARDES_MOUSE_BACK : PARDES_MOUSE_FORWARD, + at: at, mods: pointerModifiers) + } + + /// A deep press, which is a second gesture layered on the click already in + /// flight. AppKit keeps sending stage-2 events while the finger stays down, + /// so only the transition counts. + /// + /// Whatever button is in flight is released before the look one goes out: + /// a right press arriving while the core holds a left select-drag is + /// acme's 1-3 chord, which is Paste. Releasing first costs a cursor move + /// at the click point — which is what clicking there would have done + /// anyway; a multi-finger press released this way fires its own Exec, + /// which is what the fingers already asked for. + /// + /// Not gated on the press being a LEFT one, which is what stopped this + /// working: on a Force Touch trackpad the deep press is just as likely to + /// have arrived on the right stream, and an in-flight Exec upgraded by + /// pressing harder is precisely the gesture. Already-Look is the only case + /// with nothing to do. + override func pressureChange(with event: NSEvent) { + trace("pressure: stage=\(event.stage) latched=\(String(describing: latchedButton?.rawValue))") + guard pressureStage < 2 else { return } + pressureStage = event.stage + guard event.stage == 2 else { return } + guard let at = latchedCell, let current = latchedButton, + current != Trackpad.forceClickButton else { return } + latchedButton = nil + latchedCell = nil + release(current, at: at, mods: modifiers(event.modifierFlags)) + click(Trackpad.forceClickButton, at: at, mods: modifiers(event.modifierFlags)) + } + + override func mouseMoved(with event: NSEvent) { + guard let at = cell(for: event) else { + leftGrid() + return + } + motion(to: at, mods: modifiers(event.modifierFlags)) + } + + override func mouseExited(with event: NSEvent) { + pointerPoint = nil + pointerMapped = false + leftGrid() + } + + override func scrollWheel(with event: NSEvent) { + guard let at = cell(for: event) else { + leftGrid() + return + } + if event.hasPreciseScrollingDeltas { + // Phases first: a finger back on the pad has to catch a coast before + // its own travel is spent, or the first millimetre of the new swipe + // would be added to the old fling instead of replacing it. + // + // Momentum events carry `phase == .none` and a momentumPhase + // instead, so neither branch here fires for them — they are just + // more travel, and libpardes lets them take the gesture over. That + // is deliberate: AppKit's fling is the one the rest of the system + // uses, and a second fling of our own underneath it would scroll + // everything at double speed. `pardes_scroll_end` exists for the + // devices AppKit does NOT fling for. + if event.phase == .began { scrollBegin() } + // The core scrolls a cell at a time, so libpardes accumulates the + // sub-cell travel and spends it as wheel presses — which is why the + // cell has to travel with the delta. + scroll(rows: -event.scrollingDeltaY / cellHeight, + cols: -event.scrollingDeltaX / cellWidth, + at: at) + switch event.phase { + case .ended: scrollEnd() + // A gesture the system took away should not be thrown. scrollBegin + // is the catching half of the pair — coast stopped, bank and + // velocity cleared — which is exactly what a cancellation means. + case .cancelled: scrollBegin() + default: break + } + } else { + // AppKit's sign is the opposite of the DOM's: positive deltaY means the + // content moved down, which is a scroll back through history. + if event.scrollingDeltaY != 0 { + wheel(event.scrollingDeltaY > 0 ? PARDES_MOUSE_WHEEL_UP : PARDES_MOUSE_WHEEL_DOWN, + at: at, mods: modifiers(event.modifierFlags)) + } + if event.scrollingDeltaX != 0 { + wheel(event.scrollingDeltaX > 0 ? PARDES_MOUSE_WHEEL_LEFT : PARDES_MOUSE_WHEEL_RIGHT, + at: at, mods: modifiers(event.modifierFlags)) + } + } + } + + /// Two fingers twisted on the trackpad are the search-step keys: clockwise + /// walks forward through the matches, counterclockwise back. It is a dial, + /// and n/N is what a dial over a list of hits means. libpardes owns the + /// quantizing and the momentum, exactly as it owns the scroll accumulator. + /// + /// AppKit gives rotation no momentum phase of its own — `momentumPhase` is + /// scroll's alone — so the fling is measured from the release speed on the + /// Zig side rather than handed to us. All this has to get right is telling + /// it where the gesture starts and stops. + override func rotate(with event: NSEvent) { + trace("rotate: degrees=\(event.rotation) phase=\(event.phase.rawValue)") + // A gesture starting drops whatever the last one left banked, so the + // first degree of a new twist cannot inherit a nearly-complete notch — + // and stops a fling still coasting, because a finger back down is how + // a hand catches a dial. + if event.phase == .began { pardes_rotate(0) } + rotate(degrees: CGFloat(event.rotation)) + // .cancelled too: a gesture the system took away should not fling. + if event.phase == .ended || event.phase == .cancelled { rotateEnd() } + } + + /// What the trackpad actually delivered, under PARDES_LOG — the same + /// variable the Zig side gates its logger on (src/macos.zig). + /// + /// This is not scaffolding left behind. Which events a trackpad produces is + /// decided by the hardware and by four different System Settings switches + /// (secondary click, three-finger drag, force click, "look up"), none of + /// which this process can read, and every one of which turns a gesture into + /// a different NSEvent or into none at all. When someone reports that + /// two-finger Exec does nothing, this is the only thing that can answer + /// whether AppKit saw two fingers, one, or no click at all. + private func trace(_ message: @autoclosure () -> String) { + guard PardesView.tracing else { return } + FileHandle.standardError.write(Data(("pardes: " + message() + "\n").utf8)) + } + + private static let tracing = ProcessInfo.processInfo.environment["PARDES_LOG"] != nil + + private func cell(for event: NSEvent) -> GridPoint? { + let point = convert(event.locationInWindow, from: nil) + pointerPoint = point + pointerModifiers = modifiers(event.modifierFlags) + let at = cellAt(point) + pointerMapped = at != nil + if let at { pointerCell = at } + return at + } + + func cellAt(_ point: CGPoint) -> GridPoint? { + // Clamp against the frame the core last rendered, not against our own + // metrics: a window that has been resized but not yet ticked would + // otherwise report a column the core has no cell for. Before the first + // frame there is no grid to point at and the event is meaningless. + let cols = Int(pardes_frame_cols()) + let rows = Int(pardes_frame_rows()) + guard cols > 0, rows > 0 else { return nil } + let sampled: CGPoint + if let scene = lastPresentedScene { + guard let mapped = ScenePostprocessor.sourcePoint(point, size: bounds.size, scene: scene) + else { return nil } + sampled = mapped + } else { + sampled = point + } + sampledBodyPointer = sampled + let row = min(max(Int(sampled.y / cellHeight), 0), rows - 1) + let col = min(max(Int(sampled.x / cellWidth), 0), cols - 1) + return GridPoint(col: UInt16(col), row: UInt16(row)) + } + + // MARK: - files dropped on the grid + + /// A drop is a CLICK followed by `Look`, and that is the whole definition. + /// + /// The core has no notion of a drop and is not being given one: the pointer + /// lands where it landed, which focuses that pane exactly as a left click + /// there would, and then the ordinary `Look` builtin runs in it — so the + /// document opens beside the pane you pointed at rather than beside + /// whichever one happened to be focused. Drop on a tag and you clicked a + /// tag; there is no case to special-case, and nothing here the hand could + /// not have done itself. + override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { + // AppKit reuses this answer for draggingUpdated when that is not + // implemented, so the cursor stays right for the whole drag. + droppedFiles(sender).isEmpty ? [] : .copy + } + + override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { + let paths = droppedFiles(sender) + guard !paths.isEmpty else { return false } + drop(paths, at: cellAt(convert(sender.draggingLocation, from: nil))) + return true + } + + /// The drop, decoded: paths and a cell, nothing AppKit left in it. + /// + /// Split out for the reason every gesture here is — `NSDraggingInfo` is a + /// protocol with a dozen members and no public conformer, so a test that + /// had to build one would be testing its own stub. The decision lives one + /// call below the event, and `drop` in test/macos_e2e.swift drives exactly + /// this. + /// + /// A nil cell is a drop before the first frame, which has no grid to point + /// at: the files still open, they just open where focus already was. + func drop(_ paths: [String], at target: GridPoint?) { + if let target { + press(PARDES_MOUSE_LEFT, at: target) + release(PARDES_MOUSE_LEFT, at: target) + } + // Whole tail, unquoted: executeBuiltinLine takes everything after the + // first word as the argument, so a path with spaces in it needs no + // escaping and would in fact break under any. + for path in paths { + let line = "Look \(path)" + line.withCString { pardes_command($0, line.utf8.count) } + } + fed() + } + + /// File paths on the drag pasteboard, in order. Empty for anything else, + /// which is also how draggingEntered decides whether to accept at all. + private func droppedFiles(_ sender: NSDraggingInfo) -> [String] { + let options: [NSPasteboard.ReadingOptionKey: Any] = [.urlReadingFileURLsOnly: true] + guard let urls = sender.draggingPasteboard.readObjects( + forClasses: [NSURL.self], options: options) as? [URL] + else { return [] } + return urls.map(\.path) + } + + // MARK: - geometry + + override func updateTrackingAreas() { + super.updateTrackingAreas() + for area in trackingAreas { removeTrackingArea(area) } + // .inVisibleRect keeps the area correct across resizes on its own, which + // is why the rect argument can be anything. + addTrackingArea(NSTrackingArea(rect: .zero, + options: [.mouseMoved, .mouseEnteredAndExited, .inVisibleRect, .activeInKeyWindow], + owner: self, + userInfo: nil)) + } + + private enum Pointer: Equatable { case text, link, target } + private var pointer: Pointer = .text + + /// The core's pointer_shape, in this shell's cursor vocabulary: a link + /// is a PDF hyperlink (the hand), a target is a word the core's own + /// Look-hover plumbing validated as a real Look or Exec operand, and + /// anything else is text — the I-beam. + private func pointerShape() -> Pointer { + switch pardes_pointer_shape() { + case 1: return .link + case 2: return .target + default: return .text + } + } + + private func cursorFor(_ shape: Pointer) -> NSCursor { + switch shape { + case .link: return .pointingHand + case .target: return .arrow + case .text: return .iBeam + } + } + + override func resetCursorRects() { + // Every cell in this view is text, including the tags. An arrow over + // plain text is the wrong affordance — but a word the core has + // validated as a Look or Exec target earns it: middle- and + // right-clicking there acts, and the cursor says so before it does. + addCursorRect(bounds, cursor: cursorFor(pointer)) + } + + override func setFrameSize(_ newSize: NSSize) { + super.setFrameSize(newSize) + // AppKit resizes a view many times over one drag and almost all of those + // land inside the same cell. Only a changed grid is news, and the core + // reflows every pty on a resize, so the no-ops are not free. + let grid = gridSize + guard grid.cols != reportedCols || grid.rows != reportedRows else { return } + reportedCols = grid.cols + reportedRows = grid.rows + delegate?.pardesViewDidResize(self) + } + + // Dragging the window between a Retina display and a 1x one changes the + // backing scale without moving a single bound, so setFrameSize above never + // fires. This is the only notification of it. (Ghostty hooks the same one, + // and additionally re-fires from the window's didChangeScreen + // notification, which AppKit does not always pair with it.) + // + // TWO things depend on the scale: the physical cell metrics the core uses + // to place PDF pages, and the cell itself, which is snapped to whole + // DEVICE pixels (see Metrics) and is therefore aligned to the display it + // was measured on. Re-measuring reports the resize on its own, so the + // delegate call is the else-branch and not an extra one. + override func viewDidChangeBackingProperties() { + super.viewDidChangeBackingProperties() + if let scale = window?.backingScaleFactor, scale != metricsScale { + wear(size: fontSize, path: fontPath) + } else { + delegate?.pardesViewDidResize(self) + } + } +} + +// ponytail: no NSTextInputClient, so dead keys and IME composition never reach +// the core — keyDown reads `characters` and that is the whole story. Adopting +// the protocol and routing through interpretKeyEvents is the upgrade when +// someone needs to type Japanese, and it needs the core to be able to render an +// underlined preedit run first. diff --git a/dev/macos/Sources/ScenePostprocessor.swift b/dev/macos/Sources/ScenePostprocessor.swift new file mode 100644 index 00000000..41d54e34 --- /dev/null +++ b/dev/macos/Sources/ScenePostprocessor.swift @@ -0,0 +1,321 @@ +// The one GPU owner for panel transitions and persistent scene effects. +// CoreText remains the renderer: while either exists PardesView draws its +// complete ordinary frame into this retained bitmap, then Core Image runs the +// standalone shaders/crt.ci.metal kernels over it. With neither, the view +// bypasses this object entirely. + +import CoreGraphics +import CoreImage +import Darwin +import Metal + +final class ScenePostprocessor { + enum CompositeOutcome { + case presented + case retry + case unavailable + } + + private let colorSpace: CGColorSpace + private let sceneKernel: CIKernel + private let panelClearKernel: CIKernel + private let panelKernel: CIKernel + private let context: CIContext + private var raster: CGContext? + private var previousRaster: CGContext? + private var rasterWidth = 0 + private var rasterHeight = 0 + private var rasterScale: CGFloat = 0 + + init?() { + let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) + ?? CGColorSpaceCreateDeviceRGB() + guard let source = ScenePostprocessor.kernelSource(), + let device = MTLCreateSystemDefaultDevice(), + let made = try? CIKernel.kernels(withMetalString: source), + let sceneKernel = made.first(where: { $0.name == "pardesScene" }), + let panelClearKernel = made.first(where: { $0.name == "pardesPanelClear" }), + let panelKernel = made.first(where: { $0.name == "pardesPanel" }) + else { return nil } + self.colorSpace = colorSpace + self.sceneKernel = sceneKernel + self.panelClearKernel = panelClearKernel + self.panelKernel = panelKernel + self.context = CIContext(mtlDevice: device, options: [ + .workingColorSpace: colorSpace, + .outputColorSpace: colorSpace, + .cacheIntermediates: false, + ]) + } + + private static func kernelSource() -> String? { + var candidates: [URL] = [] + if let resources = Bundle.main.resourceURL { + candidates.append(resources.appendingPathComponent("crt.ci.metal")) + } + // An unbundled e2e executable has no Contents/Resources. Its build + // puts the asset next to the binary, and this explicit candidate keeps + // that dev loop independent of Bundle's treatment of command tools. + if let executable = Bundle.main.executableURL { + candidates.append(executable.deletingLastPathComponent() + .appendingPathComponent("crt.ci.metal")) + } + for url in candidates { + if let source = try? String(contentsOf: url, encoding: .utf8) { + return source + } + } + return nil + } + + /// A body-font-sized, top-left-origin CGContext matching the view's own + /// coordinate system. It is retained across frames; only a resize or a + /// backing-scale move reallocates the pixel storage. + func renderContext(size: CGSize, scale: CGFloat) -> CGContext? { + let scale = max(1, scale) + let width = max(1, Int((size.width * scale).rounded(.up))) + let height = max(1, Int((size.height * scale).rounded(.up))) + if raster == nil || width != rasterWidth || height != rasterHeight || scale != rasterScale { + let info = CGBitmapInfo.byteOrder32Big.rawValue + | CGImageAlphaInfo.premultipliedLast.rawValue + guard let next = CGContext( + data: nil, width: width, height: height, + bitsPerComponent: 8, bytesPerRow: width * 4, + space: colorSpace, bitmapInfo: info) + else { return nil } + next.translateBy(x: 0, y: CGFloat(height)) + next.scaleBy(x: scale, y: -scale) + raster = next + // The old and new snapshots must have identical extents. Lazily + // rebuild the old owner only if an effect actually needs it. + previousRaster = nil + rasterWidth = width + rasterHeight = height + rasterScale = scale + } + return raster + } + + /// A second complete CoreText raster for the frozen old grid. It is + /// intentionally a peer of `raster`, not a collection of per-pane image + /// pointers: deleted PDF/image panes have already released their core + /// bytes, while PardesView's frozen CGImages remain safe to draw here. + func previousRenderContext(size: CGSize, scale: CGFloat) -> CGContext? { + guard renderContext(size: size, scale: scale) != nil else { return nil } + if previousRaster == nil { + let info = CGBitmapInfo.byteOrder32Big.rawValue + | CGImageAlphaInfo.premultipliedLast.rawValue + guard let next = CGContext( + data: nil, width: rasterWidth, height: rasterHeight, + bitsPerComponent: 8, bytesPerRow: rasterWidth * 4, + space: colorSpace, bitmapInfo: info) + else { return nil } + next.translateBy(x: 0, y: CGFloat(rasterHeight)) + next.scaleBy(x: rasterScale, y: -rasterScale) + previousRaster = next + } + return previousRaster + } + + /// Run the one scene kernel and copy its result into the flipped NSView + /// context. Allocation/device failures may be retried briefly. A kernel + /// rejecting its fixed argument layout is permanent for this executable, + /// so the caller can turn the advertised effects back off instead of + /// silently spinning a display clock forever. + func composite( + scene: pardes_scene_s, + tracks: UnsafeBufferPointer, + changedCells: UnsafePointer?, + changedAttachmentRects: [CGRect], + gridSize: (cols: Int, rows: Int), + cellSize: CGSize, + ground: UInt32?, + size: CGSize, + into destination: CGContext + ) -> CompositeOutcome { + guard let raster, let sourceImage = raster.makeImage() else { return .retry } + let extent = CGRect(x: 0, y: 0, width: rasterWidth, height: rasterHeight) + let current = CIImage(cgImage: sourceImage, options: [.colorSpace: colorSpace]) + let old: CIImage + if let previousImage = previousRaster?.makeImage() { + old = CIImage(cgImage: previousImage, options: [.colorSpace: colorSpace]) + } else { + old = current + } + let mask = changeMask( + changedCells, attachmentRects: changedAttachmentRects, + gridSize: gridSize, cellSize: cellSize) ?? + CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 1)) + .cropped(to: CGRect(x: 0, y: 0, width: 1, height: 1)) + var filtered = current + + // Geometric targets are prepared before any presented panel is drawn. + // Horizontal slide/zoom use the theme ground; a vertical opener uses + // the exact old frame inside its fixed clip. Data effects and closing + // tombstones leave the canonical current frame untouched underneath. + let clear = ground.map { encoded in + CIColor( + red: CGFloat((encoded >> 16) & 0xFF) / 255, + green: CGFloat((encoded >> 8) & 0xFF) / 255, + blue: CGFloat(encoded & 0xFF) / 255, + alpha: 1) + } ?? CIColor(red: 0, green: 0, blue: 0, alpha: 0) + for track in tracks { + let content = track.phase == UInt8(PARDES_PANEL_CLOSING) ? track.from : track.to + guard let next = panelClearKernel.apply( + extent: extent, + roiCallback: { _, _ in extent }, + arguments: [ + filtered, old, + pixelBox(content, cellSize: cellSize), clear, + Float(track.effect), Float(track.phase), + ]) + else { return .unavailable } + filtered = next + } + + // libpardes orders moving, opening, then closing tombstones. Each pass + // samples immutable old/new rasters and composes over the prior pass, + // so a deleted pane can safely outlive its core Pane allocation. + let pixelCell = CIVector( + x: cellSize.width * rasterScale, + y: cellSize.height * rasterScale) + for track in tracks { + let content = track.phase == UInt8(PARDES_PANEL_CLOSING) ? track.from : track.to + guard let next = panelKernel.apply( + extent: extent, + roiCallback: { _, _ in extent }, + arguments: [ + current, old, mask, filtered, + pixelBox(content, cellSize: cellSize), + pixelBox(track.from, cellSize: cellSize), + pixelBox(track.to, cellSize: cellSize), + Float(track.effect), Float(track.phase), Float(track.frame), + CIVector( + x: CGFloat(track.serial & 0xFFFF), + y: CGFloat(track.serial >> 16)), + pixelCell, + CIVector( + x: 0, + y: extent.height - CGFloat(gridSize.rows) * pixelCell.y), + ]) + else { return .unavailable } + filtered = next + } + + if scene.flags != 0 { + let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 + // SDL samples the scene with CLAMP_TO_EDGE. A finite Core Image + // instead supplies transparent black outside its extent, which + // would tear dark seams at the window edge. + // Clamp the input only; the kernel still emits true black before + // sampling when a destination lies outside the CRT tube. + let sceneInput = filtered.clampedToExtent() + guard let next = sceneKernel.apply( + extent: extent, + roiCallback: { _, _ in extent }, + arguments: [ + sceneInput, scene.time_seconds, Float(scene.frame), + crt, + CIVector(x: extent.width, y: extent.height), + CIVector(x: extent.minX, y: extent.minY), + ]) + else { return .unavailable } + filtered = next + } + + guard let presented = context.createCGImage(filtered, from: extent) else { return .retry } + + destination.clear(CGRect(origin: .zero, size: size)) + destination.saveGState() + destination.translateBy(x: 0, y: size.height) + destination.scaleBy(x: 1, y: -1) + destination.interpolationQuality = .none + destination.draw(presented, in: CGRect(origin: .zero, size: size)) + destination.restoreGState() + return .presented + } + + /// Byte-per-cell mask from the core. Zig expands true to 255 so the image + /// is a literal normalized 0/1 texture; sampling cell centres below keeps + /// adjacent values from interpolating at pane/cell boundaries. + private func changeMask( + _ cells: UnsafePointer?, + attachmentRects: [CGRect], + gridSize: (cols: Int, rows: Int), + cellSize: CGSize + ) -> CIImage? { + let count = gridSize.cols * gridSize.rows + guard count > 0, let cells, cellSize.width > 0, cellSize.height > 0 else { return nil } + var bytes = Array(UnsafeBufferPointer(start: cells, count: count)) + for rect in attachmentRects where !rect.isNull && !rect.isEmpty { + let x0 = max(0, Int((rect.minX / cellSize.width).rounded(.down))) + let x1 = min(gridSize.cols, Int((rect.maxX / cellSize.width).rounded(.up))) + let y0 = max(0, Int((rect.minY / cellSize.height).rounded(.down))) + let y1 = min(gridSize.rows, Int((rect.maxY / cellSize.height).rounded(.up))) + guard x0 < x1, y0 < y1 else { continue } + for row in y0.. CIVector { + let cellW = cellSize.width * rasterScale + let cellH = cellSize.height * rasterScale + let x = CGFloat(box.x) * cellW + let w = CGFloat(box.w) * cellW + let h = CGFloat(box.h) * cellH + let y = CGFloat(rasterHeight) - (CGFloat(box.y) + CGFloat(box.h)) * cellH + return CIVector(x: x, y: y, z: w, w: h) + } + + /// The scene kernel is a destination-to-source mapping. Pointer input must + /// apply that same mapping before the grid and its panel tracks see a cell, + /// otherwise a visible word under the barrel is not the word Look gets. + static func sourcePoint( + _ point: CGPoint, + size: CGSize, + scene: pardes_scene_s + ) -> CGPoint? { + guard size.width > 0, size.height > 0 else { return nil } + if scene.flags == 0 { return point } + + var uvX = Float(point.x / size.width) + var uvY = 1 - Float(point.y / size.height) // Core Image is bottom-up + var ccX = uvX * 2 - 1 + var ccY = uvY * 2 - 1 + let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 + let radius2 = ccX * ccX + ccY * ccY + let barrel = 1 + 0.016 * radius2 * crt + ccX *= barrel + ccY *= barrel + uvX = ccX * 0.5 + 0.5 + uvY = ccY * 0.5 + 0.5 + // The CRT's black tube has no cell under it. + if crt > 0.5 && min(min(uvX, uvY), min(1 - uvX, 1 - uvY)) <= 0 { return nil } + uvX = min(max(uvX, 0), max(0, 1 - 1 / Float(size.width))) + uvY = min(max(uvY, 0), max(0, 1 - 1 / Float(size.height))) + return CGPoint( + x: CGFloat(uvX) * size.width, + y: CGFloat(1 - uvY) * size.height) + } + +} diff --git a/dev/macos/Sources/main.swift b/dev/macos/Sources/main.swift new file mode 100644 index 00000000..6cb2646e --- /dev/null +++ b/dev/macos/Sources/main.swift @@ -0,0 +1,16 @@ +import AppKit + +// Ghostty's ordering lesson: whatever must exist before AppKit boots goes above +// app.run(), because after that call the runloop owns this thread forever. +// pardes has nothing in that class — the core cannot come up until there is a +// window to measure, so pardes_init waits for applicationDidFinishLaunching. + +let app = NSApplication.shared +app.setActivationPolicy(.regular) + +// NSApplication does not own its delegate. This is a global, so it lives as +// long as the process does; the same line inside a function would not. +let delegate = AppDelegate() +app.delegate = delegate + +app.run() diff --git a/dev/macos/icon.png b/dev/macos/icon.png new file mode 100644 index 00000000..9889c348 Binary files /dev/null and b/dev/macos/icon.png differ diff --git a/dev/macos/icon.swift b/dev/macos/icon.swift new file mode 100644 index 00000000..2f45220f --- /dev/null +++ b/dev/macos/icon.swift @@ -0,0 +1,194 @@ +// Cuts pardes.app's icon out of a committed drawing and hands the result to +// iconutil. +// +// The mark is still GLENDA, the Plan 9 rabbit — pardes is an acme, and acme is +// Plan 9's, so the bunny is the lineage stated in one shape. What changed is +// where she comes from: she used to be drawn here out of the terminal's own +// palette, four ellipses and a tag bar, and she is now `icon.png` beside this +// file. A drawing is not derivable from a palette, so the old argument for +// generating her ("a checked-in .icns stops matching the app the first time a +// colour moves") no longer applies to the artwork — but it still applies to +// the ICNS, which is why this file did not become a committed binary. What is +// committed is the source picture, in one format, reviewable as an image; what +// is generated is the ten-size container macOS actually reads. +// +// So the work here is no longer drawing. It is the part a designer's PNG never +// has: Apple's icon grid, the rounded-square mask, and ten exact sizes. +// +// build.zig compiles this file alone into a cached binary and runs it with the +// source PNG as argv[1] and the bundle's Resources directory as argv[2]; +// Info.plist's CFBundleIconFile names the pardes.icns that comes out. Compiled +// alone is also what makes top-level code legal here: one file, one module. +// +// Byte-identical output for byte-identical input is a requirement, not a +// nicety — an icns that churns on every build is a bundle that churns on every +// build, and Launch Services notices. Hence a pinned sRGB colour space, +// integer geometry, and nothing read from the clock or the environment. + +import CoreGraphics +import Foundation +import ImageIO +import UniformTypeIdentifiers + +/// Every failure path lands here. A build that ships the generic blank-page +/// icon looks like an app nobody finished, so half-drawn is worse than absent +/// and build.zig has this exit code waiting: a bundle whose icon did not draw +/// should not have built. +func die(_ message: String) -> Never { + fputs("icon.swift: \(message)\n", stderr) + exit(1) +} + +// Apple's icon grid rather than the whole square: the artwork is a rounded +// square floating in a transparent margin, 824 of 1024 with a 185.4 corner +// radius in the template — 80.47% of the canvas, and 22.37% of the SQUARE, not +// of the canvas, which would over-round it by a quarter. Filling the canvas +// edge to edge is the loudest tell that an app was not built on a Mac. +let squareFraction: CGFloat = 0.8047 +let cornerFraction: CGFloat = 0.2237 + +/// Where the crop comes off when the source is not square. +/// +/// The drawing is 1204x1306 — taller than wide — so filling a square throws +/// away 8% of its height, and WHICH 8% is the whole decision. Anchoring the +/// top keeps the sun, which is the only warm thing in the picture and sits in +/// the top-right corner, and spends the loss on the bottom band of grass, +/// which is texture and repeats. Anchoring the centre would clip the sun's +/// rays to buy back grass, which is the trade backwards. 0 is top, 1 is +/// bottom; a square source ignores this entirely. +let cropAnchor: CGFloat = 0 + +/// sRGB in the bitmap, so the paper white in the drawing is the paper white in +/// the icon rather than whatever DeviceRGB would make of it. +func sRGB() -> CGColorSpace { + guard let space = CGColorSpace(name: CGColorSpace.sRGB) else { die("sRGB colour space unavailable") } + return space +} + +func loadSource(_ url: URL) -> CGImage { + guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { + die("cannot read \(url.path)") + } + guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { + die("\(url.lastPathComponent) holds no decodable image") + } + return image +} + +func renderIcon(_ art: CGImage, pixels: Int) -> CGImage { + guard + let ctx = CGContext( + data: nil, width: pixels, height: pixels, + bitsPerComponent: 8, bytesPerRow: 0, space: sRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) + else { die("CGContext \(pixels)x\(pixels) failed") } + + // Round the MARGIN and derive the square from it. Rounding the square + // instead leaves an odd remainder to split, and at 16 pixels the artwork + // lands a pixel off centre. At 1024 this is Apple's 100/824/100 exactly. + let canvas = CGFloat(pixels) + let inset = (canvas * (1 - squareFraction) / 2).rounded() + let side = canvas - 2 * inset + let body = CGRect(x: inset, y: inset, width: side, height: side) + let corner = side * cornerFraction + + ctx.addPath(CGPath(roundedRect: body, cornerWidth: corner, cornerHeight: corner, transform: nil)) + ctx.clip() + + // Aspect FILL, not fit. Fitting would letterbox the rounded square with a + // flat band beside textured paper, and the seam between the two is visible + // at every size the band is wide enough to see. Filling overflows the clip + // instead, and the clip is already exact. + let artWidth = CGFloat(art.width) + let artHeight = CGFloat(art.height) + guard artWidth > 0, artHeight > 0 else { die("source image is empty") } + let scale = max(side / artWidth, side / artHeight) + let drawWidth = artWidth * scale + let drawHeight = artHeight * scale + + // CoreGraphics is bottom-left origin, so `cropAnchor` 0 (the TOP of the + // picture) means the drawing's top edge meets the body's top edge and the + // overflow hangs off the bottom, into the clip. + let overflowY = drawHeight - side + let overflowX = drawWidth - side + ctx.interpolationQuality = .high + ctx.draw( + art, + in: CGRect( + x: body.minX - overflowX / 2, + y: body.maxY - drawHeight + overflowY * cropAnchor, + width: drawWidth, height: drawHeight)) + + guard let image = ctx.makeImage() else { die("CGContext.makeImage failed at \(pixels)") } + return image +} + +func writePNG(_ image: CGImage, to url: URL) { + guard + let sink = CGImageDestinationCreateWithURL( + url as CFURL, UTType.png.identifier as CFString, 1, nil) + else { die("cannot open \(url.path) for writing") } + CGImageDestinationAddImage(sink, image, nil) + guard CGImageDestinationFinalize(sink) else { die("encoding \(url.lastPathComponent) failed") } +} + +// The ten names iconutil demands, spelled out rather than derived: the set is +// fixed by the tool, and a loop that generated them would be a loop to read +// before believing the list. 32, 256 and 512 appear twice under two names and +// are simply drawn twice — a third of a megapixel, against the clarity of not +// caching anything in a build tool. +let variants: [(name: String, pixels: Int)] = [ + ("icon_16x16.png", 16), + ("icon_16x16@2x.png", 32), + ("icon_32x32.png", 32), + ("icon_32x32@2x.png", 64), + ("icon_128x128.png", 128), + ("icon_128x128@2x.png", 256), + ("icon_256x256.png", 256), + ("icon_256x256@2x.png", 512), + ("icon_512x512.png", 512), + ("icon_512x512@2x.png", 1024), +] + +let arguments = CommandLine.arguments +guard arguments.count == 3 else { + die("usage: \(URL(fileURLWithPath: arguments.first ?? "icon").lastPathComponent) ") +} + +let files = FileManager.default +let art = loadSource(URL(fileURLWithPath: arguments[1])) +let outputDir = URL(fileURLWithPath: arguments[2], isDirectory: true) +let output = outputDir.appendingPathComponent("pardes.icns") + +// A fixed scratch path, cleared before use rather than a unique one: a run that +// died half way leaves a partial iconset behind, and iconutil would happily +// fold the stale sizes into the next icns without a word. +let scratch = files.temporaryDirectory.appendingPathComponent("pardes-icon", isDirectory: true) +let iconset = scratch.appendingPathComponent("pardes.iconset", isDirectory: true) + +try? files.removeItem(at: scratch) +do { + try files.createDirectory(at: iconset, withIntermediateDirectories: true) + try files.createDirectory(at: outputDir, withIntermediateDirectories: true) +} catch { + die("cannot create \(iconset.path): \(error.localizedDescription)") +} + +for variant in variants { + writePNG(renderIcon(art, pixels: variant.pixels), to: iconset.appendingPathComponent(variant.name)) +} + +let iconutil = Process() +iconutil.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil") +iconutil.arguments = ["-c", "icns", "-o", output.path, iconset.path] +do { + try iconutil.run() +} catch { + die("cannot run /usr/bin/iconutil: \(error.localizedDescription)") +} +iconutil.waitUntilExit() +guard iconutil.terminationStatus == 0 else { + die("iconutil exited \(iconutil.terminationStatus) over \(iconset.path)") +} + +try? files.removeItem(at: scratch) diff --git a/dev/root.zig b/dev/root.zig new file mode 100644 index 00000000..2c70783f --- /dev/null +++ b/dev/root.zig @@ -0,0 +1,34 @@ +//! The devices: the frontends (tui, gui; the macOS app's Swift and +//! resources in macos/), the host's services (host_io), the file watcher, +//! the fonts installed, the language servers' client and the SCIP index, +//! and what the frontends share (Art, jump_trail, glide, vaxis_input). +//! Module `dev`, naming `core` and `runtime`. +pub const tui = @import("tui/tui.zig"); +pub const gui = @import("gui/gui.zig"); +pub const host_io = @import("host_io.zig"); +pub const file_watch = @import("file_watch.zig"); +pub const fonts = @import("fonts.zig"); +pub const lsp_client = @import("lsp/lsp_client.zig"); +pub const Scip = @import("lsp/Scip.zig"); +pub const Art = @import("Art.zig"); +pub const jump_trail = @import("jump_trail.zig"); +pub const glide = @import("glide.zig"); +pub const vaxis_input = @import("vaxis_input.zig"); + +test { + _ = host_io; + _ = host_io.Shell; + _ = host_io.Lsp; + _ = file_watch; + _ = fonts; + _ = lsp_client; + _ = Scip; + _ = glide; + // The frontends', which main.zig's test block collected: a shell's + // build (shell-test); the core without a terminal never compiled them. + if (comptime @import("term_options").terminal) { + if (comptime @import("pardes_config").platform == .tui) _ = tui; + if (comptime @import("pardes_config").platform == .gui) _ = gui; + _ = vaxis_input; + } +} diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig new file mode 100644 index 00000000..df2d0016 --- /dev/null +++ b/dev/tui/tui.zig @@ -0,0 +1,3386 @@ +const filesystem = @import("core").filesystem; +const std = @import("std"); +const builtin = @import("builtin"); +const posix = std.posix; +/// libc: termios, signals, kitty shm segments and the fds a terminal hands over. +const libc = std.c; +const vaxis = @import("vaxis"); +const pardes = @import("core"); +const JumpTrail = @import("../jump_trail.zig"); +const Art = @import("../Art.zig"); +const vaxis_input = @import("../vaxis_input.zig"); +const tracy = @import("core").tracy; +const look = @import("core").look; +const message = pardes.Messages.Message; +const file_watch = @import("../file_watch.zig"); +const selection_pipe = @import("core").selection_pipe; +const ninep_io = @import("runtime").ninep_io; +const daemon = @import("runtime").daemon; +const host_io = @import("../host_io.zig"); +const upgrade = @import("runtime").upgrade; +const replica = @import("core").replica; + +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 the terminal's input reader keeps: its graphemes, the frame it +/// waits on the answer to, and the shm probe. +const Feed = struct { + 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), +}; + +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 {}; +} + +/// What the loop's queue carries: a terminal's input, a pane's output, a +/// worker's answer, a wake. +const Msg = 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, + /// 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, + /// A kind's job done on a worker (host_io.KindJob). + kind_job: *host_io.KindJob, + 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, +}; +const Loop = vaxis.Loop(Msg); + +fn startInput(loop: *Loop, sc: *Screen) !void { + 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)}); + }; + loop.postEvent(.quit) catch {}; +} + +fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { + try loop.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(loop, vx, &feed.cache, Msg, 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; +} + +/// What a test of a terminal's input needs: vaxis (its capabilities, its +/// parser's allocator), the loop's queue and a feed, set up in place (vaxis +/// keeps the environment's address) and torn down in the order vaxis needs. +const TestInput = struct { + env: std.process.Environ.Map, + vx: vaxis.Vaxis, + out: std.Io.Writer.Allocating, + loop: Loop, + feed: Feed, + + fn init(t: *TestInput) !void { + const gpa = std.testing.allocator; + t.env = try std.testing.environ.createMap(gpa); + errdefer t.env.deinit(); + t.vx = try vaxis.init(std.testing.io, gpa, &t.env, .{ .system_clipboard_allocator = gpa }); + t.out = .init(gpa); + t.loop = .init(std.testing.io, undefined, &t.vx); + t.feed = .{}; + } + + fn deinit(t: *TestInput) void { + t.vx.deinit(std.testing.allocator, &t.out.writer); + t.out.deinit(); + t.env.deinit(); + } +}; + +/// A terminal that hands over `parts`, a read each (an empty one passed +/// over), and says more follows (within `gap_ms`) while some are left. +const TestReader = struct { + parts: []const []const u8, + next: usize = 0, + gap_ms: u32 = 0, + asked: bool = false, + + fn getWinsize(_: *TestReader) !vaxis.Winsize { + return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; + } + + pub fn inputFollows(r: *TestReader, ms: u32) bool { + r.asked = true; + return r.next < r.parts.len and r.gap_ms <= ms; + } + + fn read(r: *TestReader, buf: []u8) !usize { + while (r.next < r.parts.len) { + const part = r.parts[r.next]; + r.next += 1; + if (part.len == 0) continue; + @memcpy(buf[0..part.len], part); + return part.len; + } + return 0; + } +}; + +const PipeTasks = selection_pipe.Tasks; + +const Pty = struct { + file: std.Io.File, + pid: posix.pid_t, + reader: std.Io.Future(error{OutOfMemory}!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 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 (one cell row): its `src` into its +/// `at`, inside that 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.Placement, + screen_cols: u16, + screen_rows: u16, + screen_pixel_w: u16, + screen_pixel_h: u16, +) ?KittyPlacement { + const g: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at 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.dst.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.dst.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 }, + }, + }; +} + +/// A PDF's page over its body: declared to kitty by its columns where it +/// is as wide as the body (fit to width), else by its rows, and its source +/// cut so the declared cells never run past its clipped bottom. +fn kittyPlacement( + place: pardes.Placement, + screen_cols: u16, + screen_rows: u16, + screen_pixel_w: u16, + screen_pixel_h: u16, +) ?KittyPlacement { + const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); + const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); + const geometry: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null }; + const fit: enum { width, height } = if (geometry.dst.w >= @as(u32, place.dst.w) * cell_w) .width else .height; + + 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 (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, + ); + }, + } + 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.dst.w or cell_y >= place.dst.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.dst.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.dst.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 (fit) { + .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, + .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, + }, + }, + }; +} + +fn kittyImageRepresentable(place: pardes.Placement) bool { + return place.raster.w > 0 and place.raster.h > 0 and + place.raster.w <= std.math.maxInt(u16) and place.raster.h <= std.math.maxInt(u16); +} + +fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool { + for (surface.placements.items) |place| { + if (place.art.glyph or !kittyImageRepresentable(place)) continue; + if (place.key == key) return true; + } + return false; +} + +/// 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, detached 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 }, detached }; + +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) }; + 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)), + .detached => {}, + } + 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 (`runClient`), drawn here. +const Client = 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: *Client, 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 runClient(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; + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + pardes.Term.start(allocs.image); + pardes.Kind.heap = allocs.addon; + pardes.syntax.start(allocs.tree_sitter); + defer { + pardes.Term.stop(); + pardes.syntax.stop(); + } + var o = opts; + o.image_allocator = allocs.image; + var joined: replica.Joined = undefined; + var r = replica.join(gpa, &joined, path, session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + + 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) }; + defer screen.kitty.deinit(); + try screen.enter(try vaxis.Tty.init(io, &tty_buf)); + defer screen.leave(); + defer screen.glide.deinit(gpa); + defer screen.art.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 client_link: Client = .{ .link = .{ .r = r, .fd = joined.fd } }; + const link = &client_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, + .own = joined.view, + .screen = &screen, + .client = &client_link, + }; + + pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; + defer pardes.Kind.drawer = null; + 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) { + sh.core = r.core(); + sh.own = joined.view; + link.reset(r, &joined); + 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) { + client_link.draw(&sh); + } else if (sh.moving() and r.core().surface.cells.len != 0) { + // The tty's own motions (its glide, a jump's trail): the last + // frame again, moved on, as the session's terminal draws them + // (`ownFrame`), not rendered again. One the terminal's answer + // holds is skipped (the next tick's moves on): nothing of it + // is written in the core, as `Client.draw` puts it back. + const skipped = r.core().present_skipped; + Shell.present(&sh, &r.core().surface); + r.core().present_skipped = skipped; + link.again += 1; + } + // Idle, its frame drawn: the next key needs no copy taken. + if (loop.tryEvent() catch null) |ev| sh.held = ev else r.ready(); + // The session's own wait: an input drawn at once, the session's + // units and deltas a frame a tick at most, the tty's own motions + // on its grid of ticks; predictions judged a frame at a time. + var wait: u32 = if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) @intCast(pardes.frame_ns / std.time.ns_per_ms) else 0; + if (link.quietCheck()) |ms| wait = if (wait == 0) ms else @min(wait, ms); + Shell.waitInput(&sh, wait); + r.settle(); + // A rollback since it drew (`toConfirmed`): its frame is drawn + // again, never moved on from cells the copy put back. + if (r.moved) { + r.moved = false; + link.dirty = true; + } + 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; + 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, .blob => |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. + r = replica.join(gpa, &joined, path, session, o, have, &why, r) orelse { + screen.leave(); + Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + }; + } +} + +/// 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), its stub `daemon.stub`. One a +/// process: a second terminal on a session is a replica client of it. +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, + feed: Feed = .{}, + thread: ?std.Io.Future(void) = null, + /// The kitty images it holds, by placement key. + kitty: std.AutoHashMap(u64, vaxis.Image), + /// The glyph art of the pictures it shows so (all of them without + /// kitty graphics). + art: Art = .{}, + caps_pending: bool = true, + /// Its size as last taken (`Shell.resized`). + size: ?vaxis.Winsize = null, + /// The view's glide, the GUI's motion drawn at whole rows (anim 12). + glide: pardes.glide.Glide = .{}, + /// The cursor's jump trail (JumpTrail), on the tty's own clock. + trail: JumpTrail = .{}, + + /// `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) { + Killed.arm(sc.tty.fd.handle, sc.tty.termios); + // What a panic puts back (vaxis.recover). + vaxis.tty.global_tty = sc.tty; + } + sc.feed = .{}; + sc.caps_pending = true; + sc.size = null; + sc.on = true; + } + + fn leave(sc: *Screen) void { + if (!sc.on) return; + sc.on = false; + Killed.disarm(); + 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) vaxis.tty.global_tty = null; + sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets + } + + /// Its terminal hung up, or the stub that waits on it is gone. + fn hungUp(sc: *const Screen) bool { + // vaxis's test tty off Linux has no fd. + if (comptime !@hasField(@TypeOf(sc.tty), "fd")) return false; + const stub = daemon.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); + } +}; + +/// SIGTERM or SIGHUP: the 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 fd: posix.fd_t = -1; + var cooked: posix.termios = undefined; + const reset = "\x1b[= 0) { + _ = std.c.write(fd, reset, reset.len); + _ = std.c.tcsetattr(fd, .FLUSH, &cooked); + } + // 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.tree_sitter_allocator = allocs.tree_sitter; + options.frame_allocator = allocs.frame; + + host_io.startWorkers(allocs); + defer host_io.stopWorkers(); + options.addons = pardes.Addon.scan(); + + 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.screen = 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); + defer screen.art.deinit(gpa); + 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.list[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); + sh.job_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); + 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), + .kind_job => |j| j.drop(), + .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; + pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; + defer pardes.Kind.drawer = null; + // An upgraded session's terminals, its own again. + if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec); + // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). + sh.setAttended(!sh.detached()); + 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); + + 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); + // Detached, the unit is its clients' frame: its output is paced to + // it as a terminal's frame paces it (waitInput), a unit a frame, not + // a unit and a delta for every read of a flood. + if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(io).nanoseconds); + 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: { + const nc = host_io.restoreCore(gpa, core, rp, &sh.peers, sh.inotify_fd, &sh.watches) orelse 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 (0..pardes.MAX_PANES) |pane| Shell.closePty(&sh, @intCast(pane)); + // One view, the terminal's (host_io.restoreCore). + const live = screen; + stopInput(io, &live.thread); + sh.own = 0; + if (live.on) startInput(loop, live) catch {}; + if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); + nc.view().frontend.native_images = live.on and live.vx.caps.kitty_graphics; + nc.unattended = !live.on; + sh.peers.detached = !live.on; + if (fs) |f| f.reset(nc); + core.deinit(); + core = nc; + sh.core = nc; + if (live.on) core.update(.{ .resize = terminalSize(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(u64, 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(); +} + +/// 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.tellStub(a.stub, "r{s}", .{"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, + /// The terminal (none in tests), and the view it shows: a second + /// terminal on the session is a replica client (`pardes --attach`). + screen: ?*Screen = null, + own: 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: host_io.Adoptions = .{}, + 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(void) = null, + lsp_task: ?host_io.Lsp.Task = null, + pipe_tasks: PipeTasks = .{}, + job_tasks: PipeTasks = .{}, + threads_ok: bool = false, + check_files: bool = false, + 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: ?Msg = null, + /// This process a replica client of a session elsewhere (`runClient`): + /// its inputs go to the replica, never straight to the core. + client: ?*Client = null, + + /// 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.client 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 { + return s.screen != null; + } + + /// 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.detached = !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 = ownFrame, + }; + + 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, + .start = host_io.startDetached, + .lsp = lsp, + .pipe = pipe, + .search = search, + .job = job, + }; + + 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.clock.now_ns; + } + return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + } + + /// The terminal, while its view is live (null in tests, and while a + /// replica client's is: its input the last). + fn term(s: *const Shell) ?*Screen { + return if (s.core.live == s.own) s.screen else null; + } + + /// No terminal of its own (a test's, with none at all, is not detached). + fn detached(s: *const Shell) bool { + const screen = s.screen orelse return false; + return !screen.on; + } + + /// Drawn only while a terminal shows it. + fn watched(ctx: ?*anyopaque) bool { + return !of(ctx).detached(); + } + + /// 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.live)) return; + if (s.detached()) return s.core.reportFailure(s.core.view().active, "Detach: detached already (no terminal of its own)"); + if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)"); + s.leaveTerminal(); + } + + fn leaveTerminal(s: *Shell) void { + const screen = s.screen orelse return; + stopInput(s.io, &screen.thread); + screen.leave(); + s.core.view().frontend.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); + } + daemon.tellStubDetached(); + daemon.setState(true); + } + + /// `pardes --attach`'s terminal, for a detached session: its own again, + /// entered as the first one was, sized, asked what it can do, and drawn + /// whole. One attached already takes no other (the daemon makes a second + /// a replica client). + fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { + const screen = s.screen orelse { + _ = libc.close(fd); + return refuse(stub, "that session has no terminal of its own to attach to"); + }; + if (screen.on) { + _ = libc.close(fd); + return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=:`"); + } + const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { + _ = libc.close(fd); + daemon.setState(true); + return refuse(stub, "that terminal would not go raw"); + }; + screen.enter(tty) catch { + daemon.setState(true); + return refuse(stub, "that terminal would not take the screen"); + }; + daemon.stub = stub; + s.setAttended(true); + startInput(s.loop, screen) catch {}; + screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; + s.core.needs_frame = true; + daemon.setState(false); + } + + /// 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.tellStub(stub, "r{s}", .{why}); + } + + fn adopt(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + s.adoptions.ask(s.core, pane); + } + + /// A client's own build is not the session's to say (its core's host + /// is the session's, through the tape). + fn newerBuild(ctx: ?*anyopaque) bool { + return of(ctx).client == null and upgrade.newer(); + } + + fn upgradeAsked(ctx: ?*anyopaque, 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 {}; + if (s.screen) |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); + if (s.screen) |sc| if (sc.on) rec.addTty(.{ + .view = s.own, + .fd = sc.tty.fd.handle, + .stub = daemon.stub, + .primary = true, + .termios = sc.tty.termios, + }); + var popped = false; + var at_buf: [1024:0]u8 = undefined; + const failed: []const u8 = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse failed: { + // What this process put in its terminals that the next puts in + // again: its images, and its keyboard mode, a stack. + if (s.screen) |sc| if (sc.on) { + clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); + if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[= 0) daemon.tellStub(t.stub, "d{s}", .{daemon.name()}); + } + if (rec.fresh) return; + for (0..pardes.views.max) |k| if (k != s.own and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); + } + + 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 (pardes.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; + // The tty's own motions (its glide, a jump's trail) wake it a frame at + // a time while they move: on a virtual clock a millisecond's wait + // moves it a frame (waitOnce), on the real one the pace below sets it. + if (s.moving()) wait = 1; + // Detached, nobody's key dismisses a message: they go on the clock + // (the pump's, after this wait), which wakes it. + if (s.detached()) { + 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.moving(); + var tick: u64 = 0; + if (paced) { + const period = pardes.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). + // Detached, its clients' echo is the frame's after an input: what a + // flood says after that goes a unit a frame (their own echo is + // predicted, src/echo.zig), not a unit and a delta a read for a second. + const echo_ns: u64 = if (s.detached()) pardes.frame_ns else std.time.ns_per_s; + 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 < echo_ns) break; + const due = s.drawn_ns + pardes.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 the tty's own + // motions move (the glide), as the real one would. + s.wake_to = s.core.nextWake() orelse if (s.moving()) s.core.clock.now_ns + pardes.frame_ns else 0; + requestWake(s.io, wait); + } + pardes.turn.rest(); + const got = s.loop.nextEvent() catch { + pardes.turn.wake(); + if (s.client) |c| c.link.quit = true; + 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: ?Msg = 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: Msg) 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: Msg) 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; + // The terminal's input goes into its view. + switch (event) { + .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { + if (s.local() and s.client == null) core.toView(s.own); + }, + else => {}, + } + switch (event) { + .nop => {}, + .winched => s.winched(), + // The terminal hung up (its stub passes the hangup on) or its + // stub died (a forked session's death signal): its input has + // ended. + .hangup => if (s.screen) |sc| if (sc.on and sc.hungUp()) { + if (s.apply(.quit)) return true; + }, + .wake => if (s.test_clock) |*virtual| { + virtual.* = @max(virtual.*, s.wake_to); + }, + .quit => { + if (s.client) |c| { + c.link.quit = true; + 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.detached()) s.leaveTerminal(); + return true; + } + core.quit = true; + return true; + }, + .attach => |a| s.attachTerminal(a.tty, a.stub, null), + .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), + .replica => |j| { + s.peers.handed(j.fd, j.view); + s.input_seen = true; + }, + .replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) { + s.input_seen = true; + }, + .said => |said| if (s.client) |c| { + // The session's units and deltas are a client's output + // (waitInput paces it): a terminal's delta, or the unit + // that answers its own input, is its echo, drawn at once. + s.output_seen = true; + const echo = switch (said) { + .screen => true, + .unit => |b| if (replica.parseUnit(b)) |u| u.origin == c.link.r.id else false, + else => false, + }; + if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + c.link.take(said); + if (said == .refused) return true; + } else switch (said) { + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), + .checked => {}, + }, + .link_gone => if (s.client) |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.detached()) s.resized(s.screen, ws), + .pty_read => |pr| { + tookRead(s.io, pr.id); + s.output_seen = true; + if (pr.id == core.view().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 = vaxis_input.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| if (mouseEvent(m)) |ev| s.feed(ev), + .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.view().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); + }, + .kind_job => |j| { + s.job_tasks.finish(s.io, j.id); + j.land(core); + // A client's draw done: its frame is its own to draw again. + if (s.client) |cl| cl.link.dirty = true; + }, + } + return false; + } + + /// Terminal `screen` (its view live) 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 = terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) }); + } + + /// A SIGWINCH: the terminal, if it changed size, resized in its view + /// (one reporting in band says so as input). + fn winched(s: *Shell) void { + const sc = s.screen orelse return; + if (!sc.on or sc.vx.state.in_band_resize) return; + const ws = sc.tty.getWinsize() catch return; + if (sc.size) |was| if (std.meta.eql(was, ws)) return; + if (s.client == null) s.core.toView(s.own); + 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 {}; + } + + /// The tty's own motions (its glide, a jump's trail) are under way. + fn moving(s: *const Shell) bool { + const sc = s.term() orelse return false; + return sc.glide.moving() or sc.trail.active; + } + + /// The tty's own motions draw their frames themselves: the last frame + /// again, moved on, when the core has none to draw. + fn ownFrame(ctx: ?*anyopaque) void { + const s = of(ctx); + if (s.moving() and !s.core.needs_frame and s.core.surface.cells.len != 0) present(ctx, &s.core.surface); + } + + fn pollFrame(ctx: ?*anyopaque) void { + const s = of(ctx); + defer ownFrame(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.view().frontend.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.view().frontend.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; + // 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 tz_cells = tracy.zone(@src(), "surface->vaxis"); + const win = vx.window(); + // The tty's own motions, on its own clock, from the frame alone. + const now: u64 = s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + // The pictures it shows as glyph art, in a copy of the frame: all + // of them where the terminal has no kitty graphics. + const cell_h = terminalCellPixels(vx.screen.height_pix, vx.screen.height, 16); + const arted = sc.art.frame(s.gpa, s.frame.allocator(), canonical, vx.caps.kitty_graphics, cell_h) catch canonical; + sc.glide.frame(s.gpa, arted, now, null, null); + s.core.frames.scroll = @round(sc.glide.follow.offset); + const glided = glideRows(s.frame.allocator(), arted, &sc.glide) catch arted; + const truecolor = vx.caps.rgb or colortermTruecolor(); + const trail_on = s.core.settings.jump_trail and truecolor; + const shown = trailCells(s.frame.allocator(), glided, &sc.trail, trail_on, now) catch glided; + paintCells(win, shown.cells, shown.cols, shown.rows); + if (s.client) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), shown.cols, shown.rows); + tz_cells.end(); + if (vx.caps.kitty_graphics) for (canonical.placements.items) |place| { + if (place.art.glyph or !kittyImageRepresentable(place)) continue; + const key = place.key; + const rgba = place.raster.bytes(); + if (!sc.kitty.contains(key) 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, rgba)) break :shm; + if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.raster.w), @intCast(place.raster.h), .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)) { + const enc = std.base64.standard.Encoder; + if (s.gpa.alloc(u8, enc.calcSize(rgba.len))) |b64| { + defer s.gpa.free(b64); + _ = enc.encode(b64, rgba); + if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.raster.w), @intCast(place.raster.h), .rgba) catch null) |handle| + sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); + } else |_| {} + } + const cached = sc.kitty.get(key) orelse continue; + const d = place.dst; + if (place.at == null) { + // Fitted: kitty's own contain, at the top left. + const child = win.child(.{ .x_off = d.x, .y_off = d.y, .width = d.w, .height = d.h }); + cached.draw(child, .{ .scale = .contain }) catch {}; + } else if (d.h == 1) { + 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 = d.x + placement.cell_x; + if (win.readCell(x, d.y)) |under| { + var cell = under; + cell.image = .{ .img_id = cached.id, .options = placement.options }; + win.writeCell(x, d.y, cell); + } + } + } 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, d.x) + placement.cell_x, + .y_off = @as(i17, d.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]u64 = undefined; + var stale_len: usize = 0; + var image_iterator = sc.kitty.iterator(); + while (image_iterator.next()) |entry| { + if (surfaceHasKittyKey(canonical, 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 (shown.cursor) |cur| { + win.showCursor(cur.x, cur.y); + win.setCursorShape(if (cur.bar) .beam else .default); + } + 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() != null) s.core.presented(); + tracy.frameMark(); + } + + fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + const s = of(ctx); + if (s.adoptions.take(pane)) |a| 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.view().screen_h, s.core.view().screen_w) 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: host_io.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.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); + if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {}; + } + + 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 }); + sc.vx.requestSystemClipboard(sc.tty.writer()) catch {}; + } + + 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.view().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); + } + + /// A draw (api.draw) on a worker, as a job is. + fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { + const s = of(ctx); + return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct { + fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void { + of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop(); + } + }.deliver); + } + + fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { + const s = of(ctx); + if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); + host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { + fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { + of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); + } + }.deliver); + } + + /// 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); + } +}; + +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) 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 (`runClient`): 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: Msg = 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; + } + } + } +} + +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) error{OutOfMemory}!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 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)); +} + +/// A replica client's own line over its frame's last row (`Client.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. +/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind +/// the cursor in its body, on the page's own ground, that ground drawn +/// toward the text's colour; a copy of `shown` while it fades. +fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface { + var at: [5]JumpTrail.Cell = undefined; + const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); + if (lit.len == 0) return shown; + const cursor = shown.cursor.?; + const body = for (shown.regionList()) |region| { + if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and + cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; + } else return shown; + const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; + const page = shown.chrome.page orelse pardes.colors.null_page; + const out = try arena.create(pardes.Surface); + out.* = shown.*; + out.cells = try arena.dupe(pardes.Cell, shown.cells); + for (lit) |cell| { + if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; + const c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))]; + // On the page's own ground alone: never a selection or a match. + const ground: [3]u8 = if (c.default) page else switch (c.style.bg) { + .rgb => |rgb| rgb, + else => page, + }; + if (!std.mem.eql(u8, &ground, &page)) continue; + if (c.default) c.style = .{}; + c.default = false; + c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) }; + } + return out; +} + +/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does +/// not answer vaxis's query. +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"); +} + +/// The tty's picture of the glide (glide.zig, anim 12): the body's rows +/// moved by the offset rounded to whole rows (the position rounded, never +/// the step, so a slowing glide's steps come further apart), the rows that +/// left in the gap it opens, and a caret whose line rode the scroll carried +/// with it; `canonical` itself while the picture is where the core is, else +/// a copy of it in `arena`. The rows are walked from the side they move +/// toward, so each is read before a move writes over it. +fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface { + const k: i32 = @intFromFloat(@round(glide.follow.offset)); + const w = glide.bw(); + const h = glide.body_h; + const x0 = glide.rect.x + pardes.config.GUTTER; + const y0 = glide.body_y; + if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical; + const out = try arena.create(pardes.Surface); + out.* = canonical.*; + out.cells = try arena.dupe(pardes.Cell, canonical.cells); + const cols: usize = out.cols; + for (0..h) |i| { + const r = if (k > 0) i else h - 1 - i; + const from = @as(i32, @intCast(r)) + k; + const to = out.cells[(y0 + r) * cols + x0 ..][0..w]; + const kept: ?[]const pardes.Cell = if (from >= 0 and from < h) + out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w] + else if (from < 0 and -from - 1 < glide.nabove) + glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w] + else if (from >= h and from - h < glide.nbelow) + glide.below[@as(usize, @intCast(from - h)) * w ..][0..w] + else + null; + if (kept) |cells| @memcpy(to, cells) else @memset(to, .{}); + } + if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) { + const y = @as(i32, c.y) - k; + if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null; + }; + return out; +} + +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 = vaxis_input.style(cell.style), + }); + } + } +} + +test "terminal input preserves fragmented keys queries paste and text after EOF" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ .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(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(t.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 t.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(t.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" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ + .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(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(t.vx.queries_done.load(.unordered)); + try std.testing.expect(t.vx.caps.kitty_graphics); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + var alt_up = false; + var clicked = false; + while (try t.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" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // Two reads with `gap_ms` between them, as an ssh link delivers a + // sequence cut across two packets (TestReader). + const Events = struct { + /// What the loop was handed, one line per event. + fn of(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| { + t.vx.caps.kitty_keyboard = case.kitty; + const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); + defer gpa.free(all); + const whole_parts = [_][]const u8{ all, "" }; + var one: TestReader = .{ .parts = &whole_parts }; + try readInput(&t.loop, &one, &t.vx, &t.feed); + try Events.of(&t.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; + const halves = [_][]const u8{ all[0..cut], all[cut..] }; + var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; + try readInput(&t.loop, &two, &t.vx, &t.feed); + try Events.of(&t.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; + }; + } + } + t.vx.caps.kitty_keyboard = false; +} + +test "an ESC read by itself is the Escape key at once" { + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + // More always follows at once: a reader that waited on the ESC would + // take `j` for the rest of its sequence (Alt-j). + for ([_]bool{ false, true }) |kitty| { + t.vx.caps.kitty_keyboard = kitty; + var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(!reader.asked); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); + const escape = (try t.loop.tryEvent()).?.key_press; + try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); + try std.testing.expect(!escape.mods.alt); + const j = (try t.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 t.loop.tryEvent() == null); + } + t.vx.caps.kitty_keyboard = false; +} + +test "a frame's answer is taken wherever the reads cut it, and never typed" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + const all = "x" ++ FrameAck.answer ++ "y"; + defer t.feed.ack.waiting.store(false, .release); + for (0..all.len) |cut| { + t.feed.ack.waiting.store(true, .release); + const halves = [_][]const u8{ all[0..cut], all[cut..] }; + var reader: TestReader = .{ .parts = &halves }; + try readInput(&t.loop, &reader, &t.vx, &t.feed); + try std.testing.expect(!t.feed.ack.waiting.load(.acquire)); + var typed: std.ArrayList(u8) = .empty; + defer typed.deinit(gpa); + var woke = false; + while (try t.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. + t.feed.ack.waiting.store(true, .release); + var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } }; + try readInput(&t.loop, &glued, &t.vx, &t.feed); + try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); + try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?)); + const escape = (try t.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 t.loop.tryEvent()).?.key_press.codepoint); + try std.testing.expect(try t.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" { + const io = std.testing.io; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + 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 loop: Loop = .init(io, undefined, &t.vx); + var feed: Feed = .{}; + var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.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(Msg) = 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); + } +} + +test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { + var place = pardes.Placement{ + .pane = 0, + .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 }, + .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, + .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 }, + .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, + .key = pardes.Placement.keyOf(3, 7, 0), + }; + // 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.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }; + place.at = .{ .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.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }; + place.at = .{ .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" { + // As wide as the body: fit to width. + const base = pardes.Placement{ + .pane = 0, + .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 }, + .src = .{ .w = 96, .h = 10 }, + .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 }, + .at = .{ .y = 195, .w = 304, .h = 29 }, + .key = pardes.Placement.keyOf(1, 0, 1), + }; + 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.at.?.h); + + // Narrower than the body: fit to height. + var height = base; + height.at.?.w = 300; + height.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.at.?.h); + + height.at.?.h = 13; + try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); +} + +test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 }); + defer core.deinit(); + core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } }); + const pane = core.panes[0].?; + pane.body.mode = .tty; + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const a = frame.allocator(); + const px = try a.alloc(u8, 64 * 64 * 3); + for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 }; + const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len)); + _ = std.base64.standard.Encoder.encode(enc, px); + core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } }); + while (core.nextEffect()) |_| {} + const s = try core.render(a); + try std.testing.expectEqual(@as(usize, 4), s.placements.items.len); + var art: Art = .{}; + defer art.deinit(gpa); + try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16)); + const shown = try art.frame(gpa, a, s, false, 16); + const r = core.view().rects[0]; + const x0 = r.x + pardes.config.GUTTER + 7; + const y0 = core.bodyTop(pane, r) + 1; + var painted: usize = 0; + for (0..4) |dy| for (0..8) |dx| { + const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy))); + const bg = switch (cell.style.bg) { + .rgb => |rgb| rgb, + else => continue, + }; + for (Art.commodore) |c| { + if (std.mem.eql(u8, &c, &bg)) painted += 1; + } + }; + try std.testing.expectEqual(@as(usize, 32), painted); +} + +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.Term.scrollback(core.panes[0].?.terminal, 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_ask.wait.?.id; + core.lspRequest(0, .status, ""); + const current_id = core.lsp_ask.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_ask.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_ask.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.view().active, .status, ""); + const req: host_io.Lsp.Request = .{ + .id = core.lsp_ask.wait.?.id, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }; + Shell.lsp(&shell, req); + try std.testing.expect(core.lsp_ask.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); + } +} + +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); +} + +test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + t.vx.queries_done.store(false, .unordered); + var reader: TestReader = .{ + .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(&t.loop, &reader, &t.vx, &t.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 t.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", vaxis_input.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()); + } + } +} + +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); + } +} + +test "a jump's trail tints the ground behind the cursor in its body, and is gone by 120 ms" { + std.testing.refAllDecls(JumpTrail); + 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.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 = .{}; + const ms = std.time.ns_per_ms; + s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; + _ = try trailCells(arena.allocator(), s, &trail, true, 1000 * ms); + // Ten cells right: a trail back toward where it was. + s.cursor = .{ .x = body.x + 12, .y = body.y + 1 }; + const lit = try trailCells(arena.allocator(), s, &trail, true, 1016 * ms); + var changed: usize = 0; + for (lit.cells, s.cells, 0..) |a, b, i| { + if (std.meta.eql(a, b)) 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); + try std.testing.expect(trail.active); + try std.testing.expect(try trailCells(arena.allocator(), s, &trail, true, 1150 * ms) == s); + try std.testing.expect(!trail.active); +} + +test "a fade sends the text it dims, not the blanks beside it" { + const gpa = std.testing.allocator; + var t: TestInput = undefined; + try t.init(); + defer t.deinit(); + try t.vx.resize(gpa, &t.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 }; + t.out.clearRetainingCapacity(); + paintCells(t.vx.window(), &cells, 32, 1); + try t.vx.render(&t.out.writer); + sent[frame] = try t.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); +} + +test "the tty draws a glide at whole rows: once a flick or a spin slows, its steps a tick never grow and its one-row steps come further apart, to where the core is" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 30, .tty_only = true }); + defer core.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..3000) |i| try text.print(gpa, "{d:0>5} line\n", .{i}); + _ = try core.setTestFile(text.items); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var glide: pardes.glide.Glide = .{}; + defer glide.deinit(gpa); + var now: u64 = std.time.ns_per_s; + // One tick of the tty: the frame, the picture. + const tick = struct { + fn f(c: *pardes.Pardes, g: *pardes.glide.Glide, a: *std.heap.ArenaAllocator, t: u64) !i32 { + c.advance(t); + _ = a.reset(.retain_capacity); + const s = try c.render(a.allocator()); + g.frame(std.testing.allocator, s, t, null, null); + _ = try glideRows(a.allocator(), s, g); + return @intFromFloat(@round(g.follow.offset)); + } + }.f; + _ = try tick(core, &glide, &arena, now); + for ([_]usize{ 4, 24 }) |notches| { + for (0..notches) |i| { + core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 20, .row = 10 } }); + if (i % 2 == 1) { + now += pardes.frame_ns; + _ = try tick(core, &glide, &arena, now); + } + } + var drawn = try tick(core, &glide, &arena, now + pardes.frame_ns); + now += pardes.frame_ns; + var last_step: i32 = std.math.maxInt(i32); + var last_gap: usize = 0; + var since: usize = 0; + var ticks: usize = 0; + while (glide.moving()) : (ticks += 1) { + try std.testing.expect(ticks < 200); + now += pardes.frame_ns; + const k = try tick(core, &glide, &arena, now); + const step = k - drawn; + drawn = k; + since += 1; + if (step == 0) continue; + // Toward the core, never past it, each step no longer than the last. + try std.testing.expect(step > 0 and k <= 0); + try std.testing.expect(step <= last_step); + if (step == 1 and last_step == 1) try std.testing.expect(since >= last_gap); + if (step == 1) last_gap = since; + last_step = step; + since = 0; + } + try std.testing.expectEqual(@as(i32, 0), drawn); + } + // j held on the bottom row: the text glides a row a key under a caret + // that stays on its cell (it does not ride: its row is kept). + const keys = struct { + fn j(c: *pardes.Pardes) void { + c.update(.{ .key = .{ .cp = 'j', .text = "j" } }); + } + }; + for (0..40) |_| keys.j(core); + now += std.time.ns_per_s; + _ = try tick(core, &glide, &arena, now); + const row = (core.surface.cursor orelse return error.NoCursor).y; + for (0..20) |i| { + if (i % 2 == 0) keys.j(core); + now += pardes.frame_ns; + _ = try tick(core, &glide, &arena, now); + const shown = try glideRows(arena.allocator(), &core.surface, &glide); + try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y); + } +} diff --git a/dev/vaxis_input.zig b/dev/vaxis_input.zig new file mode 100644 index 00000000..6cea6553 --- /dev/null +++ b/dev/vaxis_input.zig @@ -0,0 +1,147 @@ +//! A key as vaxis parses it from a terminal's bytes, as the core's Event: +//! the one map for every shell that reads a terminal (tty, gui's stdin). +//! Three copies had drifted; the gui's had lost the F-keys, +//! Insert and the keypad. And the other way, a cell's style as vaxis draws +//! it. +const std = @import("std"); +const vaxis = @import("vaxis"); +const pardes = @import("core"); + +/// The effective codepoint the way vaxis's own `Key.matches` sees it: a +/// single-character `text` wins, the terminal having resolved shift; +/// otherwise the shifted codepoint. +pub fn effCp(key: vaxis.Key) u21 { + if (key.text) |t| { + const view = std.unicode.Utf8View.init(t) catch return key.codepoint; + var it = view.iterator(); + if (it.nextCodepoint()) |c| { + if (it.nextCodepoint() == null) return c; + } + } + return key.shifted_codepoint orelse key.codepoint; +} + +/// vaxis's functional-key codepoints as the core's; the ASCII ones +/// (enter, tab, escape, backspace) already coincide. +pub fn mapKey(cp: u21) u21 { + return switch (cp) { + vaxis.Key.kp_enter => pardes.Key.enter, + vaxis.Key.up => pardes.Key.up, + vaxis.Key.down => pardes.Key.down, + vaxis.Key.left => pardes.Key.left, + vaxis.Key.right => pardes.Key.right, + vaxis.Key.home => pardes.Key.home, + vaxis.Key.end => pardes.Key.end, + vaxis.Key.page_up => pardes.Key.page_up, + vaxis.Key.page_down => pardes.Key.page_down, + vaxis.Key.delete => pardes.Key.delete, + vaxis.Key.insert => pardes.Key.insert, + vaxis.Key.print_screen => pardes.Key.print_screen, + vaxis.Key.scroll_lock => pardes.Key.scroll_lock, + vaxis.Key.pause => pardes.Key.pause, + vaxis.Key.menu => pardes.Key.menu, + vaxis.Key.f1...vaxis.Key.f25 => pardes.Key.f1 + (cp - vaxis.Key.f1), + // The keypad's own keys, which the kitty keyboard protocol tells + // apart, do what the keys they are named for do. + vaxis.Key.kp_left => pardes.Key.left, + vaxis.Key.kp_right => pardes.Key.right, + vaxis.Key.kp_up => pardes.Key.up, + vaxis.Key.kp_down => pardes.Key.down, + vaxis.Key.kp_page_up => pardes.Key.page_up, + vaxis.Key.kp_page_down => pardes.Key.page_down, + vaxis.Key.kp_home => pardes.Key.home, + vaxis.Key.kp_end => pardes.Key.end, + vaxis.Key.kp_insert => pardes.Key.insert, + vaxis.Key.kp_delete => pardes.Key.delete, + else => cp, + }; +} + +/// The key as the core's event, its text the key's own. +pub fn keyEvent(key: vaxis.Key) pardes.Event { + return .{ .key = .{ + .cp = mapKey(effCp(key)), + .text = key.text orelse "", + .ctrl = key.mods.ctrl, + .alt = key.mods.alt, + .shift = key.mods.shift, + } }; +} + +/// What a key typed inside a bracketed paste adds to it: its text, else a +/// tab, or a newline for Enter (the keypad's too) and Ctrl-J. +pub fn pasteBytes(key: vaxis.Key) []const u8 { + const text = key.text orelse ""; + if (text.len > 0) return text; + const cp = mapKey(effCp(key)); + if (cp == pardes.Key.tab) return "\t"; + if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n"; + return ""; +} + +/// A cell's style as vaxis draws it. +pub fn style(s: pardes.CellStyle) vaxis.Style { + return .{ + .fg = color(s.fg), + .bg = color(s.bg), + .bold = s.bold, + .dim = s.dim, + .italic = s.italic, + .blink = s.blink, + .reverse = s.reverse, + .invisible = s.invisible, + .strikethrough = s.strikethrough, + // The two underline enums name the same six styles. + .ul_style = switch (s.ul) { + inline else => |ul| @field(@FieldType(vaxis.Style, "ul_style"), @tagName(ul)), + }, + }; +} + +pub fn color(c: pardes.Color) vaxis.Color { + return switch (c) { + .default => .default, + .index => |i| .{ .index = i }, + .rgb => |rgb| .{ .rgb = rgb }, + }; +} + +test "F-keys, Insert and the keypad map to the core's keys" { + try std.testing.expectEqual(pardes.Key.f1 + 4, mapKey(vaxis.Key.f5)); + try std.testing.expectEqual(pardes.Key.f1 + 24, mapKey(vaxis.Key.f25)); + try std.testing.expectEqual(pardes.Key.insert, mapKey(vaxis.Key.insert)); + try std.testing.expectEqual(pardes.Key.up, mapKey(vaxis.Key.kp_up)); + try std.testing.expectEqual(pardes.Key.enter, keyEvent(.{ .codepoint = vaxis.Key.kp_enter }).key.cp); + try std.testing.expectEqual(@as(u21, 'a'), mapKey('a')); +} + +test "an event queue emptied in one batch lets every writer it held go on (build.zig's patch)" { + const io = std.testing.io; + const Q = vaxis.Queue(u8, 2); + var q: Q = .init(io); + try q.push(1); + try q.push(2); + const Writer = struct { + fn run(queue: *Q, byte: u8) !void { + try queue.push(byte); + } + }; + // Two writers waiting on the full queue, as a pane's pty reader and + // the frame ack's wake do under `yes`. + var a = try io.concurrent(Writer.run, .{ &q, 3 }); + defer a.cancel(io) catch {}; + var b = try io.concurrent(Writer.run, .{ &q, 4 }); + defer b.cancel(io) catch {}; + try io.sleep(.fromMilliseconds(20), .awake); + // The loop takes both at once: one pop from full, then one more. + try q.lock(); + _ = q.drain().?; + _ = q.drain().?; + q.unlock(); + var got: usize = 0; + var waited: usize = 0; + while (got < 2 and waited < 200) : (waited += 1) { + if (try q.tryPop() != null) got += 1 else try io.sleep(.fromMilliseconds(5), .awake); + } + try std.testing.expectEqual(@as(usize, 2), got); +} diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig index acc851c4..ef4ecfdd 100644 --- a/runtime/9p_io.zig +++ b/runtime/9p_io.zig @@ -1097,7 +1097,7 @@ const TempRuntime = struct { if (t.old) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); testing.allocator.free(v); - } else _ = @import("core").host_io.testUnsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("dev").host_io.testUnsetenv("XDG_RUNTIME_DIR"); std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&t.directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); } }; @@ -1133,7 +1133,7 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listene /// ChildEnv.exportVar for why). pub fn exportEnv(serial: u32, adopts: bool) void { const socket: ?[]const u8 = if (own_socket_len > 0) own_socket[0..own_socket_len] else null; - const ChildEnv = @import("core").host_io.ChildEnv; + const ChildEnv = @import("dev").host_io.ChildEnv; var pid_buf: [16]u8 = undefined; ChildEnv.exportVar("PARDES_PID", if (adopts) std.fmt.bufPrint(&pid_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable else null); // a u32 fits 16 if (socket) |own| { @@ -1164,10 +1164,10 @@ fn exportMount(sock_path: []const u8) void { if (mntgen and root.len > 0 and std.mem.startsWith(u8, base, sock_prefix) and std.mem.endsWith(u8, base, suffix) and base.len > sock_prefix.len + suffix.len) { var buf: [4096]u8 = undefined; if (std.fmt.bufPrint(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] })) |mount| { - return @import("core").host_io.ChildEnv.exportVar("PARDES_MOUNT", mount); + return @import("dev").host_io.ChildEnv.exportVar("PARDES_MOUNT", mount); } else |_| {} } - @import("core").host_io.ChildEnv.exportVar("PARDES_MOUNT", null); + @import("dev").host_io.ChildEnv.exportVar("PARDES_MOUNT", null); } pub const Client = struct { @@ -2719,16 +2719,16 @@ test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and u if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = @import("core").host_io.testUnsetenv(name); + } else _ = @import("dev").host_io.testUnsetenv(name); }; _ = setenv("NINE_MOUNT", "/mnt/9p", 1); _ = setenv("NINE_MNTGEN", "1", 1); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("core").host_io.ChildEnv.exported("PARDES_MOUNT").?); + try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("dev").host_io.ChildEnv.exported("PARDES_MOUNT").?); // A mount of another server (9ns --unix): not this session's. - _ = @import("core").host_io.testUnsetenv("NINE_MNTGEN"); + _ = @import("dev").host_io.testUnsetenv("NINE_MNTGEN"); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_MOUNT") == null); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_MOUNT") == null); } test "9P shell environment states being inside pardes apart from how to reach it" { @@ -2741,16 +2741,16 @@ test "9P shell environment states being inside pardes apart from how to reach it if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = @import("core").host_io.testUnsetenv(name); + } else _ = @import("dev").host_io.testUnsetenv(name); }; var dir: [sun_path_len:0]u8 = undefined; _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1); try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?); - _ = @import("core").host_io.testUnsetenv("XDG_RUNTIME_DIR"); + _ = @import("dev").host_io.testUnsetenv("XDG_RUNTIME_DIR"); _ = setenv("HOME", "/home/example", 1); try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); - _ = @import("core").host_io.testUnsetenv("HOME"); + _ = @import("dev").host_io.testUnsetenv("HOME"); try testing.expect(socketDir(&dir) == null); // The socket a listener keeps while it lives. @@ -2766,24 +2766,24 @@ test "9P shell environment states being inside pardes apart from how to reach it // parent, so a pardes started in one of its shells runs a session of // its own instead of handing its argument over. exportEnv(7, false); - try testing.expectEqualStrings(path, @import("core").host_io.ChildEnv.exported("PARDES_9P").?); - try testing.expectEqualStrings("7", @import("core").host_io.ChildEnv.exported("PARDES_PANE").?); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PID") == null); + try testing.expectEqualStrings(path, @import("dev").host_io.ChildEnv.exported("PARDES_9P").?); + try testing.expectEqualStrings("7", @import("dev").host_io.ChildEnv.exported("PARDES_PANE").?); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_PID") == null); exportEnv(8, true); - try testing.expectEqualStrings("8", @import("core").host_io.ChildEnv.exported("PARDES_PANE").?); - try testing.expectEqualStrings(own_pid, @import("core").host_io.ChildEnv.exported("PARDES_PID").?); + try testing.expectEqualStrings("8", @import("dev").host_io.ChildEnv.exported("PARDES_PANE").?); + try testing.expectEqualStrings(own_pid, @import("dev").host_io.ChildEnv.exported("PARDES_PID").?); // A session whose listener never came up is still the session this shell // is inside: the pid stands on its own, and only the address is missing. own_socket_len = 0; exportEnv(0, true); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_9P") == null); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PANE") == null); - try testing.expectEqualStrings(own_pid, @import("core").host_io.ChildEnv.exported("PARDES_PID").?); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, @import("dev").host_io.ChildEnv.exported("PARDES_PID").?); exportEnv(0, false); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_9P") == null); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PANE") == null); - try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PID") == null); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_PANE") == null); + try testing.expect(@import("dev").host_io.ChildEnv.exported("PARDES_PID") == null); } diff --git a/runtime/macos.zig b/runtime/macos.zig index f968597b..9475eb78 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -12,9 +12,9 @@ const colors = @import("core").colors; const look = @import("core").look; const message = pardes.Messages.Message; const layout = @import("core").layout; -const file_watch = @import("core").file_watch; -const host_io = @import("core").host_io; -const fonts = @import("core").fonts; // the shared fallback preference order +const file_watch = @import("dev").file_watch; +const host_io = @import("dev").host_io; +const fonts = @import("dev").fonts; // the shared fallback preference order const tracy = @import("core").tracy; // no-op unless -Dtracy names a checkout const selection_pipe = @import("core").selection_pipe; // start, Response and Tasks const crash = @import("runtime").crash; diff --git a/runtime/main.zig b/runtime/main.zig index 85b3e249..5d67ad60 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -1537,7 +1537,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("core").tui.Term = if (detach != null) .detached else .open; + var term: @import("dev").tui.Term = if (detach != null) .detached else .open; var detached = detach != null; upgrade.remember(args); if (upgrade.resumed) |*rec| { @@ -1583,7 +1583,7 @@ fn nativeMain(std_init: std.process.Init) !void { defer daemon.quit(); errdefer daemon.tellStubExit(1); switch (pardes.platform) { - .tui => @import("core").tui.run(init, opts, term) catch |err| switch (err) { + .tui => @import("dev").tui.run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not // an error trace. error.NoDevice => { @@ -1592,7 +1592,7 @@ fn nativeMain(std_init: std.process.Init) !void { }, else => return err, }, - .gui => try @import("core").gui.run(init, opts, detached), + .gui => try @import("dev").gui.run(init, opts, detached), .macos => unreachable, } daemon.tellStubExit(0); @@ -1692,8 +1692,8 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 { /// 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) { - .tui => try @import("core").tui.runClient(init, opts, path, name, far), - .gui => try @import("core").gui.runClient(init, opts, path, name, far), + .tui => try @import("dev").tui.runClient(init, opts, path, name, far), + .gui => try @import("dev").gui.runClient(init, opts, path, name, far), else => unreachable, } } @@ -1916,11 +1916,12 @@ test "tcgetattr writes nothing past a Zig termios" { test { _ = pardes.config.User; // The rest this block collected is collected where it lives now: the - // runtime's files by runtime/root.zig's test block, the core's (the - // frontends among them) by pardes.zig's. The window stays named: its - // C's allocator (ui_malloc and the rest) is gui.zig's. + // runtime's files by runtime/root.zig's test block, the core's by + // pardes.zig's, the devices' (the frontends) by dev/root.zig's. The + // window stays named: its C's allocator (ui_malloc and the rest) is + // gui.zig's. if (comptime pardes.platform == .tui) { - _ = @import("core").tui; + _ = @import("dev").tui; } - if (comptime pardes.platform == .gui) _ = @import("core").gui; + if (comptime pardes.platform == .gui) _ = @import("dev").gui; } diff --git a/runtime/root.zig b/runtime/root.zig index 86fd9a75..3297db5e 100644 --- a/runtime/root.zig +++ b/runtime/root.zig @@ -22,5 +22,5 @@ test { // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. - if (comptime @import("term_options").terminal and @import("pardes_config").platform == .gui) _ = @import("core").gui; + if (comptime @import("term_options").terminal and @import("pardes_config").platform == .gui) _ = @import("dev").gui; } diff --git a/src/Art.zig b/src/Art.zig deleted file mode 100644 index 2e2941c6..00000000 --- a/src/Art.zig +++ /dev/null @@ -1,591 +0,0 @@ -//! Glyph art: a picture drawn in a frame's cells with block, line and -//! letter glyphs in sixteen colours (the matcher is adapted from -//! caioluders/petsciinator). It is the frontends' (tui.zig always where the -//! terminal shows no pixels, gui.zig where a pane asks): the core hands a -//! picture as a `Placement` and never draws it, so its grid, `/screen`, is -//! the same on every client. One of these a frontend keeps the art of the -//! pictures it shows, while it shows them. -const std = @import("std"); -const colors = @import("colors.zig"); -const pardes = @import("pardes.zig"); - -const Art = @This(); -const Surface = pardes.Surface; -const Placement = pardes.Placement; -const Raster = pardes.Raster; -const RectPx = pardes.RectPx; - -grids: std.AutoHashMapUnmanaged(Key, Kept) = .empty, - -/// What a grid was made from: the picture, the part of it, the cells, and -/// how (fitted when the placement leaves its place to the frontend). -const Key = struct { key: u64, src: RectPx, cols: u16, rows: u16, fitted: bool, palette: Placement.Art.Palette, ascii: bool }; -const Kept = struct { grid: Grid, used: bool = true }; - -pub fn deinit(art: *Art, gpa: std.mem.Allocator) void { - var it = art.grids.valueIterator(); - while (it.next()) |kept| gpa.free(kept.grid.cells); - art.grids.deinit(gpa); -} - -/// `s` as this frontend draws it: every placement it shows as glyph art -/// (each one where it shows no `pixels`, else those whose pane asks for -/// art) painted into a copy of the frame made in `arena`; `s` itself when -/// there is none. `cell_h` is a cell's height in the frontend's pixels: a -/// sliver of a row (under half of it) has no art. -pub fn frame(art: *Art, gpa: std.mem.Allocator, arena: std.mem.Allocator, s: *const Surface, pixels: bool, cell_h: u32) !*const Surface { - var it = art.grids.valueIterator(); - while (it.next()) |kept| kept.used = false; - defer art.prune(gpa); - var out: ?*Surface = null; - for (s.placements.items) |place| { - if (pixels and !place.art.glyph) continue; - const grid = art.gridOf(gpa, place, cell_h) orelse continue; - const drawn = out orelse copy: { - const copy = try arena.create(Surface); - copy.* = s.*; - copy.cells = try arena.dupe(pardes.Cell, s.cells); - out = copy; - break :copy copy; - }; - // Fitted, the art is centred in its cells; else it fills them. - const offx = if (place.at == null) (place.dst.w - grid.cols) / 2 else 0; - const offy = if (place.at == null) (place.dst.h - grid.rows) / 2 else 0; - for (0..grid.rows) |cy| for (0..grid.cols) |cx| { - const cell = &grid.cells[cy * grid.cols + cx]; - const sx = place.dst.x + offx + cx; - const sy = place.dst.y + offy + cy; - if (sx >= drawn.cols or sy >= drawn.rows) continue; - drawn.set(@intCast(sx), @intCast(sy), cell.glyph[0..cell.glyph_len], switch (place.art.palette) { - .commodore => .{ .fg = .{ .rgb = commodore[cell.fg] }, .bg = .{ .rgb = commodore[cell.bg] } }, - .terminal => .{ .fg = .{ .index = cell.fg }, .bg = .{ .index = cell.bg } }, - }); - }; - } - return out orelse s; -} - -/// The placement's art, made the first frame it is drawn. -fn gridOf(art: *Art, gpa: std.mem.Allocator, place: Placement, cell_h: u32) ?Grid { - if (place.dst.w == 0 or place.dst.h == 0) return null; - if (place.at) |at| if (at.h * 2 < @as(u32, place.dst.h) * cell_h) return null; - const key: Key = .{ .key = place.key, .src = place.src, .cols = place.dst.w, .rows = place.dst.h, .fitted = place.at == null, .palette = place.art.palette, .ascii = place.art.ascii }; - if (art.grids.getPtr(key)) |hit| { - hit.used = true; - return hit.grid; - } - const colours = switch (place.art.palette) { - .commodore => commodore, - .terminal => colors.xterm[0..16].*, - }; - const grid = (if (place.at == null) - fitted(gpa, place.raster, place.src, place.dst.w, place.dst.h, colours, place.art.ascii) - else - renderRect(gpa, place.raster, place.src, place.dst.w, place.dst.h, colours, place.art.ascii)) catch return null; - if (grid.cells.len == 0) { - gpa.free(grid.cells); - return null; - } - art.grids.put(gpa, key, .{ .grid = grid }) catch { - gpa.free(grid.cells); - return null; - }; - return grid; -} - -/// Drop what this frame did not draw. -fn prune(art: *Art, gpa: std.mem.Allocator) void { - while (true) { - var it = art.grids.iterator(); - const stale = while (it.next()) |entry| { - if (!entry.value_ptr.used) break entry.key_ptr.*; - } else break; - gpa.free(art.grids.get(stale).?.grid.cells); - _ = art.grids.remove(stale); - } -} - -pub const commodore = [16][3]u8{ - .{ 0x00, 0x00, 0x00 }, // 0 black - .{ 0xff, 0xff, 0xff }, // 1 white - .{ 0x68, 0x37, 0x2b }, // 2 red - .{ 0x70, 0xa4, 0xb2 }, // 3 cyan - .{ 0x6f, 0x3d, 0x86 }, // 4 purple - .{ 0x58, 0x8d, 0x43 }, // 5 green - .{ 0x35, 0x28, 0x79 }, // 6 blue - .{ 0xb8, 0xc7, 0x6f }, // 7 yellow - .{ 0x6f, 0x4f, 0x25 }, // 8 orange - .{ 0x43, 0x39, 0x00 }, // 9 brown - .{ 0x9a, 0x67, 0x59 }, // 10 light red - .{ 0x44, 0x44, 0x44 }, // 11 dark grey - .{ 0x6c, 0x6c, 0x6c }, // 12 grey - .{ 0x9a, 0xd2, 0x84 }, // 13 light green - .{ 0x6c, 0x5e, 0xb5 }, // 14 light blue - .{ 0x95, 0x95, 0x95 }, // 15 light grey -}; - -const Colours = [16][3]u8; - -pub const Cell = struct { - glyph: [4]u8 = .{ ' ', 0, 0, 0 }, - glyph_len: u3 = 1, - fg: u4 = 1, - bg: u4 = 0, -}; - -pub const Grid = struct { cells: []Cell, cols: usize, rows: usize }; - -fn dist2(a: [3]u8, b: [3]u8) u32 { - const dr = @as(i32, a[0]) - b[0]; - const dg = @as(i32, a[1]) - b[1]; - const db = @as(i32, a[2]) - b[2]; - return @intCast(dr * dr + dg * dg + db * db); -} - -fn nearest(px: [3]u8, pal: Colours) u4 { - var best: u4 = 0; - var bestd: u32 = std.math.maxInt(u32); - for (pal, 0..) |c, i| { - const d = dist2(px, c); - if (d < bestd) { - bestd = d; - best = @intCast(i); - } - } - return best; -} - -// ---- glyph set: each is a codepoint + an 8x8 ink bitmap (bit y*8+x set = fg) ---- -const Glyph = struct { cp: u21, bits: u64 }; - -fn sextantCp(p: u6) u21 { - return switch (p) { - 0 => ' ', - 21 => 0x258C, // left half ▌ - 42 => 0x2590, // right half ▐ - 63 => 0x2588, // full block █ - else => blk: { - var off: u21 = @as(u21, p) - 1; - if (p > 21) off -= 1; - if (p > 42) off -= 1; - break :blk 0x1FB00 + off; // Symbols for Legacy Computing sextants - }, - }; -} - -// the 8x8 ink bitmap for a sextant pattern (2 cols x 3 rows of subcells). -fn sextantBits(p: u6) u64 { - var bits: u64 = 0; - var y: usize = 0; - while (y < 8) : (y += 1) { - const band = (y * 3) / 8; // 0,0,0,1,1,1,2,2 - var x: usize = 0; - while (x < 8) : (x += 1) { - const col: usize = if (x < 4) 0 else 1; - const sub: u6 = @intCast(band * 2 + col); - if ((p >> sub) & 1 != 0) bits |= @as(u64, 1) << @intCast(y * 8 + x); - } - } - return bits; -} - -// pack 8 row-bytes (bit x set, x=0 leftmost) into the 8x8 bitmap. -fn glyphMask(r: [8]u8) u64 { - var b: u64 = 0; - for (r, 0..) |row, y| b |= @as(u64, row) << @intCast(y * 8); - return b; -} - -// the horizontal half blocks and the ten 2x2 quadrants — sextants are 2x3, so they -// can't express an exact 4-row half or a quarter; these fill that gap. -const block_glyphs = [_]Glyph{ - .{ .cp = 0x2580, .bits = glyphMask(.{ 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0 }) }, // ▀ top half - .{ .cp = 0x2584, .bits = glyphMask(.{ 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff }) }, // ▄ bottom half - .{ .cp = 0x2598, .bits = glyphMask(.{ 0x0f, 0x0f, 0x0f, 0x0f, 0, 0, 0, 0 }) }, // ▘ TL - .{ .cp = 0x259d, .bits = glyphMask(.{ 0xf0, 0xf0, 0xf0, 0xf0, 0, 0, 0, 0 }) }, // ▝ TR - .{ .cp = 0x2596, .bits = glyphMask(.{ 0, 0, 0, 0, 0x0f, 0x0f, 0x0f, 0x0f }) }, // ▖ BL - .{ .cp = 0x2597, .bits = glyphMask(.{ 0, 0, 0, 0, 0xf0, 0xf0, 0xf0, 0xf0 }) }, // ▗ BR - .{ .cp = 0x259a, .bits = glyphMask(.{ 0x0f, 0x0f, 0x0f, 0x0f, 0xf0, 0xf0, 0xf0, 0xf0 }) }, // ▚ TL+BR - .{ .cp = 0x259e, .bits = glyphMask(.{ 0xf0, 0xf0, 0xf0, 0xf0, 0x0f, 0x0f, 0x0f, 0x0f }) }, // ▞ TR+BL - .{ .cp = 0x259b, .bits = glyphMask(.{ 0xff, 0xff, 0xff, 0xff, 0x0f, 0x0f, 0x0f, 0x0f }) }, // ▛ ¬BR - .{ .cp = 0x259c, .bits = glyphMask(.{ 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0 }) }, // ▜ ¬BL - .{ .cp = 0x2599, .bits = glyphMask(.{ 0x0f, 0x0f, 0x0f, 0x0f, 0xff, 0xff, 0xff, 0xff }) }, // ▙ ¬TR - .{ .cp = 0x259f, .bits = glyphMask(.{ 0xf0, 0xf0, 0xf0, 0xf0, 0xff, 0xff, 0xff, 0xff }) }, // ▟ ¬TL -}; - -// line/diagonal glyphs add the characteristic PETSCII "drawn" look on edges. -const line_glyphs = [_]Glyph{ - .{ .cp = 0x2500, .bits = glyphMask(.{ 0, 0, 0, 0xff, 0xff, 0, 0, 0 }) }, // ─ - .{ .cp = 0x2502, .bits = glyphMask(.{ 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18 }) }, // │ - .{ .cp = 0x253c, .bits = glyphMask(.{ 0x18, 0x18, 0x18, 0xff, 0xff, 0x18, 0x18, 0x18 }) }, // ┼ - .{ .cp = 0x2572, .bits = glyphMask(.{ 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }) }, // ╲ - .{ .cp = 0x2571, .bits = glyphMask(.{ 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }) }, // ╱ - .{ .cp = 0x2573, .bits = glyphMask(.{ 0x81, 0x42, 0x24, 0x18, 0x18, 0x24, 0x42, 0x81 }) }, // ╳ -}; - -const ascii_glyphs = [_]Glyph{ - .{ .cp = 0x21, .bits = 0x00180018183c3c18 }, // ! - .{ .cp = 0x22, .bits = 0x0000000000246666 }, // " - .{ .cp = 0x23, .bits = 0x0036367f367f3636 }, // # - .{ .cp = 0x24, .bits = 0x00183e603c067c18 }, // $ - .{ .cp = 0x25, .bits = 0x0063660c18336300 }, // % - .{ .cp = 0x26, .bits = 0x006e333b6e1c361c }, // & - .{ .cp = 0x27, .bits = 0x00000000000c1818 }, // ' - .{ .cp = 0x28, .bits = 0x0030180c0c0c1830 }, // ( - .{ .cp = 0x29, .bits = 0x000c18303030180c }, // ) - .{ .cp = 0x2a, .bits = 0x0000663cff3c6600 }, // * - .{ .cp = 0x2b, .bits = 0x000018187e181800 }, // + - .{ .cp = 0x2c, .bits = 0x0c18180000000000 }, // , - .{ .cp = 0x2d, .bits = 0x000000007e000000 }, // - - .{ .cp = 0x2e, .bits = 0x0018180000000000 }, // . - .{ .cp = 0x2f, .bits = 0x000103060c183060 }, // / - .{ .cp = 0x30, .bits = 0x001c36636b63361c }, // 0 - .{ .cp = 0x31, .bits = 0x007e181818181c18 }, // 1 - .{ .cp = 0x32, .bits = 0x007f660c3860633e }, // 2 - .{ .cp = 0x33, .bits = 0x003e63603c60633e }, // 3 - .{ .cp = 0x34, .bits = 0x0078307f33363c38 }, // 4 - .{ .cp = 0x35, .bits = 0x003e63603f03037f }, // 5 - .{ .cp = 0x36, .bits = 0x003e63633f03061c }, // 6 - .{ .cp = 0x37, .bits = 0x000c0c0c1830637f }, // 7 - .{ .cp = 0x38, .bits = 0x003e63633e63633e }, // 8 - .{ .cp = 0x39, .bits = 0x001e30607e63633e }, // 9 - .{ .cp = 0x3a, .bits = 0x0018180000181800 }, // : - .{ .cp = 0x3b, .bits = 0x0c18180000181800 }, // ; - .{ .cp = 0x3c, .bits = 0x006030180c183060 }, // < - .{ .cp = 0x3d, .bits = 0x00007e00007e0000 }, // = - .{ .cp = 0x3e, .bits = 0x00060c1830180c06 }, // > - .{ .cp = 0x3f, .bits = 0x001800181830633e }, // ? - .{ .cp = 0x40, .bits = 0x001e037b7b7b633e }, // @ - .{ .cp = 0x41, .bits = 0x006363637f63361c }, // A - .{ .cp = 0x42, .bits = 0x003f66663e66663f }, // B - .{ .cp = 0x43, .bits = 0x003c66030303663c }, // C - .{ .cp = 0x44, .bits = 0x001f36666666361f }, // D - .{ .cp = 0x45, .bits = 0x007f46161e16467f }, // E - .{ .cp = 0x46, .bits = 0x000f06161e16467f }, // F - .{ .cp = 0x47, .bits = 0x005c66730303663c }, // G - .{ .cp = 0x48, .bits = 0x006363637f636363 }, // H - .{ .cp = 0x49, .bits = 0x003c18181818183c }, // I - .{ .cp = 0x4a, .bits = 0x001e333330303078 }, // J - .{ .cp = 0x4b, .bits = 0x006766361e366667 }, // K - .{ .cp = 0x4c, .bits = 0x007f66460606060f }, // L - .{ .cp = 0x4d, .bits = 0x0063636b7f7f7763 }, // M - .{ .cp = 0x4e, .bits = 0x006363737b6f6763 }, // N - .{ .cp = 0x4f, .bits = 0x003e63636363633e }, // O - .{ .cp = 0x50, .bits = 0x000f06063e66663f }, // P - .{ .cp = 0x51, .bits = 0x703e73636363633e }, // Q - .{ .cp = 0x52, .bits = 0x006766363e66663f }, // R - .{ .cp = 0x53, .bits = 0x003c6630180c663c }, // S - .{ .cp = 0x54, .bits = 0x003c1818185a7e7e }, // T - .{ .cp = 0x55, .bits = 0x003e636363636363 }, // U - .{ .cp = 0x56, .bits = 0x001c366363636363 }, // V - .{ .cp = 0x57, .bits = 0x00367f6b6b636363 }, // W - .{ .cp = 0x58, .bits = 0x006363361c366363 }, // X - .{ .cp = 0x59, .bits = 0x003c18183c666666 }, // Y - .{ .cp = 0x5a, .bits = 0x007f664c1831637f }, // Z - .{ .cp = 0x5b, .bits = 0x003c0c0c0c0c0c3c }, // [ - .{ .cp = 0x5c, .bits = 0x00406030180c0603 }, // \\ - .{ .cp = 0x5d, .bits = 0x003c30303030303c }, // ] - .{ .cp = 0x5e, .bits = 0x0000000063361c08 }, // ^ - .{ .cp = 0x5f, .bits = 0xff00000000000000 }, // _ - .{ .cp = 0x60, .bits = 0x000000000030180c }, // ` - .{ .cp = 0x61, .bits = 0x006e333e301e0000 }, // a - .{ .cp = 0x62, .bits = 0x003b6666663e0607 }, // b - .{ .cp = 0x63, .bits = 0x003e6303633e0000 }, // c - .{ .cp = 0x64, .bits = 0x006e3333333e3038 }, // d - .{ .cp = 0x65, .bits = 0x003e037f633e0000 }, // e - .{ .cp = 0x66, .bits = 0x000f06061f06663c }, // f - .{ .cp = 0x67, .bits = 0x1f303e33336e0000 }, // g - .{ .cp = 0x68, .bits = 0x006766666e360607 }, // h - .{ .cp = 0x69, .bits = 0x003c1818181c0018 }, // i - .{ .cp = 0x6a, .bits = 0x3c66666060600060 }, // j - .{ .cp = 0x6b, .bits = 0x0067361e36660607 }, // k - .{ .cp = 0x6c, .bits = 0x003c18181818181c }, // l - .{ .cp = 0x6d, .bits = 0x006b6b6b7f370000 }, // m - .{ .cp = 0x6e, .bits = 0x00666666663b0000 }, // n - .{ .cp = 0x6f, .bits = 0x003e6363633e0000 }, // o - .{ .cp = 0x70, .bits = 0x0f063e66663b0000 }, // p - .{ .cp = 0x71, .bits = 0x78303e33336e0000 }, // q - .{ .cp = 0x72, .bits = 0x000f06066e3b0000 }, // r - .{ .cp = 0x73, .bits = 0x003f603e037e0000 }, // s - .{ .cp = 0x74, .bits = 0x00386c0c0c3f0c0c }, // t - .{ .cp = 0x75, .bits = 0x006e333333330000 }, // u - .{ .cp = 0x76, .bits = 0x001c366363630000 }, // v - .{ .cp = 0x77, .bits = 0x00367f6b6b630000 }, // w - .{ .cp = 0x78, .bits = 0x0063361c36630000 }, // x - .{ .cp = 0x79, .bits = 0x3f607e6363630000 }, // y - .{ .cp = 0x7a, .bits = 0x007e4c18327e0000 }, // z - .{ .cp = 0x7b, .bits = 0x007018180e181870 }, // { - .{ .cp = 0x7c, .bits = 0x0018181818181818 }, // | - .{ .cp = 0x7d, .bits = 0x000e18187018180e }, // } - .{ .cp = 0x7e, .bits = 0x0000000000003b6e }, // ~ -}; - -// the block glyph table (sextants + half/quadrant blocks + line glyphs), built at -// comptime, and the same set extended with the ASCII glyphs. `render(ascii=…)` picks. -const glyphs = blk: { - @setEvalBranchQuota(100000); - var list: [64 + block_glyphs.len + line_glyphs.len]Glyph = undefined; - var p: usize = 0; - while (p < 64) : (p += 1) list[p] = .{ .cp = sextantCp(@intCast(p)), .bits = sextantBits(@intCast(p)) }; - for (block_glyphs, 0..) |bg, i| list[64 + i] = bg; - for (line_glyphs, 0..) |lg, i| list[64 + block_glyphs.len + i] = lg; - break :blk list; -}; -const glyphs_ascii = glyphs ++ ascii_glyphs; - -fn matchCell(cell: *const [64][3]u8, pal: Colours, gset: []const Glyph) Cell { - var counts = @as([16]u16, @splat(0)); - for (cell) |px| counts[nearest(px, pal)] += 1; - var cand: [4]u4 = undefined; - var ncand: usize = 0; - var used = @as([16]bool, @splat(false)); - while (ncand < 4) : (ncand += 1) { - var best: ?usize = null; - for (counts, 0..) |c, i| { - if (used[i] or c == 0) continue; - if (best == null or c > counts[best.?]) best = i; - } - if (best) |bi| { - cand[ncand] = @intCast(bi); - used[bi] = true; - } else break; - } - if (ncand == 0) return .{}; // can't happen (64 pixels), but keep it total - if (ncand == 1) return encode(' ', cand[0], cand[0]); // solid color - - var best_cost: i64 = std.math.maxInt(i64); - var best = encode(' ', cand[0], cand[0]); - var fi: usize = 0; - while (fi < ncand) : (fi += 1) { - var bi: usize = 0; - while (bi < ncand) : (bi += 1) { - if (fi == bi) continue; - const fg = cand[fi]; - const bg = cand[bi]; - var dfg: [64]u32 = undefined; - var dbg: [64]u32 = undefined; - var base: i64 = 0; - for (cell, 0..) |px, p| { - dfg[p] = dist2(px, pal[fg]); - dbg[p] = dist2(px, pal[bg]); - base += dbg[p]; - } - for (gset) |g| { - var delta: i64 = 0; - var bits = g.bits; - while (bits != 0) : (bits &= bits - 1) { - const p: usize = @ctz(bits); - delta += @as(i64, dfg[p]) - @as(i64, dbg[p]); - } - const cost = base + delta; - if (cost < best_cost) { - best_cost = cost; - best = encode(g.cp, fg, bg); - } - } - } - } - return best; -} - -fn encode(cp: u21, fg: u4, bg: u4) Cell { - var c = Cell{ .fg = fg, .bg = bg }; - const n = std.unicode.utf8Encode(cp, &c.glyph) catch 1; - c.glyph_len = @intCast(n); - return c; -} - -/// `src` of `raster` fitted into `max_cols` x `max_rows` cells, its shape -/// kept: cells are about twice as tall as wide, so a row spans two widths. -fn fitted(gpa: std.mem.Allocator, raster: Raster, src: RectPx, max_cols: usize, max_rows: usize, pal: Colours, ascii: bool) !Grid { - if (src.w == 0 or src.h == 0 or max_cols == 0 or max_rows == 0) return .{ .cells = try gpa.alloc(Cell, 0), .cols = 0, .rows = 0 }; - var cols = max_cols; - var rows = (max_cols * src.h) / (2 * src.w); - if (rows > max_rows) { - rows = max_rows; - cols = (max_rows * 2 * src.w) / src.h; - } - cols = std.math.clamp(cols, 1, max_cols); - rows = std.math.clamp(rows, 1, max_rows); - return renderRect(gpa, raster, src, cols, rows, pal, ascii); -} - -/// The pixels of `src` laid over exactly `cols` x `rows` cells, whatever -/// their shape: a terminal's image fragment is already the size its cells -/// are. -fn renderRect(gpa: std.mem.Allocator, raster: Raster, src: RectPx, cols: usize, rows: usize, pal: Colours, ascii: bool) !Grid { - const iw: usize = raster.w; - const ih: usize = raster.h; - const rgba = raster.bytes(); - const x0: usize = @min(src.x, iw); - const y0: usize = @min(src.y, ih); - const sw: usize = @min(src.w, iw - x0); - const sh: usize = @min(src.h, ih - y0); - if (sw == 0 or sh == 0 or cols == 0 or rows == 0) return .{ .cells = try gpa.alloc(Cell, 0), .cols = 0, .rows = 0 }; - const gset: []const Glyph = if (ascii) &glyphs_ascii else &glyphs; - const cells = try gpa.alloc(Cell, cols * rows); - var cy: usize = 0; - while (cy < rows) : (cy += 1) { - const ry0 = y0 + cy * sh / rows; - const ry1 = @max(ry0 + 1, y0 + (cy + 1) * sh / rows); - var cx: usize = 0; - while (cx < cols) : (cx += 1) { - const rx0 = x0 + cx * sw / cols; - const rx1 = @max(rx0 + 1, x0 + (cx + 1) * sw / cols); - var cell: [64][3]u8 = undefined; - var sy: usize = 0; - while (sy < 8) : (sy += 1) { - const py0 = ry0 + sy * (ry1 - ry0) / 8; - const py1 = @max(py0 + 1, ry0 + (sy + 1) * (ry1 - ry0) / 8); - var sx: usize = 0; - while (sx < 8) : (sx += 1) { - const px0 = rx0 + sx * (rx1 - rx0) / 8; - const px1 = @max(px0 + 1, rx0 + (sx + 1) * (rx1 - rx0) / 8); - var rs: usize = 0; - var gs: usize = 0; - var bs: usize = 0; - var n: usize = 0; - var yy = py0; - while (yy < py1 and yy < ih) : (yy += 1) { - var xx = px0; - while (xx < px1 and xx < iw) : (xx += 1) { - const i = yy * raster.stride + xx * 4; - rs += rgba[i]; - gs += rgba[i + 1]; - bs += rgba[i + 2]; - n += 1; - } - } - if (n == 0) n = 1; - cell[sy * 8 + sx] = .{ @intCast(rs / n), @intCast(gs / n), @intCast(bs / n) }; - } - } - cells[cy * cols + cx] = matchCell(&cell, pal, gset); - } - } - return .{ .cells = cells, .cols = cols, .rows = rows }; -} - -test "sextant codepoints: blocks + endpoints" { - try std.testing.expectEqual(@as(u21, ' '), sextantCp(0)); - try std.testing.expectEqual(@as(u21, 0x2588), sextantCp(63)); - try std.testing.expectEqual(@as(u21, 0x258C), sextantCp(21)); - try std.testing.expectEqual(@as(u21, 0x2590), sextantCp(42)); - try std.testing.expectEqual(@as(u21, 0x1FB00), sextantCp(1)); // first sextant - try std.testing.expectEqual(@as(u21, 0x1FB3B), sextantCp(62)); // last sextant -} - -test "matchCell: solid color -> space on that bg" { - var cell: [64][3]u8 = undefined; - for (&cell) |*p| p.* = commodore[5]; // all green - const m = matchCell(&cell, commodore, &glyphs); - try std.testing.expectEqual(@as(u4, 5), m.bg); - try std.testing.expectEqual(@as(u8, ' '), m.glyph[0]); -} - -test "matchCell: clean top/bottom split picks the two colors" { - var cell: [64][3]u8 = undefined; - for (0..64) |p| cell[p] = if (p < 32) commodore[1] else commodore[6]; // white over blue - const m = matchCell(&cell, commodore, &glyphs); - // both palette colors must be chosen (in some fg/bg order) - const a = @as(u4, @min(m.fg, m.bg)); - const b = @as(u4, @max(m.fg, m.bg)); - try std.testing.expectEqual(@as(u4, 1), a); - try std.testing.expectEqual(@as(u4, 6), b); - // a clean top/bottom split must resolve to a real block glyph (the top-4-rows - // half block ▀), never a blank cell. - const cp = std.unicode.utf8Decode(m.glyph[0..m.glyph_len]) catch 0; - try std.testing.expectEqual(@as(u21, 0x2580), cp); -} - -test "ascii option only enables the ascii glyphs" { - // the ascii glyph codepoints must be reachable exactly when ascii is on. - var seen_block = false; - var seen_ascii = false; - for (glyphs) |g| if (g.cp == '#') { - seen_block = true; - }; - for (glyphs_ascii) |g| if (g.cp == '#') { - seen_ascii = true; - }; - try std.testing.expect(!seen_block); // '#' is an ascii-only glyph - try std.testing.expect(seen_ascii); - try std.testing.expectEqual(glyphs.len + ascii_glyphs.len, glyphs_ascii.len); -} - -test "ascii glyph is chosen when a cell has its exact shape" { - // a cell shaped exactly like the font 'S' (ink=white on black) must match 'S' - // with ascii on (cost 0), and fall back to some block glyph with ascii off. - const s_bits: u64 = 0x003c6630180c663c; - var cell: [64][3]u8 = undefined; - for (0..64) |p| cell[p] = if ((s_bits >> @intCast(p)) & 1 != 0) commodore[1] else commodore[0]; - const on = matchCell(&cell, commodore, &glyphs_ascii); - try std.testing.expectEqual(@as(u21, 'S'), std.unicode.utf8Decode(on.glyph[0..on.glyph_len]) catch 0); - const off = matchCell(&cell, commodore, &glyphs); - try std.testing.expect((std.unicode.utf8Decode(off.glyph[0..off.glyph_len]) catch 0) != 'S'); -} - -test "a tiny image fitted into cells makes a grid within bounds" { - const a = std.testing.allocator; - // 2x2 checker, RGBA - var img = @as([2 * 2 * 4]u8, @splat(0)); - img[0] = 255; - img[1] = 255; - img[2] = 255; - img[3] = 255; // (0,0) white - img[(3) * 4 + 0] = 255; - img[(3) * 4 + 1] = 255; - img[(3) * 4 + 2] = 255; - img[(3) * 4 + 3] = 255; // (1,1) white - const g = try fitted(a, .of(&img, 2, 2), .{ .w = 2, .h = 2 }, 10, 10, commodore, true); - defer a.free(g.cells); - try std.testing.expect(g.cols >= 1 and g.cols <= 10); - try std.testing.expect(g.rows >= 1 and g.rows <= 10); - try std.testing.expectEqual(g.cols * g.rows, g.cells.len); -} - -test "a frontend draws a placement as glyph art where it shows no pixels, or where its pane asks, and else leaves the frame be" { - const gpa = std.testing.allocator; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var art: Art = .{}; - defer art.deinit(gpa); - // 8x8 pixels, white over blue, over a 20x6 cell body at (2, 1). - var px: [8 * 8 * 4]u8 = undefined; - for (0..64) |i| px[i * 4 ..][0..4].* = if (i < 32) .{ 255, 255, 255, 255 } else .{ 0x35, 0x28, 0x79, 255 }; - var cells: [30 * 8]pardes.Cell = @splat(.{}); - var s: Surface = .{ .cols = 30, .rows = 8, .cells = &cells }; - defer s.placements.deinit(gpa); - try s.placements.append(gpa, .{ .pane = 0, .raster = .of(&px, 8, 8), .src = .{ .w = 8, .h = 8 }, .dst = .{ .x = 2, .y = 1, .w = 20, .h = 6 }, .key = Placement.keyOf(1, 0, 0) }); - - try std.testing.expectEqual(@as(*const Surface, &s), try art.frame(gpa, arena.allocator(), &s, true, 16)); - const drawn = try art.frame(gpa, arena.allocator(), &s, false, 16); - try std.testing.expect(drawn != &s); - try std.testing.expect(s.at(2, 1).default); - // Fitted at its shape (a square is half as many rows as columns) and - // centred: 12x6 cells from column 6. - try std.testing.expect(@constCast(drawn).at(5, 1).default); - try std.testing.expectEqual(pardes.Color{ .rgb = commodore[1] }, @constCast(drawn).at(6, 1).style.bg); - try std.testing.expect(!@constCast(drawn).at(17, 6).default); - try std.testing.expect(@constCast(drawn).at(18, 6).default); - try std.testing.expectEqual(@as(u32, 1), art.grids.count()); - - // The pane asks for art in the terminal's sixteen: indices, not rgb. - s.placements.items[0].art = .{ .glyph = true, .palette = .terminal }; - const asked = try art.frame(gpa, arena.allocator(), &s, true, 16); - try std.testing.expect(@constCast(asked).at(6, 1).style.bg == .index); - // What a frame did not draw is let go. - try std.testing.expectEqual(@as(u32, 1), art.grids.count()); - s.placements.clearRetainingCapacity(); - try std.testing.expectEqual(@as(*const Surface, &s), try art.frame(gpa, arena.allocator(), &s, false, 16)); - try std.testing.expectEqual(@as(u32, 0), art.grids.count()); - - // Placed exactly (a terminal's image row), it fills its cells, but not - // a sliver of a row. - try s.placements.append(gpa, .{ .pane = 0, .raster = .of(&px, 8, 8), .src = .{ .w = 8, .h = 4 }, .dst = .{ .x = 0, .y = 7, .w = 4, .h = 1 }, .at = .{ .w = 40, .h = 16 }, .key = Placement.keyOf(1, 2, 0) }); - const row = try art.frame(gpa, arena.allocator(), &s, false, 16); - for (0..4) |x| try std.testing.expect(!@constCast(row).at(@intCast(x), 7).default); - try std.testing.expect(@constCast(row).at(4, 7).default); - s.placements.items[0].at.?.h = 7; - try std.testing.expectEqual(@as(*const Surface, &s), try art.frame(gpa, arena.allocator(), &s, false, 16)); -} diff --git a/src/Core.zig b/src/Core.zig index 9ba448be..ffc60360 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -1344,7 +1344,7 @@ fn sayShellFailure(p: *Pardes, id: u8, err: anyerror) void { /// The program the shell's `#!` names that is not there, in `out`. fn missingInterpreter(bin: []const u8, out: []u8) ?[]const u8 { - const Shell = @import("host_io.zig").Shell; + const Shell = @import("dev").host_io.Shell; var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; return Shell.missingInterpreter(Shell.find(bin, &buf) orelse return null, out); } diff --git a/src/Effect.zig b/src/Effect.zig index 344034e2..420bb8e3 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -8,7 +8,7 @@ const tape = @import("tape.zig"); const panes = @import("panes.zig"); const ctlfs = @import("ninep/tree.zig"); const filesystem = @import("fs.zig"); -const host_io = @import("host_io.zig"); +const host_io = @import("dev").host_io; const exec = @import("exec.zig"); const lsp = @import("lsp/lsp.zig"); const Stream = @import("Stream.zig"); diff --git a/src/Handover.zig b/src/Handover.zig index b8491978..7e71fff6 100644 --- a/src/Handover.zig +++ b/src/Handover.zig @@ -679,7 +679,7 @@ test "a handover under a runtime directory too long for a window's socket is ref _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); } else { - _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); + _ = @import("dev").host_io.testUnsetenv("XDG_RUNTIME_DIR"); }; // The ledger's case, past 490 bytes, and one past sun_path alone. for ([_]usize{ 600, 100 }) |n| { diff --git a/src/Kind.zig b/src/Kind.zig index b4e04d6d..021d0247 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -23,7 +23,7 @@ const tape = @import("tape.zig"); const surface = @import("surface.zig"); const views = @import("views.zig"); const Addon = @import("Addon.zig"); -const host_io = @import("host_io.zig"); +const host_io = @import("dev").host_io; pub const Loaded = Addon.Loaded; pub const LoadedWord = Addon.LoadedWord; pub const loadedOf = Addon.loadedOf; diff --git a/src/Output.zig b/src/Output.zig index 8f49fa4e..f748f949 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -19,7 +19,7 @@ const File = panes.File; const Builtin = builtins.registry.Builtin(); -const fonts = if (builtins.capabilities.font_picker) @import("fonts.zig") else struct {}; +const fonts = if (builtins.capabilities.font_picker) @import("dev").fonts else struct {}; pub const Origin = union(enum) { cmd: Builtin, diff --git a/src/Stream.zig b/src/Stream.zig index abdf9afa..e94ac58d 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -1088,7 +1088,7 @@ fn work(io: std.Io, job: *Job, ctx: ?*anyopaque, sink: Sink) void { // ---- tests ---- -const host_io = @import("host_io.zig"); +const host_io = @import("dev").host_io; const testing = std.testing; /// The shell's half, in a test: perform the `search` effect on a real diff --git a/src/builtins.zig b/src/builtins.zig index 02718ff0..a44afb98 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1182,7 +1182,7 @@ pub const Term = struct { if (arg.len > 0) { var why: [320]u8 = undefined; // 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| { + if (pardes.tape.value(.shell, @import("dev").host_io.Shell.refusal, .{ arg[0..@min(arg.len, 200)], &why })) |refused| { var said: pardes.Kind.Buf(340) = .{}; return c.p.reportFailure(c.id, said.print("Term: {s}", .{refused})); } diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index f299a39d..54ce5c1f 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -238,7 +238,7 @@ pub fn run(p: *Pardes, id: usize, command: []const u8) void { .token = selection_pipe.newToken(), // What a pane's command is given: $PARDES_MOUNT, $PARDES_9P, // $PARDES_PID, $winid as the Edit's pane. - .env = @import("host_io.zig").commandEnv(arena, pane.serial, !p.opts.nested) catch &.{}, + .env = @import("dev").host_io.commandEnv(arena, pane.serial, !p.opts.nested) catch &.{}, }; keep = true; p.pipe.edit_run = pd; diff --git a/src/exec.zig b/src/exec.zig index f2fb30d4..0a831a85 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -1025,7 +1025,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] return p.setMessage(v.active, said.print("Shell: the default again, {s} ($SHELL, else /bin/sh)", .{config.defaultShell()[0..@min(config.defaultShell().len, 256)]})); } var why: [320]u8 = undefined; - if (pardes.tape.value(.shell, @import("host_io.zig").Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { + if (pardes.tape.value(.shell, @import("dev").host_io.Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { var text: pardes.Kind.Buf(340) = .{}; return p.reportFailure(v.active, text.print("Shell: {s}", .{refused})); } diff --git a/src/file_watch.zig b/src/file_watch.zig deleted file mode 100644 index 9bb59683..00000000 --- a/src/file_watch.zig +++ /dev/null @@ -1,963 +0,0 @@ -//! Native file-watch state and the mark/reconcile transaction shared by the -//! TTY and SDL hosts. Their event loops still own blocking waits, wake -//! coalescing, and retry scheduling; this file owns the identical synchronous -//! operation each wake performs. Text buffers already own the bytes whose hash -//! is their generation. A kind's pane (a PDF) uses metadata which changes for -//! in-place and rename-over saves, reading its file only when it changed. -//! -//! Two kernels, one transaction: inotify on linux (and FreeBSD 15's, the -//! same events), kqueue on macos. `init`, `wait`, `stop`, `drain`, `markDir` -//! and `unmarkDir` are the whole of that difference, and nothing above them -//! knows which one it is on. -const std = @import("std"); -const builtin = @import("builtin"); -/// libc: inotify and kqueue, which std.Io does not have. -const libc = std.c; -const linux = std.os.linux; -const pardes = @import("pardes.zig"); -const colors = @import("colors.zig"); -const filesystem = @import("fs.zig"); -const message = pardes.Messages.Message; - -pub const Identity = struct { - inode: std.Io.File.INode, - size: u64, - mtime_ns: i96, - ctime_ns: i96, - - pub fn eql(a: Identity, b: Identity) bool { - return std.meta.eql(a, b); - } -}; - -/// The last disk generation accepted by a native shell. Text panes already -/// need their bytes, so their exact content hash is cheapest. A kind's pane -/// uses metadata, its file read only once that moved (a PDF can be large). -pub const Generation = union(enum) { - text: u64, - kind: ?Identity, -}; - -/// Whether a kind's file is still the bytes its pane opened from. -fn sameBytes(core: *pardes.Pardes, pane: *const pardes.Pane, path: []const u8) bool { - const k = pane.addon orelse return false; - if (k.opened == 0) return false; - const bytes = filesystem.read(core, path) catch return false; - defer core.gpa.free(bytes); - return std.hash.Wyhash.hash(0, bytes) == k.opened; -} - -fn kindPath(pane: *const pardes.Pane) ?[]const u8 { - const k = pane.addon orelse return null; - return if (k.path.len > 0) k.path else null; -} - -/// One native directory mark, plus what macos needs beside it. -/// -/// `wd` is an inotify wd on linux and an open EVTONLY directory descriptor on -/// macos. Either way it marks the CONTAINING directory, because editor-style -/// rename-over saves replace the file inode. -/// -/// `file_wd` and `kq` exist only on macos, and only because a kqueue directory -/// filter reports changes to the DIRECTORY — entries added, removed, renamed — -/// and never a write to a file already inside it. inotify's CLOSE_WRITE covers -/// that from the directory mark; kqueue has no equivalent, so an in-place save -/// needs a second filter on the file itself. `kq` is the queue both filters -/// live on, kept here so `reloadPane` can re-arm the file filter after a -/// rename-over gave the pathname a new inode, without every caller between it -/// and a host having to carry the descriptor. -/// -/// `generation` is the reconciled disk snapshot; Restore establishes this -/// baseline without replacing its saved buffer. Serial rejects reused slots. -pub const Watch = struct { - wd: c_int, - file_wd: c_int = -1, - kq: c_int = -1, - serial: u32, - generation: Generation, - /// The path last read while watched (its hash): its going away later is - /// a deletion to say, where a path never there (a pane renamed to a new - /// name) is not. - existed: ?u64 = null, -}; - -/// The final slot is the one non-pane watched payload: the active ThemeFile. -/// Sharing the table also shares directory descriptors correctly when a user -/// happens to open that .zon as an ordinary document. -pub const theme_slot = pardes.MAX_PANES; -pub const Table = [theme_slot + 1]?Watch; - -/// Whether this OS has a watcher at all. Off it every entry point below -/// returns the inert answer: `watchPane` installs nothing, so `watches` stays -/// empty and `reloadPane` returns false for every slot. The core then keeps its -/// own record of what was asked and simply never gets a `file_changed`, which -/// is what a host with no watcher has always done here. -pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd or builtin.os.tag == .macos; - -/// The wake filter's `ident` on macos. `ident` is a directory descriptor for -/// every other filter on this queue, and no descriptor is `maxInt(usize)`, so -/// nothing can collide with it. -const wake_ident: usize = std.math.maxInt(usize); - -/// Create the descriptor a host waits on, and the ONE place the difference -/// between the two kernels is spelled. -/// -/// linux: an inotify instance; a mark is a wd added to it. -/// macos: a kqueue; a mark is an EVFILT_VNODE filter whose `ident` is an open -/// directory descriptor, plus the one EVFILT_USER filter registered here that -/// `stop` triggers to end a parked `wait`. -/// -/// `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` (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 -/// queue. -/// -/// -1 when there is no watcher to make, which every entry point below reads as -/// "mark nothing". -pub fn init(polled: bool) c_int { - switch (builtin.os.tag) { - .linux => return libc.inotify_init1(if (polled) - linux.IN.CLOEXEC | linux.IN.NONBLOCK - else - linux.IN.CLOEXEC), - // FreeBSD's IN_CLOEXEC and IN_NONBLOCK are its O_ flags. - .freebsd => return libc.inotify_init1(if (polled) 0x00100000 | 0x4 else 0x00100000), - .macos => { - const kq = libc.kqueue(); - if (kq < 0) return -1; - const changes = [_]libc.Kevent{.{ - .ident = wake_ident, - .filter = libc.EVFILT.USER, - .flags = libc.EV.ADD | libc.EV.CLEAR, - .fflags = 0, - .data = 0, - .udata = 0, - }}; - var events: [1]libc.Kevent = undefined; - if (libc.kevent(kq, &changes, 1, &events, 0, null) < 0) { - _ = libc.close(kq); - return -1; - } - return kq; - }, - else => return -1, - } -} - -/// Park until a marked directory changes. False ends the watcher: `stop` was -/// called, or the queue died. -/// -/// 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 -/// (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 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; - if (fd < 0) return false; - const none = [_]libc.Kevent{}; - var events: [8]libc.Kevent = undefined; - while (true) { - const n = libc.kevent(fd, &none, 0, &events, events.len, null); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - return false; - } - if (n == 0) continue; - for (events[0..@intCast(n)]) |event| { - if (event.filter == libc.EVFILT.USER) return false; - } - return true; - } -} - -/// Wake a host parked in `wait` so it returns BEFORE the descriptor it is -/// parked on is closed. A no-op on linux, where cancelling the future reading -/// that descriptor is what ends the watcher. -pub fn stop(fd: c_int) void { - if (comptime builtin.os.tag != .macos) return; - if (fd < 0) return; - const changes = [_]libc.Kevent{.{ - .ident = wake_ident, - .filter = libc.EVFILT.USER, - .flags = 0, - .fflags = libc.NOTE.TRIGGER, - .data = 0, - .udata = 0, - }}; - var events: [1]libc.Kevent = undefined; - _ = libc.kevent(fd, &changes, 1, &events, 0, null); -} - -/// Consume every pending edge without blocking, for a host that found the -/// descriptor ready in its own `poll(2)` rather than parking a thread on it. -/// True when at least one of them was a directory change. -/// -/// DRAINED TO EMPTY on both kernels, and for the same reason: the descriptor is -/// level-triggered, so a queue left partly full makes the next `poll` return -/// ready immediately, and each of those rounds is a whole pump. -pub fn drain(fd: c_int) bool { - if (fd < 0) return false; - switch (builtin.os.tag) { - .linux, .freebsd => { - var buf: [4096]u8 = undefined; - var seen = false; - while (libc.read(fd, &buf, buf.len) > 0) seen = true; - return seen; - }, - .macos => { - const none = [_]libc.Kevent{}; - const now: libc.timespec = .{ .sec = 0, .nsec = 0 }; - var events: [16]libc.Kevent = undefined; - var seen = false; - while (true) { - const n = libc.kevent(fd, &none, 0, &events, events.len, &now); - if (n <= 0) return seen; - for (events[0..@intCast(n)]) |event| { - if (event.filter != libc.EVFILT.USER) seen = true; - } - if (n < events.len) return seen; - } - }, - else => return false, - } -} - -/// Install the kernel mark on `dir_z` and return its handle, or -1. -/// -/// The handle is an inotify wd on linux and an open directory descriptor on -/// macos, and BOTH have to answer "the same directory twice is the same -/// handle": `watchPane`'s sharing loop compares handles to decide when the last -/// user of a mark is gone, and `Watch` keeps no path to compare instead. -/// inotify does that deduplication itself. On macos it is done here, by device -/// and inode, because each EVFILT_VNODE filter needs a descriptor of its own. -fn markDir(fd: c_int, dir_z: [:0]const u8, watches: *const Table) c_int { - switch (builtin.os.tag) { - .linux, .freebsd => { - // CLOSE_WRITE coalesces one writer's writes; MOVED_TO and CREATE - // cover rename-over and delete-then-recreate saves; DELETE and - // MOVED_FROM a file going away, said at once (File.deleted), not - // when something else next changes in the directory. - const mask = linux.IN.CLOSE_WRITE | linux.IN.MOVED_TO | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_FROM | linux.IN.ONLYDIR; - return libc.inotify_add_watch(fd, dir_z, mask); - }, - .macos => { - // EVTONLY is the point of the descriptor: it marks the directory - // without counting as a reference that would keep an unmounting - // volume busy. DIRECTORY is inotify's ONLYDIR. - const dir_fd = libc.open(dir_z, .{ - .ACCMODE = .RDONLY, - .EVTONLY = true, - .CLOEXEC = true, - .DIRECTORY = true, - }, @as(libc.mode_t, 0)); - if (dir_fd < 0) return -1; - var want: libc.Stat = undefined; - if (libc.fstat(dir_fd, &want) != 0) { - _ = libc.close(dir_fd); - return -1; - } - for (watches) |other| { - const candidate = other orelse continue; - var have: libc.Stat = undefined; - if (libc.fstat(candidate.wd, &have) != 0) continue; - if (have.dev != want.dev or have.ino != want.ino) continue; - _ = libc.close(dir_fd); - return candidate.wd; - } - // What a DIRECTORY filter reports is its entries changing, which - // is a rename-over or a delete-then-recreate — MOVED_TO and CREATE - // above. It does NOT report a write to a file already inside it, - // which is what CLOSE_WRITE covers there; `markFile` is that half. - // RENAME and DELETE here are the marked directory itself going - // away. - // - // EV_CLEAR is not optional: without it the filter stays triggered - // once it has fired and every `wait` returns immediately forever. - const changes = [_]libc.Kevent{.{ - .ident = @intCast(dir_fd), - .filter = libc.EVFILT.VNODE, - .flags = libc.EV.ADD | libc.EV.CLEAR, - .fflags = libc.NOTE.WRITE | libc.NOTE.RENAME | libc.NOTE.DELETE, - .data = 0, - .udata = 0, - }}; - var events: [1]libc.Kevent = undefined; - if (libc.kevent(fd, &changes, 1, &events, 0, null) < 0) { - _ = libc.close(dir_fd); - return -1; - } - return dir_fd; - }, - else => return -1, - } -} - -/// The other half of a macos mark: the filter on the watched FILE, which is the -/// only thing that reports an in-place save. -1 when there is no file there yet -/// — a path that does not exist is still worth marking the directory for, and -/// the create arrives on that mark. -/// -/// Not deduplicated, unlike the directory: two panes on the same file are two -/// slots that each want their own wake, and a file filter has exactly one user. -fn markFile(kq: c_int, path_z: [:0]const u8) c_int { - if (comptime builtin.os.tag != .macos) return -1; - const file_fd = libc.open(path_z, .{ - .ACCMODE = .RDONLY, - .EVTONLY = true, - .CLOEXEC = true, - }, @as(libc.mode_t, 0)); - if (file_fd < 0) return -1; - // EXTEND and ATTRIB beside WRITE because an append and a truncate-in-place - // are both saves, and DELETE/RENAME because losing this inode is how a - // rename-over reaches the pane whose file it replaced. - const changes = [_]libc.Kevent{.{ - .ident = @intCast(file_fd), - .filter = libc.EVFILT.VNODE, - .flags = libc.EV.ADD | libc.EV.CLEAR, - .fflags = libc.NOTE.WRITE | libc.NOTE.EXTEND | libc.NOTE.ATTRIB | - libc.NOTE.RENAME | libc.NOTE.DELETE | libc.NOTE.REVOKE, - .data = 0, - .udata = 0, - }}; - var events: [1]libc.Kevent = undefined; - if (libc.kevent(kq, &changes, 1, &events, 0, null) < 0) { - _ = libc.close(file_fd); - return -1; - } - return file_fd; -} - -/// Re-point a live mark's file filter at whatever the pathname is NOW. Called -/// from `reloadPane`, because a rename-over leaves the old filter on an inode -/// that no longer answers to this name and a later in-place save would then -/// wake nobody. A no-op off macos, where the directory mark covers both cases -/// by itself and there is no second filter to move. -fn remarkFile(live: *Watch, path: ?[]const u8) void { - if (comptime builtin.os.tag != .macos) return; - if (live.kq < 0) return; - const watched = filesystem.localPath(path orelse return) orelse return; - var path_buf: [4096:0]u8 = undefined; - if (watched.len >= path_buf.len) return; - @memcpy(path_buf[0..watched.len], watched); - path_buf[watched.len] = 0; - // Mark first, compare second. There is no `stat` in std.c on this target — - // only `fstat` — and opening the path is what tells us both whether it is - // there and which inode it is now. - const fresh = markFile(live.kq, path_buf[0..watched.len :0]); - if (fresh < 0) return; // nothing at that name now; keep whatever we had - if (live.file_wd >= 0) { - var have: libc.Stat = undefined; - var want: libc.Stat = undefined; - // Same inode as the filter already on it? Then that one still reports - // this file and the registration just made is a duplicate to drop. - if (libc.fstat(live.file_wd, &have) == 0 and libc.fstat(fresh, &want) == 0 and - have.dev == want.dev and have.ino == want.ino) - { - _ = libc.close(fresh); - return; - } - _ = libc.close(live.file_wd); - } - live.file_wd = fresh; -} - -/// Drop one slot's marks. The DIRECTORY mark goes only when its last slot is -/// gone — several panes share it — while the file filter has exactly one user -/// and always goes. On macos a filter dies with the descriptor it was -/// registered against, so the close IS the removal. -fn unmark(fd: c_int, old: Watch, drop_dir: bool) void { - if (comptime builtin.os.tag == .macos) { - if (old.file_wd >= 0) _ = libc.close(old.file_wd); - } - if (!drop_dir) return; - switch (builtin.os.tag) { - .linux, .freebsd => _ = libc.inotify_rm_watch(fd, old.wd), - .macos => _ = libc.close(old.wd), - else => {}, - } -} - -/// Mark or unmark the pathname in `slot`: a pane's id, `theme_slot` or a -/// shader's. Panes in the same directory share an inotify descriptor, so -/// removing one pane drops the kernel mark only after its last user -/// disappears. -pub fn watchPane( - fd: c_int, - watches: *Table, - slot: usize, - path: ?[]const u8, - serial: u32, - generation: Generation, -) void { - if (comptime !supported) return; - if (fd < 0) return; - if (watches[slot]) |old| { - var shared = false; - for (watches, 0..) |other, i| { - const candidate = other orelse continue; - if (i != slot and candidate.wd == old.wd) shared = true; - } - watches[slot] = null; - unmark(fd, old, !shared); - } - const declared_path = path orelse return; - const watched_path = filesystem.localPath(declared_path) orelse return; - // The path may lie in a mount this editor serves, and marking it is a - // stat and a lookup out there: the turn goes out with them. - pardes.turn.yield(); - defer pardes.turn.back(); - const stat = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), watched_path, .{}) catch null; - const dir = if (stat != null and stat.?.kind == .directory) watched_path else std.Io.Dir.path.dirname(watched_path) orelse "."; - var dir_buf: [4096:0]u8 = undefined; - if (dir.len >= dir_buf.len) return; - @memcpy(dir_buf[0..dir.len], dir); - dir_buf[dir.len] = 0; - const wd = markDir(fd, dir_buf[0..dir.len :0], watches); - if (wd < 0) return; - watches[slot] = .{ .wd = wd, .kq = fd, .serial = serial, .generation = generation }; - // The file half, which only macos has and only for a path that exists yet. - if (comptime builtin.os.tag == .macos) { - if (watches[slot]) |*live| remarkFile(live, declared_path); - } -} - -/// Every pane's mark dropped (a Restore's old core, a test's end). -pub fn unwatchAll(fd: c_int, watches: *Table) void { - for (0..pardes.MAX_PANES) |id| watchPane(fd, watches, @intCast(id), null, 0, .{ .text = 0 }); -} - -/// Reconcile one marked pane. A true result requests an immediate second pass: -/// a kind's pathname changed between the stat before its pane reopened and -/// the stat after, so committing either identity would lose a generation. -pub fn reloadPane( - core: *pardes.Pardes, - io: std.Io, - watches: *Table, - id: usize, - announce: bool, -) bool { - const watched = watches[id] orelse return false; - const pane = core.panes[id] orelse return false; - if (pane.serial != watched.serial) return false; - - // Re-point the macos file filter at whatever this pathname is now, BEFORE - // deciding anything: a rename-over left the old filter on a dead inode, and - // the next in-place save would otherwise wake nobody. A no-op elsewhere, - // and a no-op here too when the inode has not moved. - if (comptime builtin.os.tag == .macos) { - if (watches[id]) |*live| remarkFile(live, if (pane.file) |f| f.path else kindPath(pane)); - } - - if (pane.file) |file| { - const bytes = filesystem.read(core, file.path) catch |err| { - // Gone from under the pane: said once, the text kept. - if (err == error.FileNotFound and watched.existed == std.hash.Wyhash.hash(0, file.path)) pardes.panes.File.deleted(core, @intCast(id)); - return false; - }; - if (watches[id]) |*live| live.existed = std.hash.Wyhash.hash(0, file.path); - defer core.gpa.free(bytes); - const hash = std.hash.Wyhash.hash(0, bytes); - switch (watched.generation) { - .text => |accepted| if (accepted == hash) return false, - .kind => {}, - } - // The pane holds the disk's text already (a Zerox twin saved, its - // other twin watching the same file): nothing reloaded, nothing said. - if (std.mem.eql(u8, file.content, bytes)) { - if (watches[id]) |*live| if (live.serial == watched.serial) { - live.generation = .{ .text = hash }; - }; - return false; - } - if (!core.reloadWatchedFile(@intCast(id), bytes)) return false; - const current = core.panes[id] orelse return false; - if (current.serial != watched.serial) return false; - const current_file = current.file orelse return false; - if (!std.mem.eql(u8, current_file.content, bytes)) return false; - if (watches[id]) |*live| { - if (live.serial == watched.serial) - live.generation = .{ .text = hash }; - } - if (announce) { - var msg_buf: [256]u8 = undefined; - core.setMessage(id, message.stamp(&msg_buf, "reloaded", current_file.path)); - } - return false; - } - - const path = kindPath(pane) orelse return false; - const before = identify(io, path) catch return false; - switch (watched.generation) { - .kind => |accepted| if (accepted) |identity| { - if (identity.eql(before)) return false; - } else if (sameBytes(core, pane, path)) { - // Armed over the bytes the pane opened: nothing to reload - // (opening it again doubled every PDF's open). Changed between - // the open and the arm, it reloads. - if (watches[id]) |*live| if (live.serial == watched.serial) { - live.generation = .{ .kind = before }; - }; - return false; - }, - .text => {}, - } - // Its kind reads the file again (Kind.fileChanged): on the tape, no bytes. - if (!core.reloadWatchedFile(@intCast(id), &.{})) return false; - const current = core.panes[id] orelse return false; - if (current.serial != watched.serial) return false; - const current_path = kindPath(current) orelse return false; - const after = identify(io, current_path) catch return true; - if (!before.eql(after)) return true; - if (watches[id]) |*live| { - if (live.serial == watched.serial) - live.generation = .{ .kind = after }; - } - if (announce) { - var msg_buf: [256]u8 = undefined; - core.setMessage(id, message.stamp(&msg_buf, "reloaded", current_path)); - } - return false; -} - -/// Install the directory mark before reconciling the open bytes/path. This -/// closes the drain-time race without requiring another filesystem event. -pub fn applyEffect( - core: *pardes.Pardes, - io: std.Io, - fd: c_int, - watches: *Table, - id: u8, - on: bool, - mode: pardes.WatchMode, -) bool { - var path: ?[]const u8 = null; - var serial: u32 = 0; - var generation: Generation = .{ .text = 0 }; - if (on) if (core.panes[id]) |pane| { - serial = pane.serial; - if (pane.file) |file| { - path = file.path; - generation = .{ .text = std.hash.Wyhash.hash(0, file.content) }; - } else if (kindPath(pane)) |kind_path| { - path = kind_path; - generation = .{ .kind = null }; - } - }; - watchPane(fd, watches, id, path, serial, generation); - if (on and mode == .baseline_disk) if (watches[id]) |*watched| { - const pane = core.panes[id] orelse return false; - const file = pane.file orelse return reloadPane(core, io, watches, id, false); - const bytes = filesystem.read(core, file.path) catch return false; - defer core.gpa.free(bytes); - watched.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }; - watched.existed = std.hash.Wyhash.hash(0, file.path); - return false; - }; - // A text armed over its open's bytes, read just now (its content that - // read's very buffer, unedited): the file still what it was before that - // read (the same inode, size and times) needs no reading again. - if (on) if (watches[id]) |*watched| if (core.panes[id]) |pane| if (pane.file) |file| if (filesystem.localPath(file.path)) |native| { - const at = std.hash.Wyhash.hash(0, native); - for (filesystem.last_reads) |r| if (r.path == at and r.bytes == file.content.ptr and r.len == file.content.len and file.revision == 0) { - const now = identify(io, file.path) catch break; - if (!now.eql(r.file)) break; - watched.existed = std.hash.Wyhash.hash(0, file.path); - return false; - }; - }; - return on and watches[id] != null and reloadPane(core, io, watches, id, false); -} - -/// Reconcile every mark after a coalesced directory wake. -pub fn reloadChanged( - core: *pardes.Pardes, - io: std.Io, - gpa: std.mem.Allocator, - watches: *Table, -) bool { - var retry = false; - for (watches[0..pardes.MAX_PANES], 0..) |slot, id| { - if (slot != null) retry = reloadPane(core, io, watches, id, true) or retry; - } - if (watches[theme_slot] != null) - retry = reloadTheme(core, gpa, watches, true) or retry; - return retry; -} - -/// Stop the old theme watch, synchronously load the requested snapshot, then -/// install its parent-directory mark and reconcile once to close the read -> -/// watch race. Returns true only when that reconciliation wants another pass. -pub fn applyThemeEffect( - core: *pardes.Pardes, - gpa: std.mem.Allocator, - fd: c_int, - watches: *Table, - generation: u32, - on: bool, -) bool { - watchPane(fd, watches, theme_slot, null, 0, .{ .text = 0 }); - if (!on) return false; - const request = colors.themeFileRequest(core, generation) orelse return false; - // What fails here is the ThemeFile write's failure too, which waits on - // this (the one-failure rule): late, as a Save's. - const pane = request.pane; - const bytes = filesystem.readFile(gpa, request.path) catch |err| { - colors.failThemeFile(core, generation, err); - core.noteLateFailure(pane); - return false; - }; - defer gpa.free(bytes); - if (!colors.loadThemeFile(core, generation, bytes)) { - core.noteLateFailure(pane); - return false; - } - const hash = std.hash.Wyhash.hash(0, bytes); - watchPane(fd, watches, theme_slot, request.path, generation, .{ .text = hash }); - if (watches[theme_slot] == null) return false; - return reloadTheme(core, gpa, watches, false); -} - -/// Re-read the one active theme file after a coalesced directory edge. The -/// generation advances only after a valid parse, so a malformed save never -/// replaces the last good colors or blesses bad bytes as the new baseline. -pub fn reloadTheme( - core: *pardes.Pardes, - gpa: std.mem.Allocator, - watches: *Table, - announce: bool, -) bool { - const watched = watches[theme_slot] orelse return false; - const request = colors.themeFileRequest(core, watched.serial) orelse return false; - // Same re-arm as reloadPane's, for the same reason: a .zon saved by rename - // moves the inode the file filter is on. - if (comptime builtin.os.tag == .macos) { - if (watches[theme_slot]) |*entry| remarkFile(entry, request.path); - } - const bytes = filesystem.readFile(gpa, request.path) catch |err| { - core.invalidate(); - colors.failThemeFile(core, watched.serial, err); - return false; - }; - defer gpa.free(bytes); - const hash = std.hash.Wyhash.hash(0, bytes); - switch (watched.generation) { - .text => |accepted| if (accepted == hash) return false, - .kind => unreachable, - } - if (!colors.loadThemeFile(core, watched.serial, bytes)) return false; - core.invalidate(); - const live = if (watches[theme_slot]) |*entry| entry else return false; - if (live.serial != watched.serial) return false; - live.generation = .{ .text = hash }; - if (announce) { - var msg_buf: [256]u8 = undefined; - core.setMessage(request.pane, message.stamp(&msg_buf, "reloaded theme", request.path)); - } - return false; -} - -pub fn identify(io: std.Io, path: []const u8) !Identity { - const native = filesystem.localPath(path) orelse return error.NonLocalPath; - pardes.turn.yield(); - defer pardes.turn.back(); - const stat = try @import("fs.zig").statPath(io, native, .{}); - if (stat.kind != .file) return error.NotFile; - return .{ - .inode = stat.inode, - .size = stat.size, - .mtime_ns = stat.mtime.nanoseconds, - .ctime_ns = stat.ctime.nanoseconds, - }; -} - -test "a restored file is watched again: one clean takes what its file became since the dump, one unsaved keeps its text" { - if (comptime !supported or !filesystem.platform_has_fs) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - for ([_]bool{ false, true }) |dirty| { - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "dumped\n" }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); - const source = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer source.deinit(); - const id: u8 = @intCast(source.freeSlot().?); - const opened = try pardes.panes.File.open(source, id, path, 0); - if (dirty) _ = pardes.ctlfs.pane.spliceBody(source, opened, 0, 0, "unsaved ").?; - try pardes.dump.dumpState(source); - // Changed on disk between the dump and its load. - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "changed since\n" }); - const core = try pardes.dump.initFromDump(gpa, .{ .tty_only = true }, source.dump_out.?); - defer core.deinit(); - const pane = core.panes[id].?; - const fd = init(true); - if (fd < 0) return error.NoWatcher; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer watchPane(fd, &watches, id, null, pane.serial, .{ .text = 0 }); - var armed = false; - while (core.nextEffect()) |effect| switch (effect) { - .watch => |watch| if (watch.pane == id and watch.on) { - _ = applyEffect(core, io, fd, &watches, id, watch.on, watch.mode); - armed = true; - }, - else => {}, - }; - try std.testing.expect(armed and watches[id] != null); - if (dirty) { - try std.testing.expectEqualStrings("unsaved dumped\n", pane.file.?.content); - try std.testing.expect(pane.file.?.disk_newer != null); - } else try std.testing.expectEqualStrings("changed since\n", pane.file.?.content); - } -} - -test "a Zerox twin's save wakes its other twin's watch, which says nothing: their text is the file's already" { - if (comptime !supported or !filesystem.platform_has_fs) return; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "twinned", .data = "before\n" }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/twinned", .{tmp.sub_path}); - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("before\n"); - core.gpa.free(pane.file.?.path); - pane.file.?.path = try core.gpa.dupe(u8, path); - try std.testing.expect(core.executeBuiltinLine(0, "Zerox")); - const twin: u8 = for (core.panes, 0..) |slot, id| { - if (id != 0) if (slot) |other| if (other.file != null) break @intCast(id); - } else return error.NoTwin; - const fd = init(true); - if (fd < 0) return error.NoWatcher; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer watchPane(fd, &watches, twin, null, core.panes[twin].?.serial, .{ .text = 0 }); - watchPane(fd, &watches, twin, path, core.panes[twin].?.serial, .{ .text = std.hash.Wyhash.hash(0, "before\n") }); - // Edited in the first and saved: the file is the twins' text now. - pardes.panes.File.setContent(core, &pane.file.?, try core.gpa.dupe(u8, "after\n")); - try tmp.dir.writeFile(io, .{ .sub_path = "twinned", .data = "after\n" }); - _ = reloadPane(core, io, &watches, twin, true); - const other = core.panes[twin].?; - try std.testing.expect(std.mem.indexOf(u8, other.msg[0..other.msg_len], "reloaded") == null); - try std.testing.expectEqualStrings("after\n", other.file.?.content); -} - -test "ordinary file watches still reconcile changes between open and watch" { - if (comptime !supported or !filesystem.platform_has_fs) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "opened\n" }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const id: u8 = @intCast(core.freeSlot().?); - const pane = try pardes.panes.File.open(core, id, path, 0); - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "changed before watch\n" }); - const fd = init(true); - if (fd < 0) return error.NoWatcher; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer watchPane(fd, &watches, id, null, pane.serial, .{ .text = 0 }); - var armed = false; - while (core.nextEffect()) |effect| switch (effect) { - .watch => |watch| if (watch.pane == id and watch.on) { - try std.testing.expectEqual(.reconcile, watch.mode); - try std.testing.expect(!applyEffect(core, io, fd, &watches, id, watch.on, watch.mode)); - armed = true; - }, - else => {}, - }; - try std.testing.expect(armed and watches[id] != null); - try std.testing.expectEqualStrings("changed before watch\n", pane.file.?.content); - try pardes.panes.File.undoStep(core, pane, true); - try std.testing.expectEqualStrings("opened\n", pane.file.?.content); -} - -test "a kind's pane whose file changed between its open and its watch opens again from it" { - if (comptime !supported or !filesystem.platform_has_fs) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "pic.ppm", .data = "opened\n" }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/pic.ppm", .{tmp.sub_path}); - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const id: u8 = @intCast(core.freeSlot().?); - _ = try pardes.Kind.open(core, id, pardes.Kind.test_kind.of(core), path, "opened\n"); - while (core.nextEffect()) |_| {} - const fd = init(true); - if (fd < 0) return error.NoWatcher; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer unwatchAll(fd, &watches); - // The file as it opened: armed, nothing opened again. - try std.testing.expect(!applyEffect(core, io, fd, &watches, id, true, .reconcile)); - try std.testing.expectEqual(std.hash.Wyhash.hash(0, "opened\n"), core.panes[id].?.addon.?.opened); - // Changed before the watch arms: opened again from it. - try std.testing.expect(!applyEffect(core, io, fd, &watches, id, false, .reconcile)); - try tmp.dir.writeFile(io, .{ .sub_path = "pic.ppm", .data = "changed before watch\n" }); - try std.testing.expect(!applyEffect(core, io, fd, &watches, id, true, .reconcile)); - try std.testing.expectEqual(std.hash.Wyhash.hash(0, "changed before watch\n"), core.panes[id].?.addon.?.opened); -} - -test "explicit OS directory watches refresh prefix-preserving listings" { - if (comptime !supported or !filesystem.platform_has_fs) return; - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "first", .data = "first\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; - var path_buf: [4102]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/n/os{s}", .{directory}); - const pane_id = core.freeSlot().?; - const pane = try pardes.panes.File.open(core, pane_id, path, 0); - const fd = init(true); - if (fd < 0) return error.NoWatcher; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer watchPane(fd, &watches, @intCast(pane_id), null, pane.serial, .{ .text = 0 }); - _ = applyEffect(core, std.testing.io, fd, &watches, @intCast(pane_id), true, .reconcile); - try std.testing.expect(watches[pane_id] != null); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "second", .data = "second\n" }); - _ = reloadChanged(core, std.testing.io, gpa, &watches); - try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "/second\n") != null); - var rows = std.mem.tokenizeScalar(u8, pane.file.?.content, '\n'); - while (rows.next()) |row| { - try std.testing.expect(std.mem.startsWith(u8, row, path)); - const bytes = try filesystem.read(core, row); - defer gpa.free(bytes); - try std.testing.expect(std.mem.endsWith(u8, bytes, "\n")); - } -} - -test "file identity changes for in-place and rename-over writes" { - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "a" }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); - const before = try identify(io, path); - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "longer" }); - const after = try identify(io, path); - try std.testing.expect(!before.eql(after)); - - // The dominant editor save shape keeps size/content arbitrary but swaps - // the inode. Keep this replacement the same length to prove identity does - // not rely on size changing. - try tmp.dir.writeFile(io, .{ .sub_path = "replacement", .data = "swap!!" }); - try tmp.dir.rename("replacement", tmp.dir, "watched", io); - const replaced = try identify(io, path); - try std.testing.expect(after.inode != replaced.inode); - try std.testing.expect(!after.eql(replaced)); -} - -test "theme watch reloads valid ZON and keeps the last theme across a bad save" { - if (comptime !supported) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - const base_len = try tmp.dir.realPath(io, &base_buf); - const path = try std.Io.Dir.path.join(gpa, &.{ base_buf[0..base_len], "mine.zon" }); - defer gpa.free(path); - - var first = pardes.themes[0]; - first.name = "watched"; - first.bg = .{ 1, 2, 3 }; - var first_zon: std.Io.Writer.Allocating = .init(gpa); - defer first_zon.deinit(); - try std.zon.stringify.serialize(first, .{ .whitespace = true }, &first_zon.writer); - try tmp.dir.writeFile(io, .{ .sub_path = "mine.zon", .data = first_zon.written() }); - - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - colors.requestThemeFile(core, 0, path); - const request = while (core.nextEffect()) |effect| switch (effect) { - .theme_file => |theme_file| break theme_file, - else => {}, - } else return error.MissingThemeFileEffect; - - const fd = init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer _ = applyThemeEffect(core, gpa, fd, &watches, 0, false); - try std.testing.expect(!applyThemeEffect( - core, - gpa, - fd, - &watches, - request.generation, - true, - )); - try std.testing.expectEqual(@as(?[3]u8, .{ 1, 2, 3 }), core.theme().bg); - try std.testing.expect(watches[theme_slot] != null); - - var second = first; - second.bg = .{ 9, 8, 7 }; - var second_zon: std.Io.Writer.Allocating = .init(gpa); - defer second_zon.deinit(); - try std.zon.stringify.serialize(second, .{ .whitespace = true }, &second_zon.writer); - try tmp.dir.writeFile(io, .{ .sub_path = "mine.zon", .data = second_zon.written() }); - try std.testing.expect(!reloadTheme(core, gpa, &watches, false)); - try std.testing.expectEqual(@as(?[3]u8, .{ 9, 8, 7 }), core.theme().bg); - - try tmp.dir.writeFile(io, .{ .sub_path = "mine.zon", .data = ".{ .name = " }); - try std.testing.expect(!reloadTheme(core, gpa, &watches, false)); - try std.testing.expectEqual(@as(?[3]u8, .{ 9, 8, 7 }), core.theme().bg); -} - -test "a watched file deleted wakes the watch at once, and its pane says so" { - if (comptime !supported or !filesystem.platform_has_fs or builtin.os.tag != .linux) return; - const io = std.testing.io; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "here\n" }); - var path_buf: [256]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/watched", .{tmp.sub_path}); - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const id: u8 = @intCast(core.freeSlot().?); - const pane = try pardes.panes.File.open(core, id, path, 0); - const fd = init(true); - if (fd < 0) return error.NoWatcher; - defer _ = libc.close(fd); - var watches: Table = @splat(null); - defer watchPane(fd, &watches, id, null, pane.serial, .{ .text = 0 }); - while (core.nextEffect()) |effect| switch (effect) { - .watch => |watch| if (watch.pane == id and watch.on) { - _ = applyEffect(core, io, fd, &watches, id, watch.on, watch.mode); - }, - else => {}, - }; - _ = drain(fd); - try tmp.dir.deleteFile(io, "watched"); - var pfd = [_]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }}; - try std.testing.expect(libc.poll(&pfd, 1, 1000) > 0); - _ = reloadChanged(core, io, gpa, &watches); - try std.testing.expect(pane.file.?.disk_gone); -} diff --git a/src/fonts.zig b/src/fonts.zig deleted file mode 100644 index 540e3a60..00000000 --- a/src/fonts.zig +++ /dev/null @@ -1,436 +0,0 @@ -//! The fonts installed on the machine: the list the picker shows (Output.zig), -//! the path a `Font ` resolves to (exec.zig), and the fallback faces a -//! window loads after its own (gui.zig, macos.zig). It is the whole seam, -//! because the core has no font and the shells have no builtin dispatch. -//! -//! It lives at src/ rather than under gui/ because two shells draw their own -//! text. It is compiled only behind `pardes.font_picker` (gui or macos), so -//! the tui binary never opens a font directory, and the browser has none to -//! open. -//! -//! No fontconfig and no CoreText. Enumerating fonts is a walk over a handful -//! of well-known directories, and the one thing the picker must know about -//! each face — whether every glyph has the same advance — is three small sfnt -//! reads. That avoids initializing a FreeType face for every file in the -//! directory, and it keeps the answer identical on both platforms: the shells -//! disagree about how to RASTERIZE a file, never about which files there are. -const std = @import("std"); -const builtin = @import("builtin"); -/// libc: the tests' scratch fonts, written raw into /tmp. -const libc = std.c; - -/// Where each platform keeps fonts. The `home` list is relative to $HOME (a -/// machine with no $HOME simply has neither). ponytail: the unix set is the -/// freedesktop list minus /usr/share/X11/fonts, whose legacy bitmap formats -/// are outside this TTF/OTF picker; XDG_DATA_DIRS is the general answer if -/// another font root becomes common. -/// -/// macOS keeps a third of its faces — Menlo and Courier among them — inside -/// `Supplemental`, which is an ordinary directory the walk would reach anyway; -/// it is named because the depth cap is the only thing that would stop it. -const system_dirs = switch (builtin.os.tag) { - .macos => [_][]const u8{ "/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts" }, - else => [_][]const u8{ "/usr/share/fonts", "/usr/local/share/fonts" }, -}; -const home_dirs = switch (builtin.os.tag) { - .macos => [_][]const u8{"Library/Fonts"}, - else => [_][]const u8{ ".local/share/fonts", ".fonts" }, -}; - -/// The same safety rails look.find has, for the same reason: this walk runs -/// INSIDE the keystroke that asked for it, so it must end whatever it is -/// pointed at. A font tree is shallow and wide (one directory per family), so -/// the depth cap is lower than find's. -/// -/// `max_fonts` is a MEMORY bound and nothing else (the work is bounded by -/// `max_steps`), and it is sized past any real machine: a desktop with the -/// Noto and Nerd Font sets has nearly a thousand monospace faces, and the list -/// is sorted AFTER the cut, so a cut list reads as complete with faces missing -/// out of its middle. -const max_fonts = 4096; -const max_steps = 20_000; -const max_depth = 8; - -pub const Font = struct { name: []const u8, path: []const u8 }; - -/// Optional fallback faces, in preference order after the always-available -/// embedded Adwaita Mono face. Keep text faces before symbol faces so ordinary -/// letters retain terminal-like metrics; DejaVu Sans is the final broad, -/// proportional safety net. -pub const fallback_names = [_][]const u8{ - "NotoSansMono-Regular", - "DejaVuSansMono", - "SymbolsNerdFont-Regular", - "NotoSansSymbols2-Regular", - "NotoSansSymbols-Regular", - "DejaVuSans", -}; - -/// Every monospace font installed, `{name, path}`, arena-owned and sorted by -/// name — or, when `want_name` is given, just the one that answers to it. -pub fn list(arena: std.mem.Allocator, want_name: ?[]const u8) []const Font { - if (want_name) |name| { - const wanted = [1][]const u8{name}; - return scan(arena, &wanted, true); - } - return scan(arena, null, true); -} - -/// The session's config's absolute font path belongs to the session's machine. -/// Resolve the same face by name on this machine, retaining the filename as a fallback. -pub fn fromSession(arena: std.mem.Allocator, path: []const u8, name: []const u8) ?Font { - if (name.len > 0) { - const matches = list(arena, name); - if (matches.len > 0) return matches[0]; - } - const base = std.Io.Dir.path.basename(path); - const stem = base[0 .. base.len - std.Io.Dir.path.extension(base).len]; - if (stem.len == 0 or std.mem.eql(u8, stem, name)) return null; - const matches = list(arena, stem); - return if (matches.len > 0) matches[0] else null; -} - -/// Installed members of `fallback_names`, returned in preference order. This -/// is runtime discovery only: no local font path or exploration result enters -/// the build, and a machine with none simply uses embedded Adwaita Mono. -pub fn fallbacks(arena: std.mem.Allocator) []const Font { - return scan(arena, &fallback_names, false); -} - -/// One bounded directory walk for the picker, one named font, or the fallback -/// chain. User-facing lists always require a fixed-pitch face, including an -/// exact `Font ` request. The fallback chain opts out deliberately so a -/// broad symbol face may fill glyphs the primary grid face does not contain. -fn scan( - arena: std.mem.Allocator, - wanted: ?[]const []const u8, - require_monospaced: bool, -) []const Font { - // From the arena, not the stack: 4096 faces of {name, path} is 128 KiB. An - // allocator that cannot spare it answers with the embedded face, like - // every other failure in here. - const found = arena.alloc(Font, max_fonts) catch return &.{}; - var found_len: usize = 0; - // The blocking single-threaded Io: the walk is synchronous, inside the - // keystroke, as look.find's is. - const io = std.Io.Threaded.global_single_threaded.io(); - const home: []const u8 = if (libc.getenv("HOME")) |h| std.mem.span(h) else ""; - var root_buf: [512]u8 = undefined; - var path_buf: [4096]u8 = undefined; - roots: for (0..system_dirs.len + home_dirs.len) |i| { - const root: []const u8 = if (i < system_dirs.len) - system_dirs[i] - else if (home.len == 0) - continue - else - std.fmt.bufPrint(&root_buf, "{s}/{s}", .{ std.mem.trimEnd(u8, home, "/"), home_dirs[i - system_dirs.len] }) catch continue; - var dir = std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }) catch continue; - defer dir.close(io); - // walkSelectively, not walk: descending is opt-in, which is the only - // way to express the depth cap at all (look.find, same reason) - var w = dir.walkSelectively(arena) catch continue; - defer w.deinit(); - var steps: usize = 0; - while (steps < max_steps and found_len < found.len) { - steps += 1; // an unreadable dir burns a step too, so it cannot spin - const e = (w.next(io) catch continue) orelse break; - if (e.kind == .directory) { - if (e.depth() < max_depth) w.enter(io, e) catch {}; - continue; - } - const ext = std.Io.Dir.path.extension(e.basename); - // .ttc is a collection: several cuts of one family in a single - // file, which is how macOS ships Menlo, Courier and a third of - // everything else. The probe below reads face 0 out of one, and - // the shell loading it takes the same face — see tableOffset. - if (!std.ascii.eqlIgnoreCase(ext, ".ttf") and - !std.ascii.eqlIgnoreCase(ext, ".otf") and - !std.ascii.eqlIgnoreCase(ext, ".ttc")) continue; - const name = e.basename[0 .. e.basename.len - ext.len]; - if (wanted) |names| { - var matches = false; - for (names) |candidate| { - if (std.mem.eql(u8, candidate, name)) { - matches = true; - break; - } - } - if (!matches) continue; - for (found[0..found_len]) |prior| { - if (std.mem.eql(u8, prior.name, name)) { - matches = false; - break; - } - } - if (!matches) continue; - } - // e.path points into the walker's own buffer and dies at the next - // next(), so the path is spelled out here and copied below - const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ root, e.path }, 0) catch continue; - if (require_monospaced and !monospaced(io, path)) continue; - found[found_len] = .{ - .name = arena.dupe(u8, name) catch break, - .path = arena.dupe(u8, path) catch break, - }; - found_len += 1; - if (wanted) |names| { - if (names.len == 1) return arena.dupe(Font, found[0..found_len]) catch &.{}; - if (found_len == names.len) break :roots; - } - } - } - if (wanted) |names| { - std.mem.sort(Font, found[0..found_len], names, struct { - fn rank(order: []const []const u8, name: []const u8) usize { - for (order, 0..) |candidate, i| - if (std.mem.eql(u8, candidate, name)) return i; - return order.len; - } - fn lt(order: []const []const u8, a: Font, b: Font) bool { - return rank(order, a.name) < rank(order, b.name); - } - }.lt); - } else { - // readdir order is undefined; sort so the picker is the same list twice - // running and n/N walks a font's own variants in a row - std.mem.sort(Font, found[0..found_len], {}, struct { - fn lt(_: void, a: Font, b: Font) bool { - return std.mem.lessThan(u8, a.name, b.name); - } - }.lt); - } - return arena.dupe(Font, found[0..found_len]) catch &.{}; -} - -/// Is every glyph in this font the same width? The grid is one advance for -/// every column, chosen once from 'M', so a proportional font in it has every -/// row a different length and the mouse pointing at the wrong character: the -/// picker lists only the faces that can be worn. -/// -/// Three reads and no allocation, which is why the walk can afford it per file: -/// the sfnt header and table directory, then `hhea`'s numberOfHMetrics, then -/// the start of `hmtx` — one {advance, lsb} pair per glyph. A font whose first -/// advances all agree is monospace. Zeros are skipped: .notdef and the -/// combining marks legitimately advance nothing, in any font. -/// -/// ponytail: the first 64 metrics, not all of them, so this is one 256-byte -/// read whatever the font's size. Those cover .notdef and the whole of basic -/// latin — the range a terminal is actually worn in — which also (deliberately) -/// keeps the CJK mono faces whose *later* glyphs are double-width, exactly the -/// fonts fontconfig calls "dual-width" and refuses. -fn monospaced(io: std.Io, path: []const u8) bool { - const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return false; - defer file.close(io); - // 12-byte header + one 16-byte record per table; 256 records is far more - // than any real font carries - var head: [12 + 16 * 256]u8 = undefined; - const n = file.readPositionalAll(io, &head, 0) catch return false; - if (n < 12) return false; - const hhea = tableOffset(head[0..n], "hhea") orelse return false; - const hmtx = tableOffset(head[0..n], "hmtx") orelse return false; - var hh: [36]u8 = undefined; - if ((file.readPositionalAll(io, &hh, hhea) catch return false) != hh.len) return false; - const metrics = std.mem.readInt(u16, hh[34..36], .big); - const k: usize = @min(@as(usize, metrics), 64); - if (k == 0) return false; - var mx: [64 * 4]u8 = undefined; - if ((file.readPositionalAll(io, mx[0 .. k * 4], hmtx) catch return false) != k * 4) return false; - var ref: u16 = 0; - for (0..k) |i| { - const adv = std.mem.readInt(u16, mx[i * 4 ..][0..2], .big); - if (adv == 0) continue; - if (ref == 0) ref = adv else if (adv != ref) return false; - } - return ref != 0; -} - -/// Where `tag`'s table starts, read out of an sfnt table directory. Called -/// twice per font, which is the only reason it is not inline up there. -fn tableOffset(head: []const u8, tag: *const [4]u8) ?u32 { - const dir = head[sfntBase(head) orelse return null ..]; - if (dir.len < 12) return null; - // 0x00010000 TrueType outlines, "OTTO" CFF ones, "true" the old Apple - // spelling. Anything else — a WOFF, a lie about its extension — is not an - // sfnt face this picker can inspect. - const ver = std.mem.readInt(u32, dir[0..4], .big); - if (ver != 0x00010000 and ver != 0x4F54544F and ver != 0x74727565) return null; - const num = std.mem.readInt(u16, dir[4..6], .big); - var i: usize = 0; - while (i < num and 12 + (i + 1) * 16 <= dir.len) : (i += 1) { - const rec = dir[12 + i * 16 ..][0..16]; - // Table offsets in a collection are from the start of the FILE, not - // from the directory that named them, so this needs no adjusting. - if (std.mem.eql(u8, rec[0..4], tag)) return std.mem.readInt(u32, rec[8..12], .big); - } - return null; -} - -/// Where the sfnt table directory begins. Zero for an ordinary font file; for -/// a `ttcf` collection, the offset of face 0 — the cut the file is named -/// after, and the one a shell asked for this path will load. A collection -/// whose first face lies past what was read has no answer here rather than a -/// guessed one. -fn sfntBase(head: []const u8) ?usize { - if (head.len < 12) return null; - if (!std.mem.eql(u8, head[0..4], "ttcf")) return 0; - if (head.len < 16) return null; - if (std.mem.readInt(u32, head[8..12], .big) == 0) return null; // numFonts - const base = std.mem.readInt(u32, head[12..16], .big); - return if (base + 12 <= head.len) base else null; -} - -/// A scratch font path only this process writes. Not a fixed name: `zig build -/// unit-test` compiles this module into two test binaries and runs them -/// CONCURRENTLY, so a shared path in /tmp is one test truncating the file -/// another is halfway through reading. -fn scratchFont(buf: *[64:0]u8, ext: []const u8) [:0]const u8 { - return std.fmt.bufPrintSentinel(buf, "/tmp/pardes-fonts-test-{d}{s}", .{ - @as(u32, @intCast(libc.getpid())), ext, - // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 - }, 0) catch unreachable; -} - -/// Write `bytes` where `monospaced` can read them back. -fn writeScratch(path: [:0]const u8, bytes: []const u8) !void { - const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(c_uint, 0o600)); - try std.testing.expect(fd >= 0); - defer _ = libc.close(fd); - try std.testing.expectEqual(@as(isize, @intCast(bytes.len)), libc.write(fd, bytes.ptr, bytes.len)); -} - -test "fallback discovery is unique and preserves candidate priority" { - for (fallback_names, 0..) |name, i| { - try std.testing.expect(name.len != 0); - for (fallback_names[0..i]) |prior| - try std.testing.expect(!std.mem.eql(u8, prior, name)); - } - - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const installed = fallbacks(arena_state.allocator()); - var previous: ?usize = null; - for (installed) |font| { - const rank = for (fallback_names, 0..) |name, i| { - if (std.mem.eql(u8, name, font.name)) break i; - } else return error.UnknownFallback; - if (previous) |p| try std.testing.expect(rank > p); - previous = rank; - } -} - -test "the picker lists every monospace face rather than the first max_fonts" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const installed = list(arena_state.allocator(), null); - // A canary, and only meaningful on a machine that HAS fonts: reaching the - // cap is the silent cut max_fonts is sized against. - try std.testing.expect(installed.len < max_fonts); - // ...and what it does return is sorted. - for (installed, 0..) |font, i| { - try std.testing.expect(font.name.len != 0); - if (i > 0) try std.testing.expect(!std.mem.lessThan(u8, font.name, installed[i - 1].name)); - } -} - -test "monospaced reads the advances out of a real sfnt layout" { - // A whole font in 92 bytes: the header, a two-record table directory, and - // an hhea + hmtx that between them say "three glyphs, all 600 units wide". - // Everything a real .ttf has that this does not (glyf, cmap, name) is - // exactly what the probe never reads, which is the property under test. - var f: [92]u8 = @splat(0); - std.mem.writeInt(u32, f[0..4], 0x00010000, .big); // sfnt version - std.mem.writeInt(u16, f[4..6], 2, .big); // numTables - @memcpy(f[12..16], "hhea"); - std.mem.writeInt(u32, f[20..24], 44, .big); // hhea at 44, 36 bytes long - @memcpy(f[28..32], "hmtx"); - std.mem.writeInt(u32, f[36..40], 80, .big); // hmtx right after it - std.mem.writeInt(u16, f[44 + 34 ..][0..2], 3, .big); // numberOfHMetrics - for (0..3) |i| std.mem.writeInt(u16, f[80 + i * 4 ..][0..2], 600, .big); - - var path_buf: [64:0]u8 = undefined; - const path = scratchFont(&path_buf, ".ttf"); - defer _ = libc.unlink(path); - try writeScratch(path, &f); - try std.testing.expect(monospaced(std.testing.io, path)); - - // ...and one glyph a different width makes it proportional - std.mem.writeInt(u16, f[80 + 4 ..][0..2], 1200, .big); - try writeScratch(path, &f); - try std.testing.expect(!monospaced(std.testing.io, path)); -} - -test "a ttc collection is read through its first face" { - // The same 92-byte font as above, moved 20 bytes down the file behind a - // `ttcf` header naming two faces. Table offsets stay absolute, which an - // "add the base" would silently break. - const base = 20; - var f: [base + 92]u8 = @splat(0); - @memcpy(f[0..4], "ttcf"); - std.mem.writeInt(u16, f[4..6], 1, .big); // majorVersion - std.mem.writeInt(u32, f[8..12], 2, .big); // numFonts - std.mem.writeInt(u32, f[12..16], base, .big); // face 0 lives here - std.mem.writeInt(u32, f[16..20], base, .big); // face 1, same tables - - const sfnt = f[base..]; - std.mem.writeInt(u32, sfnt[0..4], 0x00010000, .big); - std.mem.writeInt(u16, sfnt[4..6], 2, .big); - @memcpy(sfnt[12..16], "hhea"); - std.mem.writeInt(u32, sfnt[20..24], base + 44, .big); - @memcpy(sfnt[28..32], "hmtx"); - std.mem.writeInt(u32, sfnt[36..40], base + 80, .big); - std.mem.writeInt(u16, sfnt[44 + 34 ..][0..2], 3, .big); - for (0..3) |i| std.mem.writeInt(u16, sfnt[80 + i * 4 ..][0..2], 600, .big); - - var path_buf: [64:0]u8 = undefined; - const path = scratchFont(&path_buf, ".ttc"); - defer _ = libc.unlink(path); - try writeScratch(path, &f); - try std.testing.expect(monospaced(std.testing.io, path)); - - // A collection claiming no faces has no first one to read. - std.mem.writeInt(u32, f[8..12], 0, .big); - try writeScratch(path, &f); - try std.testing.expect(!monospaced(std.testing.io, path)); -} - -test "the walk finds this machine's monospace faces" { - // Not a fixture: the directory list is the entire platform-specific part - // of this file, and a wrong one produces an empty picker rather than an - // error. Every OS pardes draws its own text on ships a monospace face, so - // finding NONE means the walk is looking somewhere that does not exist. - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const found = list(arena_state.allocator(), null); - try std.testing.expect(found.len > 0); - for (found) |font| { - try std.testing.expect(font.name.len > 0); - try std.testing.expect(font.path[0] == '/'); - // The name is the stem, so the file it came from is always longer. - try std.testing.expect(std.Io.Dir.path.basename(font.path).len > font.name.len); - } - - // macOS ships Menlo, and ships it inside a .ttc. It is the one face this - // machine can be held to by name, and naming it here is what keeps the - // collection branch honest end to end: drop .ttc from the walk, or read a - // collection's directory at offset 0, and this is what notices. - if (comptime builtin.os.tag == .macos) { - const menlo = for (found) |font| { - if (std.mem.eql(u8, font.name, "Menlo")) break font; - } else return error.MenloMissing; - try std.testing.expect(std.mem.endsWith(u8, menlo.path, ".ttc")); - } -} - -test "the session's font config resolves the installed face despite another machine's path" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const alloc = arena.allocator(); - const installed = list(alloc, null); - if (installed.len == 0) return error.SkipZigTest; - const face = installed[0]; - const foreign = try std.fmt.allocPrint(alloc, "/other-machine/fonts/{s}", .{std.Io.Dir.path.basename(face.path)}); - const by_name = fromSession(alloc, foreign, face.name) orelse return error.MissingLocalFace; - try std.testing.expectEqualStrings(face.path, by_name.path); - const by_file = fromSession(alloc, foreign, "") orelse return error.MissingLocalFace; - try std.testing.expectEqualStrings(face.path, by_file.path); -} diff --git a/src/fs.zig b/src/fs.zig index d352866e..c249ed6d 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -60,7 +60,7 @@ const source_files = [_]Source{ .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, .{ .path = "src/9p.zig", .contents = @embedFile("runtime/9p.zig") }, .{ .path = "src/9p_io.zig", .contents = @embedFile("runtime/9p_io.zig") }, - .{ .path = "src/host_io.zig", .contents = @embedFile("host_io.zig") }, + .{ .path = "src/host_io.zig", .contents = @embedFile("dev/host_io.zig") }, .{ .path = "src/config.zig", .contents = @embedFile("config.zig") }, .{ .path = "src/main.zig", .contents = @embedFile("runtime/main.zig") }, .{ .path = "src/builtins.zig", .contents = @embedFile("builtins.zig") }, @@ -804,7 +804,7 @@ pub fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u /// it returned and what the file was before the read: a watch armed over a /// text whose content is that very buffer (file_watch.applyEffect) finds the /// disk the same without reading it again. -pub var last_reads: [8]struct { path: u64 = 0, bytes: [*]const u8 = undefined, len: usize = 0, file: @import("file_watch.zig").Identity = undefined } = @splat(.{}); +pub var last_reads: [8]struct { path: u64 = 0, bytes: [*]const u8 = undefined, len: usize = 0, file: @import("dev").file_watch.Identity = undefined } = @splat(.{}); var last_read: usize = 0; /// A 9P write of an Edit held while its commands run (Namespace.edit_hold). diff --git a/src/glide.zig b/src/glide.zig deleted file mode 100644 index 1c49d8e8..00000000 --- a/src/glide.zig +++ /dev/null @@ -1,466 +0,0 @@ -//! The view's glide (G6, anim 3, 9, 12): a frontend's own picture of a -//! scroll, on its own clock, from the frames it draws alone. Whatever -//! scrolls a text (a wheel's lines, Ctrl-d, a page, G, n, a Look) scrolls -//! the core at once, so every key and click acts on where the text is; the -//! frontend sees a body's first line move between two frames (Region.line) -//! and its picture follows there, critically damped (text never passes its -//! mark), every distance on the same law. The GUI draws it at the pixel; -//! the tty at whole rows (tui.zig's glideRows). Nothing here reaches back -//! into the core. - -const std = @import("std"); -const pardes = @import("pardes.zig"); -const config = @import("config.zig"); - -/// How far the rows moved is measured on the frame against the last drawn, -/// a line wrapped over several rows or a terminal's output included, and -/// the rows that left are kept to draw in the gap. A move past what the two -/// frames share (a page and more, G) has no rows between them to show: the -/// picture comes from the last frame's body as if it lay just past the new -/// one, one body away, so a jump of any length reads as one body's slide. -/// -/// The picture's motion is one system with its own state, integrated in -/// one place every frame (`Follow.advance`), and every scroll, whatever -/// made it, is an input into it (`Follow.kick`): it moves the target by the -/// rows the core moved and leaves the motion as it is. Inputs coming as a -/// stream (each like the last, at a steady spacing: a held key, a spun -/// wheel) feed it at the stream's own rate; an input into a resting view, -/// or against the way it moves, starts the spring from the speed it has; a -/// jump mid-glide adds its rows with the speed kept. -pub const Glide = struct { - /// The picture's lag behind the core's rows and its motion (rows). - follow: Follow = .{}, - now_ns: u64 = 0, - pane: usize = 0, - rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, - body_y: u16 = 0, - body_h: u16 = 0, - /// The way the last scroll went, and the body's rows before it. - dir: i8 = 0, - before: []pardes.Cell = &.{}, - /// The rows past the body's top (`above`) and bottom (`below`), nearest - /// first, `bw` cells each: what the gap shows while the picture lags. - above: []pardes.Cell = &.{}, - below: []pardes.Cell = &.{}, - nabove: u16 = 0, - nbelow: u16 = 0, - /// The core's lines a scroll moved, not yet measured; and what the - /// glide in flight has moved, in lines and in the picture's rows. A - /// wrapped line is several rows, and the thumb counts lines. - pending_lines: f32 = 0, - lines_moved: f32 = 0, - rows_moved: f32 = 0, - /// The caret's row as the last frame drew it, and whether the move - /// measured carried it with its line (a wheel's) or left it on its row - /// (a page, a held key's): the tty draws a carried caret with the rows. - caret_row: ?u16 = null, - caret_rides: bool = false, - /// Each body as the last frame showed it, by its pane: its serial, - /// first line, text and place, so a view that moved since is found - /// whatever moved it. - seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), - /// Each body's rows held at its top while it scrolls (a source's - /// sticky context rows, TreeContext), its frontend's to say: they do - /// not move, so a move is measured, and the rows that left are kept, - /// below them. - held: [pardes.MAX_PANES]u16 = @splat(0), - /// The last frame's cells, which a move is measured against. - last: []pardes.Cell = &.{}, - last_cols: u16 = 0, - last_rows: u16 = 0, - - /// The rows kept past each edge, in bodies, so a jump made while one - /// glides carries on from where it is: as far as the picture may lag. - pub const reach = Follow.reach; - - pub fn moving(glide: *const Glide) bool { - return glide.follow.moving(); - } - - pub fn stop(glide: *Glide) void { - glide.follow = .{ .at_ns = glide.follow.at_ns }; - glide.nabove = 0; - glide.nbelow = 0; - glide.pending_lines = 0; - glide.lines_moved = 0; - glide.rows_moved = 0; - } - - /// The glide's lag in the core's lines: its rows, scaled by the lines - /// they carried. - pub fn lagLines(glide: *const Glide) f32 { - if (glide.rows_moved == 0) return glide.follow.offset; - return glide.follow.offset * glide.lines_moved / glide.rows_moved; - } - - pub fn deinit(glide: *Glide, gpa: std.mem.Allocator) void { - gpa.free(glide.before); - gpa.free(glide.above); - gpa.free(glide.below); - gpa.free(glide.last); - } - - pub fn bw(glide: *const Glide) u16 { - return glide.rect.w -| config.GUTTER; - } - - /// The rules at this body's size: a tenth of a pixel is 5e-3 rows. - pub fn pace(glide: *const Glide) Follow.Pace { - return Follow.pace(@floatFromInt(glide.body_h), 5e-3); - } - - /// The frame about to be drawn, at `now_ns` on the frontend's clock: - /// the glide moves on to now, and a body whose first line moved since - /// the last frame (the same text in the same place) is measured against - /// that frame and kicks it. A terminal's view glides only under the - /// wheel (`wheeled`: its output scrolls it at every line, and that is no - /// glide); not one the frontend moves by the pixel (`direct`). One glide - /// at a time: the focused body's, else the one that moved most. - pub fn frame(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface, now_ns: u64, wheeled: ?usize, direct: ?usize) void { - glide.now_ns = now_ns; - defer glide.remember(gpa, surface); - if (glide.follow.moving()) { - glide.follow.advance(now_ns, glide.pace()); - if (glide.follow.offset == 0) { - glide.nabove = 0; - glide.nbelow = 0; - glide.lines_moved = 0; - glide.rows_moved = 0; - } - } - var pick: ?pardes.Region = null; - var delta: i64 = 0; - var shown: [pardes.MAX_PANES]bool = @splat(false); - for (surface.regionList()) |region| { - if (region.kind != .body or region.owner >= glide.seen.len) continue; - const id: usize = region.owner; - shown[id] = true; - const was = glide.seen[id]; - glide.seen[id] = .{ .serial = region.serial, .line = region.line, .doc = region.doc, .rect = region.rect }; - if (was.serial != region.serial or was.doc != region.doc or was.line == region.line) continue; - // The last frame drew this body where it is now: a pane that - // moved or was resized in the same step has no picture to glide - // from. - if (!std.meta.eql(was.rect, region.rect)) continue; - if (region.doc == 0 and wheeled != id) continue; - if (direct == id) continue; - const moved = @as(i64, region.line) - was.line; - if (pick) |best| if (best.active or (!region.active and @abs(moved) <= @abs(delta))) continue; - pick = region; - delta = moved; - } - for (&glide.seen, shown) |*seen, here| if (!here) { - seen.* = .{}; - }; - const body = pick orelse return; - const r = body.rect; - const rect: pardes.Rect = .{ .x = r.x -| config.GUTTER, .y = r.y, .w = r.w + config.GUTTER, .h = r.h }; - // A new pane or place: what was kept belongs to another picture. - if (glide.pane != body.owner or !std.meta.eql(glide.rect, rect)) glide.stop(); - glide.pane = body.owner; - glide.rect = rect; - glide.body_y = r.y; - glide.body_h = r.h; - const w = r.w; - if (w == 0 or r.h == 0 or glide.last_cols != surface.cols or glide.last_rows != surface.rows or - r.x + w > surface.cols or r.y + r.h > surface.rows) return glide.stop(); - // The body as the last frame drew it, which the move is measured from. - const n = @as(usize, w) * r.h; - if (glide.before.len < n) glide.before = gpa.realloc(glide.before, n) catch &.{}; - if (glide.before.len < n) return glide.stop(); - for (0..r.h) |row| @memcpy(glide.before[row * w ..][0..w], glide.last[(@as(usize, r.y) + row) * glide.last_cols + r.x ..][0..w]); - glide.dir = @intCast(std.math.sign(delta)); - glide.pending_lines += @floatFromInt(@abs(delta)); - glide.measure(gpa, surface); - } - - /// This frame's cells and caret, for the next frame's measure. - fn remember(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { - if (glide.last.len != surface.cells.len) { - gpa.free(glide.last); - glide.last = gpa.alloc(pardes.Cell, surface.cells.len) catch &.{}; - } - if (glide.last.len != surface.cells.len) { - glide.last_cols = 0; - return; - } - @memcpy(glide.last, surface.cells); - glide.last_cols = surface.cols; - glide.last_rows = surface.rows; - glide.caret_row = if (surface.cursor) |c| c.y else null; - } - - /// Finds how far the pane's body rows moved, `dir` rows at a time, by - /// the rows of `surface` against `before`; keeps the rows that left. - fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { - const w = glide.bw(); - const x0 = glide.rect.x + config.GUTTER; - if (w == 0 or glide.body_h == 0 or x0 + w > surface.cols or glide.body_y + glide.body_h > surface.rows or glide.before.len < @as(usize, w) * glide.body_h) return glide.stop(); - // The rows under the held ones (`held`) are what scrolls: `before` - // and the frame are compared, and kept, from there. - const top = @min(glide.held[glide.pane], glide.body_h -| 1); - const h = glide.body_h - top; - const now = struct { - fn row(s: *const pardes.Surface, x: u16, y: u16, n: u16) []const pardes.Cell { - return s.cells[@as(usize, y) * s.cols + x ..][0..n]; - } - }; - // The least shift under which the rows agree, but for a few: the - // cursor's line and its number's weight move with the scroll. The - // lines the core moved are tried first: unwrapped, they are the - // rows, and one pass over the body settles it (the search over - // every shift was 6 ms of the first frame of a page in Debug). - const agrees = struct { - fn at(gl: *const Glide, surf: *const pardes.Surface, x: u16, width: u16, height: u16, kk: u16) bool { - if (kk == 0 or kk + 3 > height) return false; - const allowed = @max(2, (height - kk) / 8); - var misses: usize = 0; - for (0..height - kk) |r| { - const rr: u16 = @intCast(r); - const held = @min(gl.held[gl.pane], gl.body_h -| 1); - const old_row = gl.before[@as(usize, held + if (gl.dir > 0) rr + kk else rr) * width ..][0..width]; - const new_row = now.row(surf, x, gl.body_y + held + if (gl.dir > 0) rr else rr + kk, width); - if (!sameRow(old_row, new_row)) { - misses += 1; - if (misses > allowed) return false; - } - } - return true; - } - }; - const guess: u16 = @intFromFloat(@min(glide.pending_lines, @as(f32, @floatFromInt(h)))); - // A body's lines or more: every row moved off, none in common. - var shift: u16 = if (guess >= h) 0 else if (agrees.at(glide, surface, x0, w, h, guess)) guess else found: for (1..h) |k| { - if (agrees.at(glide, surface, x0, w, h, @intCast(k))) break :found @intCast(k); - } else 0; - // Rows that disagree under every shift though the core moved a few - // lines: their colours changed as they moved (a paint arriving as a - // spin stops). Unwrapped, the rows moved are the lines: glide those - // (it landed from wherever it was, a snap at a spin's end). - if (shift == 0 and guess > 0 and guess < h) shift = guess; - // None in common: a body's move from the last frame's body, if the - // lines moved are that many (rows that merely changed, a small - // scroll the rows cannot show, land at once). - if (shift == 0 and glide.pending_lines + 3 < @as(f32, @floatFromInt(h))) return glide.stop(); - const far = shift == 0; - if (far) shift = h; - glide.caret_rides = !far and if (glide.caret_row) |old| if (surface.cursor) |c| - @as(i32, c.y) == @as(i32, old) - @as(i32, shift) * glide.dir - else - false else false; - glide.rows_moved += @floatFromInt(shift); - glide.lines_moved += glide.pending_lines; - glide.pending_lines = 0; - // The rows that left: past the top going down, the bottom going up. - if (!glide.ensure(gpa)) return glide.stop(); - const keep = if (glide.dir > 0) &glide.above else &glide.below; - const count = if (glide.dir > 0) &glide.nabove else &glide.nbelow; - const kept = @min(count.*, h * reach - shift); - std.mem.copyBackwards(pardes.Cell, keep.*[@as(usize, shift) * w ..][0 .. @as(usize, kept) * w], keep.*[0 .. @as(usize, kept) * w]); - for (0..shift) |i| { - const src_row: usize = top + if (glide.dir > 0) shift - 1 - i else h - shift + i; - @memcpy(keep.*[i * w ..][0..w], glide.before[src_row * w ..][0..w]); - } - count.* = kept + shift; - // What came into view is no longer past the other edge. - const other = if (glide.dir > 0) &glide.below else &glide.above; - const other_n = if (glide.dir > 0) &glide.nbelow else &glide.nabove; - // ...and after a jump, the rows past it are another place's. - const dropped = if (far) other_n.* else @min(other_n.*, shift); - std.mem.copyForwards(pardes.Cell, other.*[0 .. @as(usize, other_n.* - dropped) * w], other.*[@as(usize, dropped) * w ..][0 .. @as(usize, other_n.* - dropped) * w]); - other_n.* -= dropped; - // An input: the core's rows moved by as many (down positive). - glide.follow.kick(@as(f32, @floatFromInt(shift)) * @as(f32, @floatFromInt(glide.dir)), glide.now_ns, glide.pace()); - } - - pub fn ensure(glide: *Glide, gpa: std.mem.Allocator) bool { - const n = @as(usize, glide.bw()) * glide.body_h * reach; - inline for (.{ &glide.above, &glide.below }) |buffer| if (buffer.len < n) { - const grown = gpa.realloc(buffer.*, n) catch return false; - buffer.* = grown; - }; - return true; - } -}; - -pub fn sameRow(a: []const pardes.Cell, b: []const pardes.Cell) bool { - for (a, b) |x, y| { - if (x.default != y.default) return false; - if (x.default) continue; - if (!std.mem.eql(u8, x.grapheme(), y.grapheme()) or !std.meta.eql(x.style, y.style)) return false; - } - return true; -} - -/// A frame's length at 60 Hz, what a tick of the follow is clamped to. -const frame_ns: u64 = 16 * std.time.ns_per_ms; - -/// A view that follows its input (anim 9, 11): the picture's offset from -/// the core's position now (rows of text; negative, the picture still -/// shows what is above), its speed (rows a second), when it was last -/// integrated, and what has been feeding it. -pub const Follow = struct { - offset: f32 = 0, - speed: f32 = 0, - at_ns: u64 = 0, - /// The last inputs (down positive), their spacing, the last's time, and - /// how many came as one stream. - feed: struct { amount: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{}, - - /// How far the picture may lag, in bodies (a flick past that jumps); - /// how fast it may move, in bodies a second, so moving text stays - /// readable. - pub const reach = 2; - pub const bodies_per_s: f32 = 15; - /// Inputs this close, each the way the last went, are one stream. - pub const stream_ns = 150 * std.time.ns_per_ms; - /// The spring's natural frequency, rad/s: an arrival lands inside - /// 220 ms. - pub const omega: f32 = 51; - - /// What a view's size makes of the rules: the speed cap, the lag cap, - /// and the offset under which it is at rest (a tenth of a pixel, in - /// rows). - pub const Pace = struct { cap: f32, limit: f32, rest: f32 }; - - pub fn pace(body: f32, rest: f32) Pace { - return .{ .cap = body * bodies_per_s, .limit = body * reach, .rest = rest }; - } - - pub fn moving(follow: *const Follow) bool { - return follow.offset != 0 or follow.speed != 0; - } - - /// An input: the core moved `amount` (down positive). The picture now - /// lags by as much more, its speed as it was. - pub fn kick(follow: *Follow, amount: f32, now_ns: u64, p: Pace) void { - follow.advance(now_ns, p); - follow.offset = std.math.clamp(follow.offset - amount, -p.limit, p.limit); - const f = &follow.feed; - const like = f.count > 0 and (amount > 0) == (f.amount > 0) and now_ns -| f.last_ns < stream_ns; - if (like) { - const gap = now_ns -| f.last_ns; - f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2; - f.amount = (f.amount + amount) / 2; - f.count +|= 1; - } else f.* = .{ .amount = amount, .count = 1 }; - f.last_ns = now_ns; - } - - /// The system moved on to `now_ns`. Fed by a stream, at the stream's - /// rate (an input's amount over their spacing), held a lag `lead` - /// behind so a late input never finds it stopped and the stream's end - /// never runs it past its mark; else on the spring, critically damped, - /// from the speed it has. Never faster than `p.cap`. - pub fn advance(follow: *Follow, now_ns: u64, p: Pace) void { - const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| follow.at_ns, 2 * frame_ns))) / std.time.ns_per_s); - follow.at_ns = now_ns; - if (follow.offset == 0 and follow.speed == 0) return; - const toward: f32 = if (follow.offset < 0) 1 else -1; - const f = follow.feed; - if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) { - const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s); - const rate = @abs(f.amount) / gap; - const lead = @max(@abs(f.amount), rate / omega); - // ponytail: a gentle pull to the lead (a tenth an input), so the - // per-frame step varies by a tenth; a stream's own jitter beyond - // that shows. An estimate of the input clock if it ever matters. - // A slow stream's lag runs out before its next input: never - // faster than the spring's own pace from there (omega a unit of - // lag a second), so it eases onto the mark, not into it at speed. - const v = std.math.clamp(rate + 0.1 / gap * (@abs(follow.offset) - lead), 0, @min(p.cap, omega * @abs(follow.offset))); - const step = @min(v * dt, @abs(follow.offset)); - follow.offset += toward * step; - follow.speed = if (follow.offset == 0) 0 else toward * v; - return; - } - const x = follow.offset; - // Coming to rest from a stream: never faster than the spring's own - // pace from here (omega a unit of lag a second), so it eases in and - // does not pass its mark. - if (follow.speed * x < 0 and @abs(follow.speed) > omega * @abs(x)) follow.speed = std.math.sign(follow.speed) * omega * @abs(x); - const lead_v = follow.speed + omega * x; - const decay = @exp(-omega * dt); - var next = (x + lead_v * dt) * decay; - var speed = (follow.speed - omega * dt * lead_v) * decay; - if (@abs(next - x) > p.cap * dt) { - next = x + std.math.sign(next - x) * p.cap * dt; - speed = std.math.sign(next - x) * p.cap; - } - follow.offset = next; - follow.speed = speed; - if (@abs(next) < p.rest and @abs(speed) < 10 * p.rest) follow.* = .{ .at_ns = now_ns }; - } -}; - -test "a follow comes to rest without a snap: past its fastest frame each step is shorter, the last under a tenth of a pixel" { - // A flick's spin (a stream of notches, then nothing), one page, and - // notches slow enough that each lag runs out before the next (its - // stream must ease onto each mark, never pass it). - const p = Follow.pace(600, 0.1); - for ([_]struct { n: u16, gap_ms: u64 }{ .{ .n = 12, .gap_ms = 16 }, .{ .n = 1, .gap_ms = 16 }, .{ .n = 6, .gap_ms = 144 } }) |run| { - var f: Follow = .{}; - var now: u64 = std.time.ns_per_s; - for (0..run.n) |_| { - f.kick(if (run.n == 1) 600 else 25, now, p); - var waited: u64 = 0; - while (waited < run.gap_ms) : (waited += 8) { - now += 8 * std.time.ns_per_ms; - const was = f.offset; - f.advance(now, p); - // Toward its mark only, and onto it from under a pixel. - try std.testing.expect(f.offset <= 0 and f.offset >= was); - if (f.offset == 0) try std.testing.expect(-was <= 3 * p.rest); - } - } - var last: f32 = std.math.inf(f32); - var before = f.offset; - var frames: usize = 0; - var fastest: f32 = 0; - while (f.moving()) : (frames += 1) { - now += frame_ns; - f.advance(now, p); - const step = @abs(f.offset - before); - try std.testing.expect(@abs(f.offset) <= @abs(before)); - if (f.offset == 0) try std.testing.expect(step <= 3 * p.rest); - fastest = @max(fastest, step); - if (step < fastest) try std.testing.expect(step <= last); - last = step; - before = f.offset; - try std.testing.expect(frames < 120); - } - try std.testing.expect(last <= 0.1); - } -} - -test "a body scrolling under held rows (sticky context) is measured, and keeps the rows that left, below them" { - const gpa = std.testing.allocator; - // A body 10 rows high whose first 3 hold still (a source's context - // rows) while the lines under them scroll one. - var cells: [2][24 * 12]pardes.Cell = undefined; - var frames: [2]pardes.Surface = undefined; - for (&frames, &cells, [_]u16{ 10, 11 }) |*s, *c, first| { - @memset(c, .{}); - s.* = .{ .cols = 24, .rows = 12, .cells = c }; - s.addRegion(.{ .kind = .body, .owner = 0, .serial = 1, .rect = .{ .x = config.GUTTER, .y = 1, .w = 24 - config.GUTTER, .h = 10 }, .active = true, .line = first, .doc = 7 }); - for (0..3) |k| { - var buf: [8]u8 = undefined; - _ = s.print(config.GUTTER, @intCast(1 + k), 20, std.fmt.bufPrint(&buf, "ctx {d}", .{k}) catch unreachable, .{}); - } - for (3..10) |k| { - var buf: [8]u8 = undefined; - _ = s.print(config.GUTTER, @intCast(1 + k), 20, std.fmt.bufPrint(&buf, "L{d}", .{first + k - 3}) catch unreachable, .{}); - } - } - var glide: Glide = .{}; - defer glide.deinit(gpa); - glide.held[0] = 3; - glide.frame(gpa, &frames[0], std.time.ns_per_s, null, null); - glide.frame(gpa, &frames[1], std.time.ns_per_s + 16 * std.time.ns_per_ms, null, null); - // A row down, and the row that left is the first under the held ones, - // L10, not a held row. - try std.testing.expect(glide.follow.offset < -0.9); - try std.testing.expectEqual(@as(u16, 1), glide.nabove); - const w = glide.bw(); - try std.testing.expect(sameRow(glide.above[0..w], frames[0].cells[@as(usize, 1 + 3) * 24 + config.GUTTER ..][0..w])); -} diff --git a/src/gui/Trackpad.zig b/src/gui/Trackpad.zig deleted file mode 100644 index ef28d211..00000000 --- a/src/gui/Trackpad.zig +++ /dev/null @@ -1,142 +0,0 @@ -//! Mac trackpad policy, after AppKit decoding. Buttons use SDL's 1/2/3. -const std = @import("std"); -const Trackpad = @This(); - -fingers: usize = 0, -stream: ?u8 = null, -button: ?u8 = null, -forced: bool = false, -rotation: f32 = 0, -rotation_total: f32 = 0, -gesture: enum { none, pinch, rotate } = .none, -pinch_base: f32 = 0, -pinch_total: f32 = 1, - -pub fn countFingers(t: *Trackpad, count: usize) void { - if (count < 2 or t.fingers < 2) { - t.gesture = .none; - t.rotation_total = 0; - t.pinch_base = 0; - t.pinch_total = 1; - } - t.fingers = count; -} - -pub fn press(t: *Trackpad, stream: u8) u8 { - if (t.fingers == 0 or stream > 3) return stream; - t.stream = stream; - t.button = if (t.fingers >= 2) 2 else stream; - t.forced = false; - return t.button.?; -} - -pub fn release(t: *Trackpad, stream: u8) ?u8 { - if (t.stream != stream) return stream; - defer { - t.stream = null; - t.button = null; - t.forced = false; - } - return if (t.forced) null else t.button; -} - -/// The caller releases this button before issuing one Look click. The -/// physical release afterwards is swallowed, so it cannot become a chord. -pub fn force(t: *Trackpad, stage: f32) ?u8 { - if (stage < 2 or t.forced or t.button == null or t.button == 3) return null; - t.forced = true; - return t.button; -} - -pub fn rotate(t: *Trackpad, degrees: f32, phase: u32) i32 { - if (phase == 1 or phase == 3) { - t.rotation = 0; - t.rotation_total = 0; - } - if (phase == 3 or !std.math.isFinite(degrees)) return 0; - if (t.gesture == .pinch) return 0; - t.rotation_total += std.math.clamp(degrees, -640, 640); - if (@abs(t.rotation_total) >= 3) t.gesture = .rotate; - const next = t.rotation + std.math.clamp(degrees, -640, 640); - const ticks: i32 = @intFromFloat(@trunc(next / 10)); - t.rotation = next - @as(f32, @floatFromInt(ticks)) * 10; - return ticks; -} - -/// Ignore small magnification noise, especially while twisting. Once a -/// deliberate pinch wins, half the logarithmic gain makes fine zoom easier. -pub fn magnify(t: *Trackpad, size: f32, scale: f32, phase: u32) ?f32 { - if (phase == 1 or t.pinch_base == 0) { - t.pinch_base = size; - t.pinch_total = 1; - } - if (phase == 3) { - t.pinch_base = 0; - if (t.gesture == .pinch) t.gesture = .none; - return null; - } - if (t.gesture == .rotate or !std.math.isFinite(scale) or scale <= 0) return null; - t.pinch_total = std.math.clamp(t.pinch_total * scale, 0.01, 100); - if (t.gesture == .none) { - if (t.pinch_total > 1 / @as(f32, 1.1) and t.pinch_total < 1.1) return null; - t.gesture = .pinch; - } - return std.math.clamp(t.pinch_base * @sqrt(t.pinch_total), 8, 72); -} - -pub fn pinch(size: f32, scale: f32) f32 { - if (!std.math.isFinite(scale) or scale <= 0) return size; - return std.math.clamp(size * scale, 8, 72); -} - -test "Mac trackpad multi-finger buttons stay latched after the fingers lift" { - var t: Trackpad = .{}; - try std.testing.expectEqual(@as(u8, 3), t.press(3)); // real mouse - try std.testing.expectEqual(@as(?u8, 3), t.release(3)); - for ([_]usize{ 2, 3 }) |n| { - t.fingers = n; - try std.testing.expectEqual(@as(u8, 2), t.press(3)); - t.fingers = 0; - try std.testing.expectEqual(@as(?u8, 2), t.release(3)); - } -} - -test "Mac trackpad force click upgrades Exec once without a paste chord or stray release" { - var t: Trackpad = .{ .fingers = 2 }; - try std.testing.expectEqual(@as(u8, 2), t.press(3)); - try std.testing.expect(t.force(1) == null); - try std.testing.expectEqual(@as(?u8, 2), t.force(2)); - try std.testing.expect(t.force(2) == null); - try std.testing.expect(t.release(3) == null); - t.fingers = 1; - try std.testing.expectEqual(@as(u8, 1), t.press(1)); - try std.testing.expectEqual(@as(?u8, 1), t.release(1)); -} - -test "Mac trackpad rotate and pinch reject invalid input and reset cancelled gestures" { - var t: Trackpad = .{}; - try std.testing.expectEqual(@as(i32, 0), t.rotate(7, 1)); - try std.testing.expectEqual(@as(i32, 1), t.rotate(5, 0)); - try std.testing.expectEqual(@as(i32, -1), t.rotate(-12, 0)); - try std.testing.expectEqual(@as(i32, 0), t.rotate(9, 3)); - try std.testing.expectEqual(@as(f32, 0), t.rotation); - try std.testing.expectEqual(@as(f32, 18), pinch(18, 1)); - try std.testing.expectEqual(@as(f32, 36), pinch(18, 2)); - try std.testing.expectEqual(@as(f32, 72), pinch(18, 100)); - try std.testing.expectEqual(@as(f32, 18), pinch(18, std.math.nan(f32))); -} - -test "trackpad pinch ignores twist noise and uses gentler deliberate zoom" { - var t: Trackpad = .{}; - t.countFingers(2); - try std.testing.expect(t.magnify(18, 1, 1) == null); - for (0..5) |_| try std.testing.expect(t.magnify(18, 1.01, 0) == null); - _ = t.rotate(7, 1); - try std.testing.expect(t.magnify(18, 1.3, 0) == null); - t.countFingers(0); - t.countFingers(2); - const zoom = t.magnify(18, 1.2, 1) orelse return error.PinchNotRecognized; - try std.testing.expect(zoom > 18 and zoom < 20.5); - try std.testing.expectEqual(@as(i32, 0), t.rotate(30, 1)); - try std.testing.expect(t.magnify(zoom, 1, 3) == null); -} diff --git a/src/gui/deck.zig b/src/gui/deck.zig deleted file mode 100644 index 1859bae8..00000000 --- a/src/gui/deck.zig +++ /dev/null @@ -1,204 +0,0 @@ -//! Steam Deck controls -> editor input, as a pure state machine: gui.zig -//! feeds SDL gamepad events in and applies the returned actions (cursor -//! moves, synthetic clicks, wheel ticks, keys, rumble), so the whole -//! mapping replays off-device from deckcap recordings (test/deck/). -//! -//! Layout: right pad moves the pointer (relative, laptop-touchpad-style) and -//! a firm press on it = select (button 1); left pad scrolls and a firm press -//! = look (button 3); R2 = select, L2 = execute (button 2), L1 = look, dpad -//! down/up = n/N, A = Enter, Y = Tab, the back paddles (L4/R4/L5/R5) toggle -//! the terminal (Ctrl-b); execute, look and pad-clicks request a brief rumble -//! ack. (The GUI mirrors this on the sticks: right stick = pointer, left -//! stick = scroll.) - -const std = @import("std"); - -// SDL_GamepadButton / SDL_GamepadAxis / touchpad indices (SDL3), verified -// against real deck recordings (test/deck/*.zon) and the pinned SDL's -// hidapi deck driver (touchpad 0 = left pad, 1 = right pad). -pub const BTN_A = 0; // SOUTH -pub const BTN_Y = 3; // NORTH -pub const BTN_L1 = 9; // LEFT_SHOULDER -pub const BTN_DPAD_UP = 11; -pub const BTN_DPAD_DOWN = 12; -// rear grip paddles (from a deckcap deckmap capture): the two-digit indices -pub const BTN_R4 = 16; -pub const BTN_L4 = 17; -pub const BTN_R5 = 18; -pub const BTN_L5 = 19; -pub const AXIS_L2 = 4; // LEFT_TRIGGER, analog 0..32767 -pub const AXIS_R2 = 5; // RIGHT_TRIGGER -pub const PAD_LEFT = 0; -pub const PAD_RIGHT = 1; - -/// feel knobs: a full-pad finger sweep covers this many screen pixels -/// (the deck's screen is 1280x800) / this many wheel ticks -pub const POINTER_SCALE: f32 = 600.0; -pub const SCROLL_SCALE: f32 = 24.0; -/// the pinned SDL 3.4.4 deck driver skips upstream's pad-Y negation, so -/// touch y arrives 0 = pad bottom; flip this when the sdl dep is bumped -pub const PAD_Y_SIGN: f32 = -1.0; -// analog triggers click at 30% and release at 20%: the gap keeps a value -// hovering near one threshold from chattering press/release pairs -pub const TRIG_PRESS: i16 = 9830; -pub const TRIG_RELEASE: i16 = 6553; -// a firm pad press (pressure 0..1) counts as a click, with the same release -// hysteresis. Real light-touch drags read ~0.03 in captures, so this is well -// clear of them; tune on-device against a real click capture. -pub const PAD_CLICK_PRESS: f32 = 0.10; -pub const PAD_CLICK_RELEASE: f32 = 0.06; - -pub const Input = union(enum) { - button: struct { idx: u8, down: bool }, - axis: struct { idx: u8, value: i16 }, - touch: struct { pad: u8, phase: enum { down, motion, up }, x: f32, y: f32, pressure: f32 }, -}; - -pub const Click = enum { select, execute, look }; // mouse buttons 1/2/3 -pub const Keytap = enum { n, cap_n, enter, tab, tty_toggle }; - -pub const Action = union(enum) { - move: struct { dx: f32, dy: f32 }, // pointer delta in screen pixels - click: struct { which: Click, down: bool }, - wheel: i32, // whole ticks, positive = wheel_down - key: Keytap, - rumble, -}; - -pub const Deck = struct { - rpad_on: bool = false, - rpad_x: f32 = 0, - rpad_y: f32 = 0, - lpad_on: bool = false, - lpad_y: f32 = 0, - scroll: f32 = 0, // fractional wheel ticks carried between motions - l2_held: bool = false, - r2_held: bool = false, - look_held: bool = false, - rpad_click: bool = false, // firm-press click state, per pad (hysteresis) - lpad_click: bool = false, - - pub fn feed(d: *Deck, in: Input, out: *[3]Action) usize { - var n: usize = 0; - switch (in) { - .button => |b| switch (b.idx) { - BTN_A => if (b.down) { - out[0] = .{ .key = .enter }; - n = 1; - }, - BTN_Y => if (b.down) { - out[0] = .{ .key = .tab }; - n = 1; - }, - BTN_DPAD_UP => if (b.down) { - out[0] = .{ .key = .cap_n }; - n = 1; - }, - BTN_DPAD_DOWN => if (b.down) { - out[0] = .{ .key = .n }; - n = 1; - }, - // any back paddle toggles the terminal (Ctrl-b), applied in gui.zig - BTN_L4, BTN_R4, BTN_L5, BTN_R5 => if (b.down) { - out[0] = .{ .key = .tty_toggle }; - n = 1; - }, - BTN_L1 => { - d.look_held = b.down; - out[0] = .{ .click = .{ .which = .look, .down = b.down } }; - n = 1; - if (b.down) { - out[1] = .rumble; - n = 2; - } - }, - else => {}, - }, - .axis => |a| { - if (a.idx != AXIS_L2 and a.idx != AXIS_R2) return 0; - const held = if (a.idx == AXIS_L2) &d.l2_held else &d.r2_held; - const which: Click = if (a.idx == AXIS_L2) .execute else .select; - if (!held.* and a.value >= TRIG_PRESS) { - held.* = true; - out[0] = .{ .click = .{ .which = which, .down = true } }; - n = 1; - if (which == .execute) { - out[1] = .rumble; - n = 2; - } - } else if (held.* and a.value <= TRIG_RELEASE) { - held.* = false; - out[0] = .{ .click = .{ .which = which, .down = false } }; - n = 1; - } - }, - .touch => |t| { - switch (t.pad) { - PAD_RIGHT => switch (t.phase) { - // a fresh touch only re-anchors — deltas start from the - // landing point, so the pointer never jumps to it - .down => { - d.rpad_on = true; - d.rpad_x = t.x; - d.rpad_y = t.y; - }, - .motion => if (d.rpad_on) { - out[n] = .{ .move = .{ - .dx = (t.x - d.rpad_x) * POINTER_SCALE, - .dy = (t.y - d.rpad_y) * PAD_Y_SIGN * POINTER_SCALE, - } }; - n += 1; - d.rpad_x = t.x; - d.rpad_y = t.y; - }, - .up => d.rpad_on = false, - }, - PAD_LEFT => switch (t.phase) { - .down => { - d.lpad_on = true; - d.lpad_y = t.y; - }, - .motion => if (d.lpad_on) { - d.scroll += (t.y - d.lpad_y) * PAD_Y_SIGN * SCROLL_SCALE; - d.lpad_y = t.y; - const ticks: i32 = @intFromFloat(d.scroll); - if (ticks != 0) { - d.scroll -= @floatFromInt(ticks); - out[n] = .{ .wheel = ticks }; - n += 1; - } - }, - .up => d.lpad_on = false, - }, - else => {}, - } - // a firm press on either pad is a click: right pad -> select - // (left button), left pad -> look (right button). The press - // rumbles as click feedback, mirroring the stock driver (SDL - // exposes no per-pad haptic, so it's a short whole-pad buzz). - if (t.pad == PAD_RIGHT or t.pad == PAD_LEFT) { - const which: Click = if (t.pad == PAD_RIGHT) .select else .look; - const held = if (t.pad == PAD_RIGHT) &d.rpad_click else &d.lpad_click; - if (t.phase == .up) { - if (held.*) { - held.* = false; - out[n] = .{ .click = .{ .which = which, .down = false } }; - n += 1; - } - } else if (!held.* and t.pressure >= PAD_CLICK_PRESS) { - held.* = true; - out[n] = .{ .click = .{ .which = which, .down = true } }; - n += 1; - out[n] = .rumble; - n += 1; - } else if (held.* and t.pressure <= PAD_CLICK_RELEASE) { - held.* = false; - out[n] = .{ .click = .{ .which = which, .down = false } }; - n += 1; - } - } - }, - } - return n; - } -}; diff --git a/src/gui/gui.zig b/src/gui/gui.zig deleted file mode 100644 index c772ac1d..00000000 --- a/src/gui/gui.zig +++ /dev/null @@ -1,8319 +0,0 @@ -const dev = @import("dev"); // sketchbook's devices -const SketchGpu = dev.Executor; -const Cells = dev.Cells; -const Atlas = dev.Atlas; -const Present = dev.Present; -const GpuScene = dev.scene; -const filesystem = @import("../fs.zig"); -const std = @import("std"); -const builtin = @import("builtin"); -const posix = std.posix; -/// libc: pipes and fcntl for the window's wakes, and a test harness's capture files written from the render thread. -const libc = std.c; -const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser -const pardes = @import("../pardes.zig"); -const vaxis_input = @import("../vaxis_input.zig"); -const dump = @import("../dump.zig"); -const config = @import("../config.zig"); -const look = @import("../look.zig"); -const message = pardes.Messages.Message; -const file_watch = @import("../file_watch.zig"); -const deck = @import("deck.zig"); -const pet = @import("pet.zig"); -const Trackpad = @import("Trackpad.zig"); -const JumpTrail = @import("../jump_trail.zig"); -const Art = @import("../Art.zig"); -const fonts = @import("../fonts.zig"); // the fallback faces -const selection_pipe = @import("../selection_pipe.zig"); -const c_heap = @import("c_heap"); - -const ninep_io = @import("runtime").ninep_io; - -const daemon = @import("runtime").daemon; -const upgrade = @import("runtime").upgrade; -const replica = @import("../replica.zig"); -const tracy = @import("../tracy.zig"); - -pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig - -const host_io = @import("../host_io.zig"); -const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); - -const log = std.log.scoped(.gui); - -const font_ttf = @embedFile("AdwaitaMono-Regular.ttf"); - -const bg_default = [3]u8{ 18, 18, 18 }; -const fg_default = [3]u8{ 204, 204, 204 }; - -const p9_arrow_clr = [32]u8{ - 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, - 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, - 0x80, 0x02, 0x80, 0x01, 0x80, 0x02, 0x8C, 0x04, - 0x92, 0x08, 0x91, 0x10, 0xA0, 0xA0, 0xC0, 0x40, -}; -const p9_arrow_set = [32]u8{ - 0x00, 0x00, 0x7F, 0xFE, 0x7F, 0xFC, 0x7F, 0xF0, - 0x7F, 0xE0, 0x7F, 0xE0, 0x7F, 0xF0, 0x7F, 0xF8, - 0x7F, 0xFC, 0x7F, 0xFE, 0x7F, 0xFC, 0x73, 0xF8, - 0x61, 0xF0, 0x60, 0xE0, 0x40, 0x40, 0x00, 0x00, -}; -/// acme's boxcursor (acme.c:956), while a grip carries a pane or column. -const p9_box_clr = [32]u8{ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, - 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, -}; -const p9_box_set = [32]u8{ - 0x00, 0x00, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, - 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, - 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, - 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x00, 0x00, -}; -const p9_box_mask = blk: { - var m: [32]u8 = undefined; - for (&m, p9_box_set, p9_box_clr) |*b, s, cl| b.* = s | cl; - break :blk m; -}; -const p9_arrow_mask = blk: { - var m: [32]u8 = undefined; - for (&m, p9_arrow_set, p9_arrow_clr) |*b, s, cl| b.* = s | cl; - break :blk m; -}; - -const atlas_w = Atlas.atlas_w; -const atlas_h = Atlas.atlas_h; -const Slot = Atlas.Slot; -const GlyphKey = Atlas.Key; -const ruleArms = Atlas.ruleArms; - -const GlyphDecoration = packed struct(u5) { - bold: bool = false, - underline: @FieldType(pardes.CellStyle, "ul") = .off, - strikethrough: bool = false, - - fn fromCell(cell: *const pardes.Cell) GlyphDecoration { - if (cell.default or cell.style.invisible) return .{}; - return .{ .bold = cell.style.bold, .underline = cell.style.ul, .strikethrough = cell.style.strikethrough }; - } - - fn drawsBlank(decoration: GlyphDecoration) bool { - return decoration.underline != .off or decoration.strikethrough; - } -}; - -// The atlas's Key holds a GlyphDecoration and a FontRole as its own -// Decoration and Role (@bitCast, @enumFromInt): the same bits, so the same -// slots. -comptime { - std.debug.assert(@bitSizeOf(GlyphDecoration) == @bitSizeOf(Atlas.Decoration)); - for (.{ .{ @FieldType(pardes.CellStyle, "ul"), Atlas.Underline }, .{ pardes.FontRole, Atlas.Role } }) |pair| { - const ours = @typeInfo(pair[0]).@"enum"; - const its = @typeInfo(pair[1]).@"enum"; - std.debug.assert(ours.tag_type == its.tag_type and ours.field_names.len == its.field_names.len); - for (ours.field_names, its.field_names, ours.field_values, its.field_values) |a, b, x, y| std.debug.assert(std.mem.eql(u8, a, b) and x == y); - } -} - -const TaglineRaster = struct { - px: f32, - width: u32, - baseline: i32, - height: u32, -}; - -fn taglineRaster(atlas: *const Atlas, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster { - const px = body_px * @as(f32, @floatFromInt(percent)) / 100.0; - var own_w: c_int = 1; - var own_h: c_int = 1; - var own_ascent: c_int = 1; - atlas.cellMetrics(px, &own_w, &own_h, &own_ascent); - const fixed_w: c_int = @intCast(body_cell_w); - const fixed_h: c_int = @intCast(body_cell_h); - const band_h = std.math.clamp(own_h, 1, fixed_h); - return .{ - .px = px, - .width = @intCast(std.math.clamp(own_w, 1, fixed_w)), - .baseline = std.math.clamp(own_ascent, 1, band_h), - .height = @intCast(band_h), - }; -} -/// What FreeType and HarfBuzz allocate from, through ui_malloc and friends: -/// the shared C heap, exported under the names font.c and HarfBuzz's -/// hb_malloc_impl expect. runNative points it at the gui's gpa once -/// HarfBuzz's process-wide objects exist (ui_font_prime), so a Debug build's -/// leak report is about fonts; a test that counts what fonts leak points it -/// at std.testing.allocator the same way. Only the render thread calls into -/// fonts, and every allocator it is pointed at is thread-safe anyway. -var font_allocator: std.mem.Allocator = std.heap.smp_allocator; -const font_heap = c_heap.Heap(&font_allocator); -comptime { - @export(&font_heap.malloc, .{ .name = "ui_malloc" }); - @export(&font_heap.calloc, .{ .name = "ui_calloc" }); - @export(&font_heap.realloc, .{ .name = "ui_realloc" }); - @export(&font_heap.free, .{ .name = "ui_free" }); -} - -/// What SDL allocates from, on its own threads as well as the render thread: -/// the gui's gpa, through the shared C heap, which is thread-safe in every -/// build. runNative hands everything back and calls SDL_Quit on the way out. -var sdl_allocator: std.mem.Allocator = undefined; -const sdl_heap = c_heap.Heap(&sdl_allocator); - -const max_fallback_fonts = 1 + fonts.fallback_names.len; -comptime { - std.debug.assert(max_fallback_fonts <= Atlas.max_fallbacks); -} - -const max_touch_points: usize = 16; -const touch_scroll_tick: f32 = 0.02; - -// The triangle overlay holds only the pet, a jump's trail and the cursor's -// glide quad: the chrome is decor. -const max_overlay_vertices: usize = pet.max_vertices + 5 * 6 + 6; - -const font_px_step: f32 = 2.0; -const font_px_min: f32 = 8.0; -const font_px_max: f32 = 72.0; - -const CellInstance = Cells.CellInstance; -const OverlayVertex = Cells.OverlayVertex; -const ImageInstance = Cells.ImageInstance; -const opaque_bg_bit = Cells.opaque_bg_bit; - -const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 }; - -const PreparedImage = struct { - premultiplied: bool = false, - place: pardes.Placement, - texture: *c.SDL_GPUTexture, -}; - -fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) bool { - core.update(resizeOf(core.view(), cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false); - return true; -} - -/// The resize a window of `cols` by `rows` cells of these sizes is to the -/// live view, or null when it is that already. -fn resizeOf(v: *const pardes.Pardes.View, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) ?pardes.Event { - const metrics: pardes.RowMetrics = .{ .body_w = @intCast(cell_w), .body_h = @intCast(cell_h), .tagline_w = @intCast(tag_w), .tagline_h = @intCast(tag_h) }; - const same_metrics = std.meta.eql(metrics, v.row_metrics); - const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16))); - const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16))); - if (cols == v.screen_w and rows == v.screen_h and - cell_px_w == v.cell_pixels.w and cell_px_h == v.cell_pixels.h and same_metrics) return null; - return .{ .resize = .{ - .cols = cols, - .rows = rows, - .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h }, - .row_metrics = metrics, - } }; -} - -const TouchPoint = struct { - active: bool = false, - id: u64 = 0, - x: f32 = 0, - y: f32 = 0, -}; - -const TouchNormPoint = struct { x: f32 = 0, y: f32 = 0 }; - -const Finger = struct { kind: enum { down, motion, up, cancel }, id: u64, x: f32, y: f32 }; - -const Touch = struct { - points: [max_touch_points]TouchPoint = @splat(.{}), - scroll: struct { - active: bool = false, - ids: [2]u64 = .{ 0, 0 }, - accum_y: f32 = 0, - scrolled: bool = false, - last_center: TouchNormPoint = .{}, - } = .{}, - - fn findSlot(t: *const Touch, id: u64) ?usize { - for (&t.points, 0..) |*tp, i| if (tp.active and tp.id == id) return i; - return null; - } - - fn updatePoint(t: *Touch, f: Finger) void { - switch (f.kind) { - .up, .cancel => if (t.findSlot(f.id)) |i| { - t.points[i].active = false; - }, - .down, .motion => { - const idx = t.findSlot(f.id) orelse blk: { - for (&t.points, 0..) |*tp, i| if (!tp.active) break :blk i; - break :blk @as(usize, @intCast(f.id % max_touch_points)); - }; - const tp = &t.points[idx]; - if (!tp.active or tp.id != f.id) tp.* = .{ .active = true, .id = f.id }; - tp.x = f.x; - tp.y = f.y; - }, - } - } - - fn pairCenter(t: *const Touch, ids: [2]u64) ?TouchNormPoint { - var sum: TouchNormPoint = .{}; - for (ids) |id| { - const i = t.findSlot(id) orelse return null; - sum.x += t.points[i].x; - sum.y += t.points[i].y; - } - return .{ .x = sum.x * 0.5, .y = sum.y * 0.5 }; - } - - fn syncPair(t: *Touch) void { - var ids: [2]u64 = .{ 0, 0 }; - var count: usize = 0; - for (&t.points) |*tp| { - if (!tp.active) continue; - if (count >= 2) { - t.scroll = .{}; - return; - } - ids[count] = tp.id; - count += 1; - } - if (count != 2) { - t.scroll = .{}; - return; - } - if (ids[0] > ids[1]) std.mem.swap(u64, &ids[0], &ids[1]); - if (t.scroll.active and t.scroll.ids[0] == ids[0] and t.scroll.ids[1] == ids[1]) return; - t.scroll = .{ .active = true, .ids = ids, .last_center = t.pairCenter(ids) orelse .{} }; - } - - fn finishPair(t: *Touch, f: Finger) ?TouchNormPoint { - if (!t.scroll.active or (t.scroll.ids[0] != f.id and t.scroll.ids[1] != f.id)) return null; - const tap = f.kind == .up and !t.scroll.scrolled; - var center: ?TouchNormPoint = null; - if (tap) { - var sum: TouchNormPoint = .{}; - var ok = true; - for (t.scroll.ids) |id| { - if (id == f.id) { - sum.x += f.x; - sum.y += f.y; - } else if (t.findSlot(id)) |i| { - sum.x += t.points[i].x; - sum.y += t.points[i].y; - } else ok = false; - } - center = if (ok) .{ .x = sum.x * 0.5, .y = sum.y * 0.5 } else t.scroll.last_center; - } - t.scroll = .{}; - return center; - } - - fn noteMotion(t: *Touch, f: Finger) ?struct { center: TouchNormPoint, ticks: i32 } { - if (!t.scroll.active or (t.scroll.ids[0] != f.id and t.scroll.ids[1] != f.id)) return null; - const center = t.pairCenter(t.scroll.ids) orelse t.scroll.last_center; - const delta_y = center.y - t.scroll.last_center.y; - t.scroll.last_center = center; - t.scroll.accum_y += delta_y; - const ticks = takeScrollTicks(&t.scroll.accum_y); - if (ticks == 0) return null; - t.scroll.scrolled = true; - return .{ .center = center, .ticks = ticks }; - } -}; - -fn takeScrollTicks(accum: *f32) i32 { - var ticks: i32 = 0; - while (accum.* >= touch_scroll_tick) : (ticks += 1) accum.* -= touch_scroll_tick; - while (accum.* <= -touch_scroll_tick) : (ticks -= 1) accum.* += touch_scroll_tick; - return ticks; -} - -fn handleFinger(t: *Touch, in: *Input, f: Finger, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { - std.debug.assert(cell_w > 0 and cell_h > 0); - switch (f.kind) { - .down => { - t.updatePoint(f); - t.syncPair(); - }, - .motion => { - const had_pair = t.scroll.active; - t.updatePoint(f); - t.syncPair(); - if (!had_pair) return; - const res = t.noteMotion(f) orelse return; - emitTouchScroll(in, res.center, res.ticks, win_w, win_h, cell_w, cell_h, tagline_w); - }, - .up, .cancel => { - const tap_center = t.finishPair(f); - t.updatePoint(f); - t.syncPair(); - if (tap_center) |center| emitTouchClick(in, center, .middle, win_w, win_h, cell_w, cell_h, tagline_w); - }, - } -} - -fn emitTouchScroll(in: *Input, center: TouchNormPoint, ticks: i32, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { - const cell = gridCellAtDimensions(in.core, center.x * win_w, center.y * win_h, cell_w, cell_h, tagline_w); - const button: pardes.Mouse.Button = if (ticks > 0) .wheel_up else .wheel_down; - var remaining: u32 = @abs(ticks); - while (remaining > 0) : (remaining -= 1) - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); -} - -fn emitTouchClick(in: *Input, point: TouchNormPoint, button: pardes.Mouse.Button, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { - const cell = gridCellAtDimensions(in.core, point.x * win_w, point.y * win_h, cell_w, cell_h, tagline_w); - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); - in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); -} - -const Pty = struct { - fd: c_int, - pid: libc.pid_t, - serial: u32, - /// Its reader, blocked in an Io read: `closePty` cancels it. - reader: ?std.Io.Future(void) = null, - /// 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 = .{}, -}; - -const Queue = host_io.Inbox; - -/// Wakes a blocking SDL_WaitEventTimeout from another thread: a push to -/// the queue, a link's message. -fn sdlWake(_: ?*anyopaque) void { - var sev = std.mem.zeroes(c.SDL_Event); - sev.type = c.SDL_EVENT_USER; - _ = c.SDL_PushEvent(&sev); -} -const PipeTasks = selection_pipe.Tasks; -const output_capacity = Queue.output_capacity; - -fn stopPipe() ![2]c_int { - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return error.PipeFailed; - errdefer for (fds) |fd| { - _ = libc.close(fd); - }; - for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed; - return fds; -} - -fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { - while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, - }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - return; - } - if (fds[0].revents != 0) return; - if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return; - if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed); - } -} - -const Gui = struct { - addon_gpu: ?SketchGpu = null, - addon_hash: [pardes.MAX_PANES]u64 = @splat(0), - addon_serial: [pardes.MAX_PANES]u32 = @splat(0), - addon_failed: [pardes.MAX_PANES]u64 = @splat(0), - window: *c.SDL_Window, - /// The device, the window's claim or soft presenter, the frame's target - /// and the capture's read back (runNative owns it). - present: *Present, - /// The pipelines, the atlas's texture, the pictures' textures and the - /// buffers the frame is drawn from, on present's device (runNative owns - /// it). - cells: *Cells, - overlay_vertices: []OverlayVertex, - prepared_images: std.ArrayListUnmanaged(PreparedImage) = .empty, - /// The glyph art of the placements whose panes ask for it (Petscii - /// on), and the frame copy it is drawn into. - art: Art = .{}, - art_arena: ?std.heap.ArenaAllocator = null, - /// renderFrame's cover of the grid (coverFrame). - cover: std.ArrayListUnmanaged(Cover) = .empty, - /// renderFrame's decor instances, group by group (buildDecor). - decor: std.ArrayListUnmanaged(CellInstance) = .empty, - - /// The faces and the glyphs drawn from them. - atlas: Atlas, - font_name: [255]u8 = @splat(0), - font_name_len: u8 = 0, - /// A replica client's: the session's font request it last followed - /// (syncReplicaFont), as a hash of the request. - session_font_request: ?u64 = null, - px: f32, - tagline_px: f32, - tagline_percent: u8, - tagline_width: u32, - tagline_height: u32, - cell_w: u32, - cell_h: u32, - ascent: i32, - tagline_baseline: i32, - - words: Words = .{}, - - touch: Touch = .{}, - /// A Mac trackpad's gestures (macos_trackpad.m decodes them). - trackpad: Trackpad = .{}, - /// The workspace tag's pet (Pet), on the window's own clock. - pet_state: pet.State = .{}, - /// The cursor's jump trail (JumpTrail), on the window's own clock. - trail: JumpTrail = .{}, - /// The caret's ease, on the window's own clock (Caret). - caret: Caret = .{}, - /// The window's clock for the frame being drawn (Shell.ownNow), and - /// what moved the glide's view since the last (stepGlide): the pane a - /// wheel scrolled, one a touchpad moves by the pixel. - now_ns: u64 = 0, - glide_wheeled: ?usize = null, - glide_direct: ?usize = null, - /// The last key, click or wheel, which the blink holds for. - input_ns: u64 = 0, - live_ctrl: bool = false, - live_alt: bool = false, - - scroll_pane: ?usize = null, - scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, - scroll_body_y: u16 = 0, // that rect's first BODY row - scroll_body_h: u16 = 0, // and its BODY rows, which a taller tag leaves fewer of - scroll_held_px: f32 = 0, // its tree-sitter context band, which never moves - scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered - scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since - scroll_delta: f32 = 0, // finite raw distance waiting for the render batch - scroll_lag: f32 = 0, // picture position - core position, in rows - scroll_edge: []pardes.Cell = &.{}, // the row that just left the pane - scroll_edge_len: u16 = 0, - /// Loop steps since the last fractional turn: past `settle_after`, a - /// resting `scroll_lag` eases onto the core's row (stepScroll). - scroll_idle: u8 = 0, - /// G6: a wheel's notches, whole lines, scroll the core at once and the - /// picture follows on a spring (Glide), never the other way round. - scroll_notch: i32 = 0, - /// A touchpad's fraction toward the next turn sent to a program that - /// owns the wheel (Term.Modes.wheel). - program_wheel: f32 = 0, - /// A trackpad's horizontal fraction toward the next turn (wheelAt). - program_wheel_x: f32 = 0, - glide: Glide = .{}, - /// PARDES_FRAMES_DEMO: the timedemo (its script's steps), its next step - /// and when it started; null when none runs. - demo: []const pardes.FrameStats.Step = &.{}, - demo_next: ?usize = null, - demo_start_ns: u64 = 0, - /// The tick the last paced frame was sampled at (waitInput), and - /// whether this loop's wait read an input (drawn at once, not paced). - pace_ns: u64 = 0, - input_seen: bool = false, - /// G14: the cells last drawn and when each last changed. - /// The cursor's blink (blinkNow): when the frame drawn last arrived, - /// a redraw owed for an edge, and this frame's cursor mode and alpha. - frame_arrival_ns: u64 = 0, - blink_due: bool = false, - no_blink: bool = false, - cursor_quad_alpha: f32 = 0, - pointer_present: bool = false, - arrow_cursor: ?*c.SDL_Cursor = null, - link_cursor: ?*c.SDL_Cursor = null, - box_cursor: ?*c.SDL_Cursor = null, - pointer_shape: pardes.Surface.PointerShape = .arrow, - pointer_cell: ?MouseCell = null, - /// The core the hit test asks (hitTest), while a local session runs; - /// null attached, where the session's tag is another process's. - hit_core: ?*pardes.Pardes = null, - - /// Pixels the capture holds past the grid (PARDES_TEST_PAD). - capture_pad: u32 = 0, - capture_dir: []const u8 = "", - /// PARDES_TEST_SERIES: every captured frame is kept too, numbered, for a - /// frame series to look at. - capture_series: bool = false, - captured: u32 = 0, - - applied_window_opacity: u8 = 100, - /// What a window is opened again with (reopenWindow): the flags (not - /// hidden), its size when it was closed (present keeps its present mode). - win_flags: c.SDL_WindowFlags = 0, - /// A native Wayland window: transparent at the first WindowOpacity - /// under 100 (syncWindowOpacity). - wayland: bool = false, - window_w: c_int = 1120, - window_h: c_int = 720, - /// The window runNative destroys at the end: the one open then, if any. - window_slot: ?*?*c.SDL_Window = null, - - gamepad: ?*c.SDL_Gamepad = null, - /// The gamepad subsystem started (startGamepads). - gamepads: bool = false, - pad_x: f32 = 0, - pad_y: f32 = 0, - pad_scroll: f32 = 0, // fractional vertical wheel ticks (left stick) - pad_scroll_h: f32 = 0, // fractional horizontal wheel ticks (left stick) - deck: deck.Deck = .{}, -}; - -/// What a window held of its own let go (closeWindow lets the window go). -fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { - g.glide.deinit(gpa); - gpa.free(g.scroll_edge); - g.prepared_images.deinit(gpa); -} - -fn setGuiFontName(g: *Gui, fallback: []const u8) void { - const name = if (g.atlas.fontName()) |name_z| std.mem.span(name_z) else fallback; - const len = @min(name.len, g.font_name.len); - @memcpy(g.font_name[0..len], name[0..len]); - g.font_name_len = @intCast(len); -} - -fn observeGuiFont(g: *const Gui, core: *pardes.Pardes) void { - const size: u16 = @intFromFloat(@round(g.px * 100.0)); - _ = core.observeFont(g.font_name[0..g.font_name_len], size, .pixels); -} - -fn acknowledgeGuiFont(g: *const Gui, core: *pardes.Pardes) void { - const size: u16 = @intFromFloat(@round(g.px * 100.0)); - _ = core.acknowledgeFont(g.font_name[0..g.font_name_len], size, .pixels); -} - -/// A replica client's font is the window's raster state: it follows the -/// session's request by the face's name on this machine (fonts.fromSession), -/// never acknowledging it or otherwise changing the replicated core. -fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator) bool { - const f = &core.settings.font; - const path = f.requested_path.get(); - const name = f.requested_name.get(); - if (path.len == 0 and name.len == 0) return false; - var hash = std.hash.Wyhash.init(0); - hash.update(path); - hash.update(name); - hash.update(std.mem.asBytes(&f.requested_size_hundredths)); - const request = hash.final(); - if (g.session_font_request == request) return false; - g.session_font_request = request; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const face = fonts.fromSession(arena.allocator(), path, name) orelse { - log.warn("the session's font is not installed here: {s}", .{name}); - return false; - }; - const bytes = filesystem.readFile(gpa, face.path) catch return false; - if (!g.atlas.setFont(gpa, bytes)) return false; - if (f.requested_size_hundredths != 0) - g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100; - setGuiFontName(g, face.name); - refitFont(g, null); - return true; -} - -fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { - _ = g.atlas.addFallback(gpa, font_ttf, false); - - var arena_state = std.heap.ArenaAllocator.init(gpa); - defer arena_state.deinit(); - for (fonts.fallbacks(arena_state.allocator())) |candidate| { - if (g.atlas.fallback_count == max_fallback_fonts) break; - const bytes = filesystem.readFile(gpa, candidate.path) catch continue; - _ = g.atlas.addFallback(gpa, bytes, true); - } -} - -const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 }; -const MouseCell = struct { col: u16, row: u16, body_hit: ?pardes.Mouse.BodyHit = null, tag_hit: ?pardes.TagHit = null, rule_above: bool = false }; - -/// How near a row's top edge a press is on the rule drawn there between two -/// panes: the rule's 2 px and a pixel either side, in logical pixels (dp). -const rule_grab_px: f32 = 3; -const WindowGeometry = struct { - window_w: f32, - window_h: f32, - pixel_w: f32, - pixel_h: f32, -}; - -fn windowGeometry(window: *c.SDL_Window) WindowGeometry { - var ww: c_int = 0; - var wh: c_int = 0; - var pw: c_int = 0; - var ph: c_int = 0; - _ = c.SDL_GetWindowSize(window, &ww, &wh); - _ = c.SDL_GetWindowSizeInPixels(window, &pw, &ph); - return .{ - .window_w = @floatFromInt(@max(ww, 1)), - .window_h = @floatFromInt(@max(wh, 1)), - .pixel_w = @floatFromInt(@max(pw, 1)), - .pixel_h = @floatFromInt(@max(ph, 1)), - }; -} - -const GridCells = struct { cols: u16, rows: u16 }; - -fn windowCells(g: *const Gui) GridCells { - var pw: c_int = 0; - var ph: c_int = 0; - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - return .{ - .cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))), - .rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))), - }; -} - -const Point = struct { x: f32, y: f32 }; - -fn windowPointToPixels(geometry: WindowGeometry, x: f32, y: f32) Point { - return .{ - .x = x * geometry.pixel_w / geometry.window_w, - .y = y * geometry.pixel_h / geometry.window_h, - }; -} - -fn fixedCellLayout(g: *const Gui) CellLayout { - return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; -} - -const Group = Cells.Group; - -/// The frame's draw groups, bottom to top: the page and the panes, the -/// notices floating over them, the debug box the core paints over those, -/// and ink (the bar cursors; the cursor's glide draws after it). -const Groups = struct { - items: [4]Group = @splat(.{}), - notices: usize = 1, - debug: usize = 2, - ink: usize = 3, - len: usize = 4, -}; - -/// What draws a grid cell, marked once a frame from the layers and the -/// regions (coverFrame), so the cell loops read it rather than search. -const Cover = packed struct(u16) { - /// A layer draws it; the grid's copy is not drawn. - layer: bool = false, - /// Under the debug box: drawn from the grid over the panes. - floating: bool = false, - /// In a pane's grip, `grip_offset` cells from its left: the grip's - /// glyph is the cell that far to the left. - grip: bool = false, - grip_offset: u4 = 0, - /// In the focused pane's or column's tag rows. - focus: bool = false, - /// At a column's left edge, where a tag's anchor is inset. - anchor: bool = false, - /// In a dirty pane's grip. - dirty: bool = false, - /// In a pane's grip (not a column's). - pane_grip: bool = false, - /// In a grip's first row, where its button is. - grip_top: bool = false, - /// In an unfocused pane's tag or body rows while InactiveDim fades them. - dim: bool = false, - _: u3 = 0, -}; - -/// Marks the grid cells a body or tag layer covers, which the layers paint -/// themselves, and what the regions say of the rest. Filling each rectangle -/// once replaces scanning every layer for every cell, which was a third of -/// the gui's CPU on a full screen of text. -fn coverFrame(cover: []Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer, regions: []const pardes.Region) void { - @memset(cover, .{}); - const mark = struct { - fn rect(into: []Cover, width: u16, height: u16, r: pardes.Rect, comptime field: []const u8, value: anytype) void { - const right = @min(width, @as(u32, r.x) + r.w); - if (r.x >= right) return; - var y: u32 = r.y; - while (y < @min(height, @as(u32, r.y) + r.h)) : (y += 1) - for (into[y * width ..][r.x..right]) |*cell| { - @field(cell, field) = value; - }; - } - }; - for (body_layers) |*layer| { - if (layer.rows != 0) mark.rect(cover, cols, rows, layer.viewport, "layer", true); - } - for (tag_layers) |*layer| { - if (layer.rows != 0) mark.rect(cover, cols, rows, .{ .x = layer.viewport.x, .y = layer.viewport.y, .w = layer.viewport.w, .h = layer.rows }, "layer", true); - } - // The column bar's rows, which the focused column's tint spans. - var bar: ?pardes.Rect = null; - for (regions) |region| { - if (region.kind == .column_grip) bar = region.rect; - } - // InactiveDim: an unfocused pane's tag and body rows (Dim.begin). - if (dim.amount > 0) for (regions) |region| { - if ((region.kind == .tag or region.kind == .body) and dim.of(region.owner)) mark.rect(cover, cols, rows, region.rect, "dim", true); - }; - for (regions) |region| switch (region.kind) { - .grip, .column_grip => { - mark.rect(cover, cols, rows, region.rect, "grip", true); - for (0..@min(region.rect.w, 16)) |offset| mark.rect(cover, cols, rows, .{ .x = region.rect.x +| @as(u16, @intCast(offset)), .y = region.rect.y, .w = 1, .h = region.rect.h }, "grip_offset", @as(u4, @intCast(offset))); - if (region.kind == .grip and region.active) mark.rect(cover, cols, rows, region.rect, "focus", true); - if (region.dirty) mark.rect(cover, cols, rows, region.rect, "dirty", true); - if (region.kind == .grip) mark.rect(cover, cols, rows, region.rect, "pane_grip", true); - mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w, .h = @min(1, region.rect.h) }, "grip_top", true); - }, - .tag => if (region.active) mark.rect(cover, cols, rows, region.rect, "focus", true), - .column => { - mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = 0, .w = 1, .h = rows }, "anchor", true); - if (region.active) if (bar) |b| mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = b.y, .w = region.rect.w, .h = b.h }, "focus", true); - }, - .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), - else => {}, - }; -} - -pub fn run(init: std.process.Init, opts: pardes.Options, detached: bool) !void { - return runNative(init, opts, detached, null); -} - -/// `pardes-gui --attach=:` (and `:`, -/// through ssh, main.zig): this window a replica client of a session -/// elsewhere, as the tty's `runClient` is a terminal's (`clientSession`). -pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far: bool) !void { - return runNative(init, opts, false, .{ .path = path, .session = session, .far = far }); -} - -const Dial = struct { path: []const u8, session: []const u8, far: bool }; - -fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, dial: ?Dial) !void { - const gpa = init.gpa; - const env = init.environ_map; - - const test_mode = env.get("PARDES_TEST") != null; - const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); - if (test_mode and capture_dir == null) { - log.err("PARDES_TEST requires PARDES_TEST_CAPTURE_DIR", .{}); - return error.SdlInit; - } - if (test_mode) if (env.get("PARDES_TEST_LATENCY")) |path| { - var path_buf: [4096]u8 = undefined; - if (std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0)) |z| - latency_fd = libc.open(z, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)) - else |_| {} - }; - - // SDL frees with whichever functions are current, so they go in before - // its first call, while nothing of SDL's exists yet. - sdl_allocator = gpa; - if (!c.SDL_SetMemoryFunctions(sdl_heap.malloc, sdl_heap.calloc, sdl_heap.realloc, sdl_heap.free)) { - log.err("SDL_SetMemoryFunctions: {s}", .{c.SDL_GetError()}); - return error.SdlInit; - } - _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI", "1"); // SDL_HINT_JOYSTICK_HIDAPI - _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI_STEAMDECK", "1"); // ..._STEAMDECK - if (comptime builtin.os.tag == .macos) _ = c.SDL_SetHint(c.SDL_HINT_MAC_SCROLL_MOMENTUM, "1"); - // The gamepads after the first frame (startGamepads). - if (!c.SDL_Init(c.SDL_INIT_VIDEO)) { - log.err("SDL_Init: {s}", .{c.SDL_GetError()}); - return error.SdlInit; - } - // SDL allocates from gpa (above), so what it still holds at exit is in a - // Debug build's leak report. The window, the GPU device and everything - // made on it go back first (the defers below run before this one). What - // is left is SDL 3.4.4's: its Vulkan backend never frees two 32-byte - // arrays per command buffer (VULKAN_INTERNAL_DestroyCommandPool; SDL's - // main branch frees them). - defer c.SDL_Quit(); - // No title bar or frame from anyone: borderless asks the compositor for - // none (xdg-decoration's client side, which SDL then leaves undrawn). - var win_flags: c.SDL_WindowFlags = c.SDL_WINDOW_RESIZABLE | c.SDL_WINDOW_BORDERLESS; - if (!test_mode) win_flags |= c.SDL_WINDOW_HIGH_PIXEL_DENSITY; - // A test run renders to the capture texture; keep it off the desktop. - if (test_mode) win_flags |= c.SDL_WINDOW_HIDDEN; - // Background-only opacity needs per-pixel alpha (whole-window compositor - // opacity would dim the text as well), so a transparent window, which - // the GPU API will not claim: it presents through SDL_Renderer, EGL and - // GL beside Vulkan, and its first present is slow. So a window starts - // opaque, and is made again transparent at the first WindowOpacity - // under 100 (syncWindowOpacity): SDL takes the flag only at creation. - const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); - const reopen_flags = win_flags; - // `--detach`: a window never shown, closed once the session is up. - if (detached) win_flags |= c.SDL_WINDOW_HIDDEN; - // `--geometry=WxH[+X+Y]`, as X11 programs take it. - var want_w: c_int = 1120; - var want_h: c_int = 720; - var want_at: ?[2]c_int = null; - if (opts_in.geometry) |spec| geometry: { - const x_at = std.mem.indexOfScalar(u8, spec, 'x') orelse break :geometry; - const plus = std.mem.indexOfAnyPos(u8, spec, x_at, "+-") orelse spec.len; - want_w = std.math.clamp(std.fmt.parseInt(c_int, spec[0..x_at], 10) catch break :geometry, 200, 16384); - want_h = std.math.clamp(std.fmt.parseInt(c_int, spec[x_at + 1 .. plus], 10) catch break :geometry, 120, 16384); - if (plus == spec.len) break :geometry; - const second = std.mem.indexOfAnyPos(u8, spec, plus + 1, "+-") orelse break :geometry; - const gx = std.fmt.parseInt(c_int, spec[plus + @intFromBool(spec[plus] == '+') .. second], 10) catch break :geometry; - const gy = std.fmt.parseInt(c_int, spec[second + @intFromBool(spec[second] == '+') ..], 10) catch break :geometry; - want_at = .{ gx, gy }; - } - const window = c.SDL_CreateWindow("pardes", want_w, want_h, win_flags) orelse { - log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); - return error.SdlInit; - }; - var window_slot: ?*c.SDL_Window = window; - if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); - defer if (window_slot) |open| c.SDL_DestroyWindow(open); - if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); - updateDisplayScale(window); - // On Linux the desktop's own cursor theme draws them (the compositor's - // cursor-shape protocol, else XCURSOR_THEME), at its size and scale: - // the arrow is its default, acme's box its move, as the plan9 theme - // has them. Elsewhere acme's bitmaps, at 16 pixels. - const themed_cursors = builtin.os.tag == .linux; - const arrow_cursor = if (themed_cursors) - c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_DEFAULT) - else - c.SDL_CreateCursor(&p9_arrow_set, &p9_arrow_mask, 16, 16, 1, 1); - defer if (arrow_cursor) |cursor| c.SDL_DestroyCursor(cursor); - const link_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER); - defer if (link_cursor) |cursor| c.SDL_DestroyCursor(cursor); - // Its hot spot the middle, as acme's {-7, -7} offset puts it. - const box_cursor = if (themed_cursors) - c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_MOVE) - else - c.SDL_CreateCursor(&p9_box_set, &p9_box_mask, 16, 16, 7, 7); - defer if (box_cursor) |cursor| c.SDL_DestroyCursor(cursor); - if (arrow_cursor) |cur| { - _ = c.SDL_SetCursor(cur); - } else log.err("SDL_CreateCursor: {s}", .{c.SDL_GetError()}); - var presenter = try Present.init(window, .{ - .test_mode = test_mode, - .surface_opacity = false, - .present_modes = &.{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }, - .debug = true, - }); - defer presenter.deinit(); - - font_allocator = gpa; - var atlas = Atlas.init(gpa, font_ttf) catch |err| { - log.err("the font atlas: {t}", .{err}); - return err; - }; - // HarfBuzz's process-wide objects are made once and never freed: made - // from the default heap, they stay out of a Debug build's leak report. - font_allocator = std.heap.smp_allocator; - atlas.prime(); - font_allocator = gpa; - // A harness forcing a density (PARDES_TEST_SCALE) draws the text as a - // person on that display would size it, so its chrome is seen at the - // proportion it has there. A live window keeps the size the user sets. - const px: f32 = if (test_mode) 27.0 * std.math.clamp(display_scale, 1, 4) else 27.0; - var cw: c_int = 10; - var chh: c_int = 20; - var asc: c_int = 16; - atlas.cellMetrics(px, &cw, &chh, &asc); - const cell_w: u32 = @intCast(@max(cw, 1)); - const cell_h: u32 = @intCast(@max(chh, 1)); - const tagline = taglineRaster(&atlas, px, cell_w, cell_h, config.gui_tagline_font_percent); - if (test_mode) { - const cols = envU16(env, "PARDES_TEST_COLS") orelse 80; - const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24; - // PARDES_TEST_PAD: extra pixels past the grid, as a real window has. - const pad = envU16(env, "PARDES_TEST_PAD") orelse 0; - _ = c.SDL_SetWindowSize(window, @intCast(cols * cell_w + pad), @intCast(rows * cell_h + pad)); - _ = c.SDL_SyncWindow(window); - } - - var cells = try Cells.init(presenter.device, presenter.swapchain_format, max_overlay_vertices); - // The pipelines, textures and buffers it holds, whatever they were - // regrown to, before the device (presenter's defer). - defer cells.deinit(gpa); - - const overlay_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices); - defer gpa.free(overlay_vertices); - - var g: Gui = .{ - .window = window, - .arrow_cursor = arrow_cursor, - .link_cursor = link_cursor, - .box_cursor = box_cursor, - .present = &presenter, - .cells = &cells, - .overlay_vertices = overlay_vertices, - .atlas = atlas, - .px = px, - .tagline_px = tagline.px, - .tagline_percent = config.gui_tagline_font_percent, - .tagline_width = tagline.width, - .tagline_height = tagline.height, - .cell_w = cell_w, - .cell_h = cell_h, - .ascent = asc, - .tagline_baseline = tagline.baseline, - .capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0, - .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, - .capture_dir = capture_dir orelse "", - .demo = if (env.get("PARDES_FRAMES_DEMO")) |path| try pardes.FrameStats.readScript(init.arena.allocator(), init.io, path) else &.{}, - .demo_next = if (env.get("PARDES_FRAMES_DEMO") != null) 0 else null, - .win_flags = reopen_flags, - .wayland = native_wayland, - .window_w = want_w, - .window_h = want_h, - .window_slot = &window_slot, - }; - defer if (g.gamepad) |pad| c.SDL_CloseGamepad(pad); - setGuiFontName(&g, "Adwaita Mono"); - loadFallbackFonts(&g, gpa); - defer g.atlas.deinit(gpa); - defer g.words.deinit(gpa); - defer { - if (g.addon_gpu) |*gpu| gpu.deinit(); - g.prepared_images.deinit(gpa); - g.art.deinit(gpa); - if (g.art_arena) |*arena| arena.deinit(); - g.cover.deinit(gpa); - g.decor.deinit(gpa); - } - defer gpa.free(g.scroll_edge); // grown on demand by stepScroll - defer g.glide.deinit(gpa); - resetGlyphAtlas(&g); - - // The window is dragged by the workspace tag's blank (hitTest): the - // compositor moves it, as it does a title bar. - if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) - log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); - if (dial) |to| return clientSession(init, &g, opts_in, test_mode, to); - try localSession(init, &g, opts_in, test_mode, detached); -} - -/// Detach: the window closed (and with it its swapchain or renderer); the -/// device, the atlas and the pipelines stay for the next one. -fn closeWindow(g: *Gui) void { - _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h); - _ = c.SDL_StopTextInput(g.window); - g.present.detach(g.window); - c.SDL_DestroyWindow(g.window); - if (g.window_slot) |slot| if (slot.* == g.window) { - slot.* = null; - }; -} - -/// `pardes-gui --attach`: a window again, as the first was made, at the -/// size the last one had. False when the display will not give one. -fn reopenWindow(g: *Gui) bool { - const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; - if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); - if (!g.present.attach(window)) { - c.SDL_DestroyWindow(window); - return false; - } - g.window = window; - if (g.window_slot) |slot| slot.* = window; - updateDisplayScale(window); - // ponytail: another view's window asks the hit test of whichever - // window's share the Gui holds then (the workspace tag sits in the same - // place in every view); a test per window if one moves it. - if (!g.present.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g); - _ = c.SDL_StartTextInput(window); - return true; -} - -fn localSession( - init: std.process.Init, - g: *Gui, - opts_in: pardes.Options, - test_mode: bool, - detached: bool, -) !void { - const io = init.io; - const gpa = init.gpa; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - host_io.startWorkers(allocs); - defer host_io.stopWorkers(); - var opts = opts_in; - opts.addons = pardes.Addon.scan(); - opts.image_allocator = allocs.image; - opts.tree_sitter_allocator = allocs.tree_sitter; - opts.frame_allocator = allocs.frame; - var pw: c_int = 0; - var ph: c_int = 0; - if (opts.load_path != null) { - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))); - opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))); - } - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, opts, rec) - else if (opts.load_path) |lp| blk: { - const bytes = try @import("../fs.zig").readFile(gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); - } else try pardes.Pardes.init(allocs.pardes, opts); - defer core.deinit(); - g.hit_core = core; - defer g.hit_core = null; - core.view().frontend.windowed = true; - core.view().frontend.native_images = true; - core.view().frontend.native_image_patches = true; - observeGuiFont(g, core); - syncTaglineFont(g, core); - - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); - - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(0); - var queue: Queue = .{ - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .wake_fn = sdlWake, - }; - defer { - if (queue.lsp_task) |*task| task.future.cancel(io); - // Its worker may be waiting on the queue for room. - core.stream.cancelTask(); - queue.deinit(); - } - var pipe_tasks: PipeTasks = .{}; - defer pipe_tasks.cancelAll(io); - var inotify_fd: c_int = file_watch.init(true); - var watch_reader: ?std.Thread = null; - var watch_stop: [2]c_int = .{ -1, -1 }; - defer if (inotify_fd >= 0) { - if (watch_reader) |thread| { - _ = host_io.writeFd(watch_stop[1], "x"); - thread.join(); - } - for (watch_stop) |fd| if (fd >= 0) { - _ = libc.close(fd); - }; - file_watch.stop(inotify_fd); - _ = libc.close(inotify_fd); - inotify_fd = -1; - }; - var watches: file_watch.Table = @splat(null); - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); - - var shell: Shell = .{ - .core = core, - .gui = g, - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .prompt_rcs = &prompt_rcs, - .ptys = &ptys, - .gens = &gens, - .queue = &queue, - .pipe_tasks = &pipe_tasks, - .inotify_fd = inotify_fd, - .watches = &watches, - .fs = fs, - .test_mode = test_mode, - .test_clock = if (test_mode) host_io.testClock() else null, - .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, - }; - defer shell.job_tasks.cancelAll(io); - defer shell.shutdownPtys(); - // A virtual clock never blinks: goldens and feel series hold still. - g.no_blink = shell.test_clock != null; - frame_probe = &core.frames; - frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; - const host = shell.host(); - core.host = host; - pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; - defer pardes.Kind.drawer = null; - shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .detached = detached }; - defer shell.peers.deinit(); - // Before the core goes: each client sees its link end. - defer shell.peers.dropAll(shell.core); - - while (core.nextEffect()) |e| core.perform(e); - // An upgraded session's shells, once a fresh session's own has a - // directory to adopt them in. - if (upgrade.resumed) |*rec| { - shell.resumePtys(rec); - while (core.nextEffect()) |e| core.perform(e); - } - for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), gens[id]); - }; - if (inotify_fd >= 0) { - watch_stop = try stopPipe(); - watch_reader = try std.Thread.spawn(.{}, watchThread, .{ inotify_fd, watch_stop[0], &queue }); - } - if (fs) |f| try f.watch(&queue, wakeFs); - - _ = c.SDL_StartTextInput(g.window); - // An upgraded session's window, its view's again. - if (upgrade.resumed) |*rec| if (!rec.fresh and !detached) shell.resumeWindow(); - - if (test_mode) setStdinRaw() catch {}; - shell.threads_ok = true; - pardes.lsp.setStatusSink(&queue, Queue.lspStatus); - defer pardes.lsp.setStatusSink(null, null); - host_io.setExitWake(&queue, Queue.wakeForExit); - defer host_io.setExitWake(null, null); - if (detached) { - shell.closeTheWindow(); - // Nothing else may wake the first wait. - daemon.watch(&shell, deliverNote); - } - - while (!core.quit) { - pardes.turn.bump(&pardes.turn.restores); - try core.pump(host); - // Its unit to each replica client, and theirs taken in. - shell.peers.boundary(core); - upgrade.locate(); - // Asked in the step (the word), done between steps: the session whole. - if (shell.upgrade_asked) |pane| shell.upgradeNow(pane); - // A window asked for again, or an adopted shell, from the daemon's - // thread through the queue; started after the first frame. - daemon.watch(&shell, deliverNote); - if (core.quit) break; // a session that ended does not restore into one - if (core.takeRestore()) |rp| blk: { - const nc = host_io.restoreCore(gpa, core, rp, &shell.peers, inotify_fd, &watches) orelse break :blk; - pipe_tasks.cancelAll(io); - queue.discardCompletions(); - // One view, the window's (host_io.restoreCore). - shell.gview = 0; - shell.stopPtys(); - g.cells.clearImages(); - g.prepared_images.clearRetainingCapacity(); - nc.view().frontend.native_images = true; - nc.view().frontend.native_image_patches = true; - nc.host = host; - if (fs) |f| f.reset(nc); - nc.view().frontend.windowed = true; - core.deinit(); - core = nc; - frame_probe = &nc.frames; // the old core's ring went with it - g.hit_core = nc; - shell.core = nc; - shell.surface = null; - observeGuiFont(g, core); - syncTaglineFont(g, core); - } - } - - if (fs) |f| { - f.deinit(gpa); - fs = null; - shell.fs = null; - } -} - -/// A window's link to a session elsewhere (`clientSession`): what the -/// window's input made, fed to the replica once its own view is put back, -/// and what the link's reader took off the stream. -const Client = struct { - link: replica.Link, - io: std.Io, - gpa: std.mem.Allocator, - /// The window's inputs since the last feed, their texts in `texts`: - /// read over its own view (`Replica.within`), applied after it. - pending: std.ArrayListUnmanaged(pardes.Event) = .empty, - texts: std.heap.ArenaAllocator, - /// The reader's, under `lock`: what it took, and whether the link ended. - lock: std.Io.Mutex = .init, - inbox: std.ArrayListUnmanaged(replica.Said) = .empty, - taken: std.ArrayListUnmanaged(replica.Said) = .empty, - ended: bool = false, - /// The size the window last posted while its view is not that size - /// yet (the session has not taken it, or speculation stopped at it): - /// posted once, not again each pass while it waits. - posted: ?@FieldType(pardes.Event, "resize") = null, - - fn deinit(cl: *Client) void { - cl.pending.deinit(cl.gpa); - cl.texts.deinit(); - cl.inbox.deinit(cl.gpa); - cl.taken.deinit(cl.gpa); - } - - fn post(cl: *Client, ev: pardes.Event) void { - var e = ev; - const a = cl.texts.allocator(); - switch (e) { - .key => |*k| k.text = a.dupe(u8, k.text) catch "", - .paste, .command => |*b| b.* = a.dupe(u8, b.*) catch return, - else => {}, - } - cl.pending.append(cl.gpa, e) catch {}; - } - - /// What the window's input made, applied at once and sent. - fn feed(cl: *Client) void { - for (cl.pending.items) |ev| { - const r = cl.link.r; - const predicted = r.echo.stats.predicted; - cl.link.input(ev); - // PARDES_TEST_LATENCY: the input, and whether it shows at once - // (applied, or its echo predicted), for the frame that shows it. - latencyNote("I {d} {d} {d}\n", .{ r.next_seq - 1, monoNs(), @intFromBool(r.applied == r.pending.items.len or r.echo.stats.predicted > predicted) }); - } - cl.pending.clearRetainingCapacity(); - _ = cl.texts.reset(.retain_capacity); - } - - /// The reader's: a message of the stream, for the loop, which it wakes. - fn said(cl: *Client, msg: replica.Said) bool { - cl.lock.lockUncancelable(cl.io); - defer cl.lock.unlock(cl.io); - cl.inbox.append(cl.gpa, msg) catch return false; - sdlWake(null); - return true; - } - - /// What the reader took, in its order, and the link's end after it. - fn takeSaid(cl: *Client) void { - cl.lock.lockUncancelable(cl.io); - std.mem.swap(std.ArrayListUnmanaged(replica.Said), &cl.inbox, &cl.taken); - const ended = cl.ended; - cl.lock.unlock(cl.io); - for (cl.taken.items) |msg| { - // PARDES_TEST_LATENCY: when a terminal's delta came (an echo's). - if (msg == .screen) latencyNote("S {d}\n", .{monoNs()}); - cl.link.take(msg); - // And after a unit, the first of its own inputs not confirmed. - if (msg == .unit) { - const r = cl.link.r; - latencyNote("U {d} {d}\n", .{ monoNs(), if (r.pending.items.len > 0) r.pending.items[0].seq else r.next_seq }); - } - } - cl.taken.clearRetainingCapacity(); - if (ended) { - cl.link.quit = true; - cl.link.gone = true; - } - } - - /// Its own view drawn in the window, outside any step, as the tty's - /// client draws its terminal (tui.zig `Client.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; - 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; - // Its render's end is marked as it presents (`present`). - core.frames.mark_render = core.frames.mark_update; - r.draw(.{ .ctx = s, .f = present }); - cl.link.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), if (s.gui) |g| frontendMoving(g) else false, cl.link.owed); - core.present_skipped = skipped; - core.needs_frame = needs; - cl.link.drawn(s.presented); - } -}; - -/// The session's stream, onto the client's inbox: its units, and its end. -fn clientReader(cl: *Client, fd: c_int, rest: *replica.Framer) void { - replica.readLink(cl.gpa, fd, rest, cl, Client.said); - cl.lock.lockUncancelable(cl.io); - cl.ended = true; - cl.lock.unlock(cl.io); - sdlWake(null); -} - -/// What the window does over its own view (`Replica.within`), its inputs -/// posted to the client (`Input.client`): an SDL event dispatched, its size -/// (the tagline's face too), the pointer under a frame that moved, the -/// timedemo's and the test feed's steps. -const OwnView = struct { - g: *Gui, - in: *Input, - s: *Shell, - sev: ?*const c.SDL_Event = null, - pointer: bool = false, - eof: bool = false, - - fn run(v: *OwnView, core: *pardes.Pardes) anyerror!void { - if (v.sev) |sev| return dispatch(v.g, v.in, sev); - const g = v.g; - if (syncReplicaFont(g, core, v.s.gpa)) v.s.client.?.link.dirty = true; - if (scrollRows(g, v.in, v.s.gpa)) v.s.client.?.link.dirty = true; - if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.client.?.link.dirty = true; - const geom = windowCells(g); - const cl = v.s.client.?; - if (resizeOf(core.view(), geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| { - if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) v.in.post(ev); - cl.posted = ev.resize; - } else cl.posted = null; - if (v.pointer) refreshPresentedPointer(g, v.in); - runDemo(g, v.in, core); - if (v.s.test_mode) { - if (v.s.feed.pump(v.s.gpa, v.in, g) catch return error.TestFeed) v.eof = true; - } - } -}; - -/// `pardes-gui --attach=:`: the window, made as a session's -/// is, a replica client of that session (docs/next-daemon.md, "Phase 6: GUI -/// replica notes"). Its own core, loaded from the session's dump, applies -/// its input at once (src/replica.zig) and draws its own view; the -/// session's units are the truth it rolls back to. The tty's `runClient`, with -/// a window for a terminal. -fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: Dial) !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 buf: [800]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes-gui: --attach: " ++ fmt ++ "\n", args) catch "pardes-gui: --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 - // and its stream in zstd, as the tty's client (replica.zig `Have`). - const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else to.far; - 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; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.Term.start(allocs.image); - pardes.Kind.heap = allocs.addon; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.Term.stop(); - pardes.syntax.stop(); - } - var o = opts_in; - o.image_allocator = allocs.image; - var joined: replica.Joined = undefined; - var r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - - var client: Client = .{ .link = .{ .r = r, .fd = joined.fd }, .io = io, .gpa = gpa, .texts = .init(gpa) }; - defer client.deinit(); - const link = &client.link; - try link.fromEnv(gpa, init.environ_map); - defer link.deinit(gpa); - // A client spawns, watches and serves nothing: the Shell's tables are - // empty ones, there for what draws. - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(0); - var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, .wake_fn = sdlWake }; - defer queue.deinit(); - var pipe_tasks: PipeTasks = .{}; - var watches: file_watch.Table = @splat(null); - const prompt_rcs: host_io.Shell.PromptFiles = .{}; - var shell: Shell = .{ - .core = r.core(), - .gui = g, - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .prompt_rcs = &prompt_rcs, - .ptys = &ptys, - .gens = &gens, - .queue = &queue, - .pipe_tasks = &pipe_tasks, - .inotify_fd = -1, - .watches = &watches, - .test_mode = test_mode, - .client = &client, - }; - pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; - defer pardes.Kind.drawer = null; - defer shell.job_tasks.cancelAll(io); - g.no_blink = test_mode; - defer g.hit_core = null; - _ = c.SDL_StartTextInput(g.window); - if (test_mode) setStdinRaw() catch {}; - // A join a pass: the first, and one after the replica diverged or the - // session let it go to upgrade. The window stays as it is. - while (true) { - const core = r.core(); - g.session_font_request = null; - shell.core = core; - shell.gview = joined.view; - shell.surface = null; - g.hit_core = core; - frame_probe = &core.frames; - link.reset(r, &joined); - client.posted = null; - client.ended = false; - // ponytail: why it joined again is the window's title (and its - // log) until a key, where a terminal's client draws it over its - // frame: a window's frame is the core's cells, which it cannot write. - var titled = link.notice_len > 0; - if (titled) { - var title: [260]u8 = undefined; - _ = c.SDL_SetWindowTitle(g.window, std.fmt.bufPrintSentinel(&title, "pardes: {s}", .{link.notice()}, 0) catch "pardes"); - log.warn("{s}", .{link.notice()}); - } - const reader = try std.Thread.spawn(.{}, clientReader, .{ &client, joined.fd, &joined.rest }); - var in: Input = .{ .core = core, .shell = &shell, .client = &client }; - // What it is, then its size, are its view's first inputs. - link.input(.{ .frontend = .{ .windowed = true, .native_images = true, .native_image_patches = true } }); - var drew = false; - var again = false; - while (!link.quit) { - core.frames.period_ns = refreshNs(g); - var own: OwnView = .{ .g = g, .in = &in, .s = &shell, .pointer = drew }; - r.within(&own, OwnView.run); - client.feed(); - if (own.eof) break; - // Its predicted echo judged and caught up, once a frame. - if (r.echoFrame()) link.dirty = true; - drew = false; - if (link.dirty) { - client.draw(&shell); - drew = shell.presented; - } else if (again and shell.presented) if (shell.surface) |frame| { - // A blink, the window's own motion: the last frame again, - // moved on, as the session's own window draws it (pollFrame). - g.now_ns = shell.ownNow(); - shell.presented = renderFrame(g, gpa, core, frame) catch false; - drew = shell.presented; - }; - again = false; - // The window's own motions (its glide, its caret, a jump's - // trail) and its blink are on its clock: no unit need come. - const minimized = !test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; - const moving = !minimized and frontendMoving(g); - const blink = if (minimized or shell.surface == null) null else blinkNow(g, core.settings.cursor_blink); - const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; - // A latency trace's feed paces the loop, as the session's own - // window's (waitInput): its poll on stdin is the wait, and SDL's, - // which polls a clock and a lock a millisecond at a time with - // the offscreen driver, is not waited too (a frame a loop more). - var ms: c_int = if (latency_fd >= 0) 0 else if (test_mode) 16 else -1; - if (demoDue(g)) |due| ms = if (ms < 0) due else @min(ms, due); - if (predicting or link.owed) ms = if (ms < 0) frame_ms else @min(ms, frame_ms); - // A touchpad's fraction settling onto a row (scrollRows). - if (moving or g.scroll_lag != 0 or g.scroll_delta != 0) { - const frame_wait: c_int = @intCast(@max(1, (refreshNs(g) + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); - ms = if (ms < 0) frame_wait else @min(ms, frame_wait); - } - if (blink) |b| if (if (b.edge) refreshNs(g) else b.next_ns) |ns| { - const wait: c_int = @intCast(@min(std.math.maxInt(c_int), ns / std.time.ns_per_ms + 1)); - ms = if (ms < 0) wait else @min(ms, wait); - }; - if (link.quietCheck()) |wait| ms = if (ms < 0) @intCast(wait) else @min(ms, @as(c_int, @intCast(wait))); - // Idle, its frame drawn: the next input needs no copy taken. - if (ms != 0 or latency_fd >= 0) r.ready(); - if (shell.surface != null) startGamepads(g); - var sev = std.mem.zeroes(c.SDL_Event); - g.input_seen = false; - var got = c.SDL_WaitEventTimeout(&sev, ms); - const timed_out = !got; - while (got) : (got = c.SDL_PollEvent(&sev)) { - if (sev.type == c.SDL_EVENT_USER) continue; - var one: OwnView = .{ .g = g, .in = &in, .s = &shell, .sev = &sev }; - r.within(&one, OwnView.run); - client.feed(); - if (link.quit) break; - } - client.takeSaid(); - // Its draws done (api.draw: this window's own pictures). - if (shell.takeDraws()) link.dirty = true; - r.settle(); - // A rollback since it drew: drawn again, never moved on from - // cells the copy put back. - if (r.moved) { - r.moved = false; - link.dirty = true; - } - if (titled and link.notice_len == 0) { - titled = false; - _ = c.SDL_SetWindowTitle(g.window, "pardes"); - } - if (link.owed or r.echo.changed) link.dirty = true; - if (moving or (blink != null and (blink.?.edge or timed_out))) again = true; - 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 reader ends with the link: what it took meanwhile is let go. - _ = libc.shutdown(joined.fd, 2); - reader.join(); - client.lock.lockUncancelable(io); - for (client.inbox.items) |msg| switch (msg) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), - .checked => {}, - }; - client.inbox.clearRetainingCapacity(); - client.lock.unlock(io); - _ = libc.close(joined.fd); - joined.rest.deinit(gpa); - 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) Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}); - return; - } - // The session again, the core it leaves held meanwhile. - r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, r) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - } -} - -const frame_ms: c_int = @intCast(pardes.frame_ns / std.time.ns_per_ms); - -const StdinFeed = struct { - parser: vaxis.Parser = .{}, - /// Inside the driver's bracketed paste: its keys are the paste's text. - in_paste: bool = false, - paste: std.ArrayList(u8) = .empty, - cache: vaxis.GraphemeCache = .{}, - buf: [1024]u8 = undefined, - fill: usize = 0, - last_cols: u16 = 0, - last_rows: u16 = 0, - - /// The test driver's keys and events since the last call, posted to - /// `in`; true once its input has ended. - fn pump(f: *StdinFeed, gpa: std.mem.Allocator, in: *Input, g: ?*Gui) !bool { - var ws: posix.winsize = std.mem.zeroes(posix.winsize); - if (posix.system.ioctl(0, posix.T.IOCGWINSZ, @intFromPtr(&ws)) == 0 and - ws.col > 0 and ws.row > 0 and ws.col <= 1000 and ws.row <= 1000 and - (ws.col != f.last_cols or ws.row != f.last_rows)) - { - f.last_cols = ws.col; - f.last_rows = ws.row; - applyResize(in, g, ws.col, ws.row); - } - - var fds = [_]posix.pollfd{.{ .fd = 0, .events = posix.POLL.IN, .revents = 0 }}; - pardes.turn.rest(); - const polled = posix.poll(&fds, 16); - pardes.turn.wake(); - _ = polled catch return false; - if ((fds[0].revents & posix.POLL.IN) == 0) return (fds[0].revents & (posix.POLL.HUP | posix.POLL.ERR)) != 0; - const rn = libc.read(0, f.buf[f.fill..].ptr, f.buf.len - f.fill); - if (rn < 0) return false; - if (rn > 0) latencyNote("R {d}\n", .{monoNs()}); - if (rn == 0) return true; - const len = f.fill + @as(usize, @intCast(rn)); - f.fill = 0; - - var seq_start: usize = 0; - while (seq_start < len) { - // ESC]777;;BEL, the driver's own: - // mouse;;;;[;] - // mouse;wheel;;;[;]: a mouse event at - // window pixels, built as SDL would and run through dispatch, - // so a driver exercises the real pointer path (pixel to cell, - // tag and body hits). SGR mouse carries only cells. - // finger;;;;; - // One the read cut short, or what may yet begin one, waits for - // the next read. - const rest = f.buf[seq_start..len]; - const osc = "\x1b]777;"; - if (std.mem.startsWith(u8, rest, osc) or std.mem.startsWith(u8, osc, rest)) { - const bel = std.mem.indexOfScalar(u8, rest, 0x07) orelse { - std.mem.copyForwards(u8, f.buf[0..rest.len], rest); - f.fill = rest.len; - break; - }; - seq_start += bel + 1; - const event = rest[osc.len..bel]; - const semi = std.mem.indexOfScalar(u8, event, ';') orelse event.len; - const fields = event[@min(semi + 1, event.len)..]; - if (std.mem.eql(u8, event[0..semi], "mouse")) { - if (g) |gp| { - var parts = std.mem.splitScalar(u8, fields, ';'); - const kind = parts.next() orelse ""; - const second = parts.next() orelse ""; - const button = std.fmt.parseInt(u8, second, 10) catch 0; - const x = std.fmt.parseFloat(f32, parts.next() orelse "") catch 0; - const y = std.fmt.parseFloat(f32, parts.next() orelse "") catch 0; - // An optional fifth field holds modifiers as xterm - // counts them: shift 4, meta (alt) 8, ctrl 16. - const held = std.fmt.parseInt(u8, parts.next() orelse "0", 10) catch 0; - var sev = std.mem.zeroes(c.SDL_Event); - const k = std.meta.stringToEnum(enum { wheel, focus, motion, down, up }, kind) orelse .up; - switch (k) { - .wheel => { - // ESC]777;mouse;wheel;;;BEL: - // a whole number is a mouse's notches, else a touchpad's. - const amount = std.fmt.parseFloat(f32, second) catch 0; - sev.type = c.SDL_EVENT_MOUSE_WHEEL; - sev.wheel.y = amount; - sev.wheel.integer_y = @intFromFloat(@trunc(amount)); - sev.wheel.mouse_x = x; - sev.wheel.mouse_y = y; - }, - // ESC]777;mouse;focus;<1 gained, 0 lost>;0;0BEL - .focus => sev.type = if (button != 0) c.SDL_EVENT_WINDOW_FOCUS_GAINED else c.SDL_EVENT_WINDOW_FOCUS_LOST, - .motion => { - sev.type = c.SDL_EVENT_MOUSE_MOTION; - sev.motion.x = x; - sev.motion.y = y; - sev.motion.state = if (button == 0 or button > 5) 0 else @as(u32, 1) << @intCast(button - 1); - }, - .down, .up => { - sev.type = if (k == .down) c.SDL_EVENT_MOUSE_BUTTON_DOWN else c.SDL_EVENT_MOUSE_BUTTON_UP; - sev.button.button = button; - sev.button.down = k == .down; - sev.button.x = x; - sev.button.y = y; - }, - } - const before = c.SDL_GetModState(); - var mods: c.SDL_Keymod = 0; - if (held & 4 != 0) mods |= c.SDL_KMOD_LSHIFT; - if (held & 8 != 0) mods |= c.SDL_KMOD_LALT; - if (held & 16 != 0) mods |= c.SDL_KMOD_LCTRL; - c.SDL_SetModState(mods); - dispatch(gp, in, &sev); - c.SDL_SetModState(before); - } - } else if (std.mem.eql(u8, event[0..semi], "finger")) { - if (parseFinger(fields)) |finger| if (g) |gp| { - var wpw: c_int = 0; - var wph: c_int = 0; - _ = c.SDL_GetWindowSizeInPixels(gp.window, &wpw, &wph); - const win_w: f32 = @floatFromInt(@max(wpw, 1)); - const win_h: f32 = @floatFromInt(@max(wph, 1)); - handleFinger(&gp.touch, in, finger, win_w, win_h, @floatFromInt(gp.cell_w), @floatFromInt(gp.cell_h), @floatFromInt(gp.tagline_width)); - }; - } - continue; - } - - const result = f.parser.parse(f.buf[seq_start..len], gpa) catch break; - if (result.n == 0) { // partial sequence: shift to front, read more - std.mem.copyForwards(u8, f.buf[0 .. len - seq_start], f.buf[seq_start..len]); - f.fill = len - seq_start; - break; - } - seq_start += result.n; - const event = result.event orelse continue; - switch (event) { - .key_press => |key| if (f.in_paste) { - // A newline reads as Ctrl-J, as the tty's paste has it. - const text = vaxis_input.pasteBytes(key); - f.paste.appendSlice(gpa, text) catch {}; - } else { - postKey(in, key, if (key.text) |t| f.cache.put(t) else ""); - }, - .paste_start => { - f.in_paste = true; - f.paste.clearRetainingCapacity(); - }, - .paste_end => { - f.in_paste = false; - if (f.paste.items.len > 0) in.post(.{ .paste = f.paste.items }); - f.paste.clearAndFree(gpa); - }, - .mouse => |m| { - 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, - .none => .none, - else => null, - }; - if (button) |b| { - in.post(.{ .mouse = .{ - .button = b, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, - }, - .col = @intCast(@max(m.col, 0)), - .row = @intCast(@max(m.row, 0)), - .ctrl = m.mods.ctrl, - .shift = m.mods.shift, - .alt = m.mods.alt, - } }); - } - }, - .winsize => |vw| { - applyResize(in, g, @intCast(vw.cols), @intCast(vw.rows)); - }, - .paste => |text| { - in.post(.{ .paste = text }); - gpa.free(@constCast(text)); - }, - else => {}, - } - } - return false; - } - - fn applyResize(in: *Input, g: ?*Gui, cols: u16, rows: u16) void { - if (g) |gp| { - _ = c.SDL_SetWindowSize(gp.window, @intCast(cols * gp.cell_w), @intCast(rows * gp.cell_h)); - _ = c.SDL_SyncWindow(gp.window); - } else { - in.post(.{ .resize = .{ .cols = cols, .rows = rows } }); - } - } -}; - -fn parseFinger(payload: []const u8) ?Finger { - var parts = std.mem.splitScalar(u8, payload, ';'); - const type_name = parts.next() orelse return null; - const id_s = parts.next() orelse return null; - const x_s = parts.next() orelse return null; - const y_s = parts.next() orelse return null; - const pressure_s = parts.next() orelse return null; - if (parts.next() != null) return null; - _ = std.fmt.parseFloat(f32, pressure_s) catch return null; - const Name = enum { SDL_EVENT_FINGER_DOWN, down, SDL_EVENT_FINGER_MOTION, motion, SDL_EVENT_FINGER_UP, up, SDL_EVENT_FINGER_CANCELED, cancel }; - const kind: @FieldType(Finger, "kind") = switch (std.meta.stringToEnum(Name, type_name) orelse return null) { - .SDL_EVENT_FINGER_DOWN, .down => .down, - .SDL_EVENT_FINGER_MOTION, .motion => .motion, - .SDL_EVENT_FINGER_UP, .up => .up, - .SDL_EVENT_FINGER_CANCELED, .cancel => .cancel, - }; - return .{ - .kind = kind, - .id = std.fmt.parseInt(u64, id_s, 10) catch return null, - .x = std.fmt.parseFloat(f32, x_s) catch return null, - .y = std.fmt.parseFloat(f32, y_s) catch return null, - }; -} - -fn setStdinRaw() !void { - var term = try posix.tcgetattr(0); - term.iflag.BRKINT = false; - term.iflag.ICRNL = false; - term.iflag.INPCK = false; - term.iflag.ISTRIP = false; - term.iflag.IXON = false; - term.oflag.OPOST = false; - term.lflag.ECHO = false; - term.lflag.ICANON = false; - term.lflag.IEXTEN = false; - term.lflag.ISIG = false; - term.cc[@backingInt(posix.V.MIN)] = 1; - term.cc[@backingInt(posix.V.TIME)] = 0; - try posix.tcsetattr(0, .NOW, term); -} - -/// A key parsed from the stdin a test window reads, posted as the tty -/// posts one (vaxis_input): F-keys, Insert and the keypad included. `text` -/// is the key's text as the feed keeps it. -fn postKey(in: *Input, key: vaxis.Key, text: []const u8) void { - var ev = vaxis_input.keyEvent(key); - ev.key.text = text; - in.post(ev); -} - -const Input = struct { - core: *pardes.Pardes, - /// The shell whose window this is (views.zig: its view is `gview`). - shell: ?*Shell = null, - /// A replica client's (`runClient`): its inputs go to its link, never - /// straight to the core, which only reads here. - client: ?*Client = null, - quit: bool = false, - - fn post(in: *Input, ev: pardes.Event) void { - if (in.client) |r| return r.post(ev); - // The window's input is its own view's, a replica client's input - // the session's last or not. - if (in.shell) |s| if (s.core.live != s.gview) { - _ = s.windowView(); - }; - in.core.update(ev); - } - - fn close(in: *Input) void { - if (in.client) |r| { - r.link.quit = true; - in.quit = true; - return; - } - if (in.shell) |s| { - // The window, with replica clients: they keep the session, - // as a Detach would, the daemon holding it. - if (s.peers.count() > 0 and daemon.kept()) return s.closeTheWindow(); - } - in.core.quit = true; - in.quit = true; - } -}; - -fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { - if (comptime builtin.os.tag == .macos) { - if (sev.type == c.ui_macos_trackpad_event_type()) { - dispatchTrackpad(g, in, @ptrCast(@alignCast(sev))); - return; - } - } - // An input's time, for its latency to the frame that answers it - // (FrameStats): SDL's stamp, moved onto the monotonic clock. - switch (sev.type) { - c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_WHEEL => { - g.input_seen = true; - g.input_ns = monoNs(); - if (frame_probe) |probe| probe.input(monoNs() -| (c.SDL_GetTicksNS() -| sev.common.timestamp)); - }, - else => {}, - } - switch (sev.type) { - c.SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED => { - updateDisplayScale(g.window); - // Underlines are drawn into the glyphs a logical pixel thick. - resetGlyphAtlas(g); - if (in.client) |r| { - r.link.dirty = true; - } else in.core.needs_frame = true; - }, - else => {}, - } - switch (sev.type) { - c.SDL_EVENT_QUIT => { - in.shell = null; - in.close(); - }, - c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), - c.SDL_EVENT_WINDOW_FOCUS_GAINED => { - in.post(.{ .focus = true }); - if (in.client == null) upgrade.noticeNewer(in.core); - }, - c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }), - c.SDL_EVENT_WINDOW_MOUSE_LEAVE => { - g.pointer_present = false; - in.post(.pointer_leave); - }, - c.SDL_EVENT_KEY_DOWN => { - g.live_ctrl = (sev.key.mod & c.SDL_KMOD_CTRL) != 0; - g.live_alt = (sev.key.mod & c.SDL_KMOD_ALT) != 0; - const step: f32 = if (!g.live_ctrl) 0 else switch (sev.key.key) { - c.SDLK_EQUALS, c.SDLK_PLUS, c.SDLK_KP_PLUS => font_px_step, - c.SDLK_MINUS, c.SDLK_UNDERSCORE, c.SDLK_KP_MINUS => -font_px_step, - else => 0, - }; - if (step != 0) return setFontPx(g, in, std.math.clamp(g.px + step, font_px_min, font_px_max)); - keyDown(in, sev.key.key, sev.key.mod); - }, - c.SDL_EVENT_KEY_UP => { - g.live_ctrl = (sev.key.mod & c.SDL_KMOD_CTRL) != 0; - g.live_alt = (sev.key.mod & c.SDL_KMOD_ALT) != 0; - }, - c.SDL_EVENT_TEXT_INPUT => { - const tptr = sev.text.text orelse return; - var tlen: usize = 0; - while (tptr[tlen] != 0) : (tlen += 1) {} - if (tlen == 0) return; - const text: []const u8 = tptr[0..tlen]; - const view = std.unicode.Utf8View.init(text) catch return; - var it = view.iterator(); - var at: usize = 0; - while (it.nextCodepoint()) |cp| : (at = it.i) { - in.post(.{ .key = .{ .cp = cp, .text = text[at..it.i], .ctrl = g.live_ctrl, .alt = g.live_alt } }); - } - }, - c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => { - const b = sev.button; - const raw_button = if (comptime builtin.os.tag == .macos) - (if (b.down) g.trackpad.press(b.button) else g.trackpad.release(b.button) orelse return) - else - b.button; - const button: pardes.Mouse.Button = switch (raw_button) { - 1 => .left, - 2 => .middle, - 3 => .right, - 4 => .back, - 5 => .forward, - else => return, - }; - const mc = pointAt(g, in.core, b.x, b.y); - var ev = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()); - // Let go past the window's edge (SDL follows a held button out - // of the window: Wayland's implicit grab, X11's capture). - const win = windowGeometry(g.window); - ev.outside = !b.down and (b.x < 0 or b.y < 0 or b.x >= win.window_w or b.y >= win.window_h); - in.post(.{ .mouse = ev }); - }, - c.SDL_EVENT_MOUSE_MOTION => { - const m = sev.motion; - const physical_held: ?pardes.Mouse.Button = if ((m.state & c.SDL_BUTTON_LMASK) != 0) - .left - else if ((m.state & c.SDL_BUTTON_MMASK) != 0) - .middle - else if ((m.state & c.SDL_BUTTON_RMASK) != 0) - .right - else - null; - // A trackpad's latched button (Trackpad.press), not SDL's. - const held: ?pardes.Mouse.Button = if (comptime builtin.os.tag == .macos) - (if (g.trackpad.forced) null else if (g.trackpad.button) |b| switch (b) { - 1 => .left, - 2 => .middle, - 3 => .right, - else => physical_held, - } else physical_held) - else - physical_held; - const mc = pointAt(g, in.core, m.x, m.y); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, pointerMods()) }); - }, - c.SDL_EVENT_MOUSE_WHEEL => { - const w = sev.wheel; - if (w.y == 0 and w.x == 0) return; - const mc = pointAt(g, in.core, w.mouse_x, w.mouse_y); - wheelAt(g, in, .{ .x = w.x, .y = w.y, .integer_y = w.integer_y, .mods = pointerMods() }, mc); - }, - c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP, c.SDL_EVENT_FINGER_CANCELED => { - const f = sev.tfinger; - // Indirect Mac touches are decoded by AppKit at the pointer, - // never as absolute positions across the window. - if (comptime builtin.os.tag == .macos) if (f.touchID == c.SDL_MOUSE_TOUCHID) return; - const finger: Finger = .{ - .kind = switch (sev.type) { - c.SDL_EVENT_FINGER_DOWN => .down, - c.SDL_EVENT_FINGER_MOTION => .motion, - c.SDL_EVENT_FINGER_UP => .up, - else => .cancel, - }, - .id = @intCast(f.fingerID), - .x = f.x, - .y = f.y, - }; - var pw: c_int = 0; - var ph: c_int = 0; - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - const win_w: f32 = @floatFromInt(@max(pw, 1)); - const win_h: f32 = @floatFromInt(@max(ph, 1)); - const fcw: f32 = @floatFromInt(g.cell_w); - const fch: f32 = @floatFromInt(g.cell_h); - handleFinger(&g.touch, in, finger, win_w, win_h, fcw, fch, @floatFromInt(g.tagline_width)); - }, - // The window's font size; a Linux touchpad's pinch stays unused. - c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => if (comptime builtin.os.tag == .macos) setFontPx(g, in, Trackpad.pinch(g.px, sev.pinch.scale)), - c.SDL_EVENT_GAMEPAD_ADDED => { - if (g.gamepad == null) g.gamepad = c.SDL_OpenGamepad(sev.gdevice.which); - }, - c.SDL_EVENT_GAMEPAD_REMOVED => { - if (g.gamepad) |pad| { - c.SDL_CloseGamepad(pad); - g.gamepad = null; - } - }, - c.SDL_EVENT_GAMEPAD_BUTTON_DOWN, - c.SDL_EVENT_GAMEPAD_BUTTON_UP, - c.SDL_EVENT_GAMEPAD_AXIS_MOTION, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_UP, - => { - const pad_input: deck.Input = switch (sev.type) { - c.SDL_EVENT_GAMEPAD_BUTTON_DOWN, c.SDL_EVENT_GAMEPAD_BUTTON_UP => .{ .button = .{ - .idx = sev.gbutton.button, - .down = sev.gbutton.down, - } }, - c.SDL_EVENT_GAMEPAD_AXIS_MOTION => .{ .axis = .{ - .idx = sev.gaxis.axis, - .value = sev.gaxis.value, - } }, - else => .{ .touch = .{ - .pad = @intCast(std.math.clamp(sev.gtouchpad.touchpad, 0, 255)), - .phase = switch (sev.type) { - c.SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN => .down, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_UP => .up, - else => .motion, - }, - .x = sev.gtouchpad.x, - .y = sev.gtouchpad.y, - .pressure = sev.gtouchpad.pressure, - } }, - }; - var acts: [3]deck.Action = undefined; - for (acts[0..g.deck.feed(pad_input, &acts)]) |act| switch (act) { - .move => |mv| { - const geometry = windowGeometry(g.window); - const old = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - const dx = mv.dx * geometry.window_w / geometry.pixel_w; - const dy = mv.dy * geometry.window_h / geometry.pixel_h; - g.pad_x = std.math.clamp(g.pad_x + dx, 0, geometry.window_w - 1); - g.pad_y = std.math.clamp(g.pad_y + dy, 0, geometry.window_h - 1); - c.SDL_WarpMouseInWindow(g.window, g.pad_x, g.pad_y); - g.pointer_present = true; - const mc = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - g.pointer_cell = mc; - if (mc.col == old.col and mc.row == old.row) continue; - const held = heldPointerButton(g); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); - }, - .click => |ck| { - const button: pardes.Mouse.Button = switch (ck.which) { - .select => .left, - .execute => .middle, - .look => .right, - }; - const mc = pointAt(g, in.core, g.pad_x, g.pad_y); - in.post(.{ .mouse = .{ - .button = button, - .kind = if (ck.down) .press else .release, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - } }); - }, - .wheel => |ticks| { - const mc = pointAt(g, in.core, g.pad_x, g.pad_y); - var left = ticks; - while (left != 0) { - left += if (ticks > 0) -1 else 1; - in.post(.{ .mouse = .{ - .button = if (ticks > 0) .wheel_down else .wheel_up, - .kind = .press, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - } }); - } - }, - .key => |k| in.post(.{ - .key = switch (k) { - .n => .{ .cp = 'n', .text = "n" }, - .cap_n => .{ .cp = 'N', .text = "N" }, - .enter => .{ .cp = pardes.Key.enter }, - .tab => .{ .cp = pardes.Key.tab }, - .tty_toggle => .{ .cp = in.core.opts.tty_toggle, .ctrl = true }, - }, - }), - .rumble => if (g.gamepad) |pad| { - _ = c.SDL_RumbleGamepad(pad, 0x4000, 0x4000, 80); - }, - }; - }, - else => {}, - } -} - -fn keyDown(in: *Input, sym: c.SDL_Keycode, mod: c.SDL_Keymod) void { - const ctrl = (mod & c.SDL_KMOD_CTRL) != 0; - const alt = (mod & c.SDL_KMOD_ALT) != 0; - const shift = (mod & c.SDL_KMOD_SHIFT) != 0; - const gui_mod = (mod & c.SDL_KMOD_GUI) != 0; - const cp: u21 = switch (sym) { - c.SDLK_RETURN, c.SDLK_KP_ENTER => pardes.Key.enter, - c.SDLK_BACKSPACE => pardes.Key.backspace, - c.SDLK_TAB => pardes.Key.tab, - c.SDLK_ESCAPE => pardes.Key.escape, - c.SDLK_LEFT => pardes.Key.left, - c.SDLK_RIGHT => pardes.Key.right, - c.SDLK_UP => pardes.Key.up, - c.SDLK_DOWN => pardes.Key.down, - c.SDLK_HOME => pardes.Key.home, - c.SDLK_END => pardes.Key.end, - c.SDLK_PAGEUP => pardes.Key.page_up, - c.SDLK_PAGEDOWN => pardes.Key.page_down, - c.SDLK_DELETE => pardes.Key.delete, - c.SDLK_INSERT => pardes.Key.insert, - c.SDLK_PRINTSCREEN => pardes.Key.print_screen, - c.SDLK_SCROLLLOCK => pardes.Key.scroll_lock, - c.SDLK_PAUSE => pardes.Key.pause, - c.SDLK_APPLICATION => pardes.Key.menu, - c.SDLK_F1...c.SDLK_F12 => pardes.Key.f1 + @as(u21, @intCast(sym - c.SDLK_F1)), - c.SDLK_F13...c.SDLK_F24 => pardes.Key.f1 + 12 + @as(u21, @intCast(sym - c.SDLK_F13)), - else => blk: { - if (!(ctrl or alt or gui_mod)) break :blk 0; - if (sym < 128 and sym >= ' ') break :blk @intCast(sym); - break :blk 0; - }, - }; - if (cp == 0) return; - in.post(.{ .key = .{ .cp = cp, .ctrl = ctrl, .alt = alt, .shift = shift } }); -} - -fn gridCellAtDimensions( - core: *const pardes.Pardes, - x: f32, - y: f32, - body_w: f32, - body_h: f32, - tagline_w: f32, -) MouseCell { - const row: u16 = @intFromFloat(@min(@floor(@max(y, 0) / @max(body_h, 1)), 10_000)); - var point: MouseCell = .{ .col = @intFromFloat(@min(@floor(@max(x, 0) / @max(body_w, 1)), 10_000)), .row = row }; - // On the rule over this row, which is where two panes meet if they do. - point.rule_above = row > 0 and @max(y, 0) - @as(f32, @floatFromInt(row)) * @max(body_h, 1) < dp(rule_grab_px); - if (onGrid(core, x / @max(body_w, 1), y / @max(body_h, 1))) for (core.surface.tagLayers()) |*layer| { - if (layer.tagHit(x, y, body_w, body_h, tagline_w, @floatFromInt(core.view().row_metrics.tagline_h))) |hit| { - point.tag_hit = hit; - break; - } - }; - return point; -} - -/// Whether a point, in cells, is on the grid. -fn onGrid(core: *const pardes.Pardes, x: f32, y: f32) bool { - return std.math.isFinite(x) and std.math.isFinite(y) and x >= 0 and y >= 0 and - x < @as(f32, @floatFromInt(core.view().screen_w)) and y < @as(f32, @floatFromInt(core.view().screen_h)); -} - -fn gridCellAtPixels(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { - var point = gridCellAtDimensions(core, x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width)); - if (onGrid(core, x / @as(f32, @floatFromInt(g.cell_w)), y / @as(f32, @floatFromInt(g.cell_h)))) for (core.surface.bodyLayers()) |*layer| { - if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| { - point.body_hit = hit; - break; - } - }; - return point; -} - -/// A wheel turned over grid cell `mc` (SDL's sign: up positive): the -/// part of dispatch after the pointer is placed, so a test can turn it. -fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { - if (w.y != 0 and std.math.isFinite(w.y)) { - const core = in.core; - const hit: ?usize = for (core.panes, 0..) |slot, i| { - if (slot == null) continue; - const r = core.view().rects[i]; - if (mc.col >= r.x and mc.col < r.x + r.w and mc.row >= r.y and mc.row < r.y + r.h) break i; - } else null; - if (g.scroll_pane) |old| if (hit == null or hit.? != old) { - resetScroll(g); - }; - if (hit) |id| { - const pane = core.panes[id].?; - if (pane.addon != null) { - // A kind's (a PDF's strip): the turn as it came, a - // touchpad's fraction of a notch too (pa_mouse.amount). - resetScroll(g); - in.post(.{ .mouse = .{ .button = if (w.y < 0) .wheel_down else .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt, .amount = @abs(w.y) } }); - } else if (!w.mods.shift and pane.isTerminal() and pardes.Term.modes(pane.terminal).wheel) { - // The program's (codex, htop, less): every whole turn goes - // to it, no glide, for nothing of ours moves. Shift keeps - // a terminal's wheel pardes's. - resetScroll(g); - g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y); - while (g.program_wheel >= 1) : (g.program_wheel -= 1) - in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); - while (g.program_wheel <= -1) : (g.program_wheel += 1) - in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); - } else if (in.client != null) { - // A replica client's notch is whole rows at once, with no - // glide; a touchpad's fraction is the window's picture - // (scrollRows), its whole rows ordinary inputs. - if (notchOf(w.y, w.integer_y)) |lines| { - g.program_wheel = @floatFromInt(lines); - } else { - g.scroll_pane = id; - g.scroll_col = mc.col; - g.scroll_row = mc.row; - g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); - } - while (g.program_wheel >= 1) : (g.program_wheel -= 1) - in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); - while (g.program_wheel <= -1) : (g.program_wheel += 1) - in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); - } else { - g.scroll_pane = id; - g.scroll_col = mc.col; - g.scroll_row = mc.row; - // A mouse wheel's notch is a whole line and - // glides (G6); a touchpad's fraction moves the - // picture by itself, under the finger. - if (notchOf(w.y, w.integer_y)) |lines| { - g.scroll_notch +|= lines; - } else g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); - } - } - } - var horizontal: i32 = if (w.x == 0 or !std.math.isFinite(w.x)) 0 else if (w.x > 0) 1 else -1; - if (w.precise and std.math.isFinite(w.x)) { - g.program_wheel_x += std.math.clamp(w.x, -64, 64); - horizontal = @intFromFloat(@trunc(g.program_wheel_x)); - g.program_wheel_x -= @floatFromInt(horizontal); - } - while (horizontal != 0) { - in.post(.{ .mouse = .{ - .button = if (horizontal > 0) .wheel_right else .wheel_left, - .kind = .press, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - .ctrl = w.mods.ctrl, - .shift = w.mods.shift, - .alt = w.mods.alt, - } }); - horizontal += if (horizontal > 0) -1 else 1; - } -} - -/// `precise`: a Mac trackpad's columns (dispatchTrackpad), whose -/// horizontal fraction is kept toward the next turn. -const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, precise: bool = false, mods: PointerMods = .{} }; - -/// The window's font at `want` pixels: a key's step, a pinch. A client's -/// view is sized by its next loop, as its input. -fn setFontPx(g: *Gui, in: *Input, want: f32) void { - if (want == g.px) return; - g.px = want; - if (in.client) |r| { - refitFont(g, null); - r.link.dirty = true; - } else { - refitFont(g, in.core); - observeGuiFont(g, in.core); - } -} - -/// A Mac trackpad's gesture, decoded by macos_trackpad.m (Trackpad.zig's -/// policy): fingers, a pinch's zoom, a swipe's Back/Forward, a rotation's -/// n/N, a force click's Look, and a two-finger scroll by the pixel. -fn dispatchTrackpad(g: *Gui, in: *Input, ev: *const c.UITrackpadEvent) void { - g.input_seen = true; - switch (ev.kind) { - c.UI_TRACKPAD_FINGERS => g.trackpad.countFingers(@intCast(@max(ev.fingers, 0))), - c.UI_TRACKPAD_PINCH => if (g.trackpad.magnify(g.px, ev.a, ev.phase)) |want| setFontPx(g, in, want), - c.UI_TRACKPAD_HISTORY => { - if (ev.a == 0 or !std.math.isFinite(ev.a)) return; - const back = ev.a < 0; - const jumps = &in.core.view().jumps; - const can_jump = jumps.n > 0 and (if (back) jumps.cur > 0 else jumps.cur + 1 < jumps.n); - in.post(.{ .command = if (back) "Back" else "Forward" }); - if (comptime builtin.os.tag == .macos) if (can_jump) c.ui_macos_trackpad_haptic(); - }, - c.UI_TRACKPAD_ROTATE => { - const pane = in.core.panes[in.core.view().active] orelse return; - // Search-step keys never become text in insert/raw mode. - if (pane.body.mode != .normal) return; - var ticks = g.trackpad.rotate(ev.a, ev.phase); - while (ticks != 0) { - in.post(.{ .key = .{ .cp = if (ticks > 0) 'N' else 'n' } }); - if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_haptic(); - ticks += if (ticks > 0) -1 else 1; - } - }, - c.UI_TRACKPAD_PRESSURE => { - const previous = g.trackpad.force(ev.a) orelse return; - const mc = mouseCell(g, in.core, ev.x, ev.y); - in.post(.{ .mouse = pointerMouse(if (previous == 2) .middle else .left, .release, mc, pointerMods()) }); - in.post(.{ .mouse = pointerMouse(.right, .press, mc, pointerMods()) }); - in.post(.{ .mouse = pointerMouse(.right, .release, mc, pointerMods()) }); - }, - c.UI_TRACKPAD_SCROLL => { - const mc = pointAt(g, in.core, ev.x, ev.y); - // AppKit reports points; the grid is measured in backing pixels. - const geometry = windowGeometry(g.window); - const rows = ev.b * geometry.pixel_h / geometry.window_h / @as(f32, @floatFromInt(g.cell_h)); - const cols = -ev.a * geometry.pixel_w / geometry.window_w / @as(f32, @floatFromInt(g.cell_w)); - wheelAt(g, in, .{ .x = cols, .y = rows, .precise = true, .mods = pointerMods() }, mc); - }, - else => {}, - } -} - -/// The modifiers held with a pointer event, as the core's Mouse carries them. -const PointerMods = struct { ctrl: bool = false, shift: bool = false, alt: bool = false, super: bool = false }; - -/// The core's Mouse for an SDL press, release or move over cell `mc`. -fn pointerMouse(button: pardes.Mouse.Button, kind: pardes.Mouse.Kind, mc: MouseCell, mods: PointerMods) pardes.Mouse { - return .{ - .button = button, - .kind = kind, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - .rule_above = (kind == .press or kind == .release) and mc.rule_above, - .ctrl = mods.ctrl, - .shift = mods.shift, - .alt = mods.alt, - .super = mods.super, - }; -} - -fn pointerMods() PointerMods { - const m = c.SDL_GetModState(); - return .{ .ctrl = (m & c.SDL_KMOD_CTRL) != 0, .shift = (m & c.SDL_KMOD_SHIFT) != 0, .alt = (m & c.SDL_KMOD_ALT) != 0, .super = (m & c.SDL_KMOD_GUI) != 0 }; -} - -fn mouseCellWithGeometry(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32, geometry: WindowGeometry) MouseCell { - const physical = windowPointToPixels(geometry, x, y); - return gridCellAtPixels(g, core, physical.x, physical.y); -} - -fn mouseCell(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { - return mouseCellWithGeometry(g, core, x, y, windowGeometry(g.window)); -} - -/// The pointer at window point (x, y), as an event or the gamepad puts it -/// there: where the window keeps it, and the cell under it. -fn pointAt(g: *Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { - g.pad_x = x; - g.pad_y = y; - g.pointer_present = true; - const mc = mouseCell(g, core, x, y); - g.pointer_cell = mc; - return mc; -} - -/// SDL's hit test, asked as the pointer moves over the window: a blank cell -/// of the workspace tag (tagline.workspaceBlank) is the window's to drag, as -/// a title bar is. SDL gives the compositor a B1 press there (Wayland's -/// xdg_toplevel.move, X11's _NET_WM_MOVERESIZE, macOS's own drag), so the -/// press never reaches the core; B2 and B3 there still do. -fn hitTest(_: ?*c.SDL_Window, area: [*c]const c.SDL_Point, data: ?*anyopaque) callconv(.c) c.SDL_HitTestResult { - const g: *Gui = @ptrCast(@alignCast(data orelse return c.SDL_HITTEST_NORMAL)); - const core = g.hit_core orelse return c.SDL_HITTEST_NORMAL; - if (area == null) return c.SDL_HITTEST_NORMAL; - const mc = mouseCell(g, core, @floatFromInt(area.*.x), @floatFromInt(area.*.y)); - return if (pardes.tagline.workspaceBlank(core, mc.col, mc.row, mc.tag_hit)) c.SDL_HITTEST_DRAGGABLE else c.SDL_HITTEST_NORMAL; -} - -fn heldPointerButton(g: *const Gui) ?pardes.Mouse.Button { - const buttons = c.SDL_GetMouseState(null, null); - if ((buttons & c.SDL_BUTTON_LMASK) != 0 or g.deck.r2_held or g.deck.rpad_click) return .left; - if ((buttons & c.SDL_BUTTON_MMASK) != 0 or g.deck.l2_held) return .middle; - if ((buttons & c.SDL_BUTTON_RMASK) != 0 or g.deck.look_held) return .right; - return null; -} - -fn refreshPresentedPointer(g: *Gui, in: *Input) void { - if (!g.pointer_present) return; - const mc = mouseCell(g, in.core, g.pad_x, g.pad_y); - const moved = g.pointer_cell == null or g.pointer_cell.?.col != mc.col or g.pointer_cell.?.row != mc.row; - g.pointer_cell = mc; - if (!moved) return; - const held = heldPointerButton(g); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); -} - -fn pollGamepad(g: *Gui, in: *Input) void { - const pad = g.gamepad orelse return; - const geometry = windowGeometry(g.window); - const deadzone: f32 = 8000; - const ax: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_RIGHTX)); - const ay: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_RIGHTY)); - const old = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - const speed: f32 = @as(f32, @floatFromInt(g.cell_h)) * 0.4; - const speed_x = speed * geometry.window_w / geometry.pixel_w; - const speed_y = speed * geometry.window_h / geometry.pixel_h; - const pointer_moved = @abs(ax) > deadzone or @abs(ay) > deadzone; - if (@abs(ax) > deadzone) g.pad_x = std.math.clamp(g.pad_x + ax / 32767.0 * speed_x, 0, geometry.window_w - 1); - if (@abs(ay) > deadzone) g.pad_y = std.math.clamp(g.pad_y + ay / 32767.0 * speed_y, 0, geometry.window_h - 1); - if (pointer_moved) { - g.pointer_present = true; - c.SDL_WarpMouseInWindow(g.window, g.pad_x, g.pad_y); - } - const mc = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - if (g.pointer_present) { - g.pointer_cell = mc; - if (mc.col != old.col or mc.row != old.row) { - const held = heldPointerButton(g); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); - } - } - const lx: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_LEFTX)); - const ly: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_LEFTY)); - if (@abs(ly) > deadzone) g.pad_scroll += ly / 32767.0 * 0.15; - if (@abs(lx) > deadzone) g.pad_scroll_h += lx / 32767.0 * 0.15; - while (@abs(g.pad_scroll) >= 1.0) { - const button: pardes.Mouse.Button = if (g.pad_scroll < 0) .wheel_up else .wheel_down; - g.pad_scroll += if (g.pad_scroll < 0) 1.0 else -1.0; - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit } }); - } - while (@abs(g.pad_scroll_h) >= 1.0) { - const button: pardes.Mouse.Button = if (g.pad_scroll_h < 0) .wheel_left else .wheel_right; - g.pad_scroll_h += if (g.pad_scroll_h < 0) 1.0 else -1.0; - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit } }); - } -} - -const Shell = struct { - core: *pardes.Pardes, - /// The window's, while one is open; null while detached (`detached` has - /// it). - gui: ?*Gui = null, - detached: ?*Gui = null, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: host_io.Adoptions = .{}, - io: std.Io, - gpa: std.mem.Allocator, - fs: ?*ninep_io.Listener = null, - lsp_allocator: std.mem.Allocator, - prompt_rcs: *const host_io.Shell.PromptFiles, - ptys: *[pardes.MAX_PANES]?Pty, - gens: *[pardes.MAX_PANES]u32, - queue: *Queue, - /// What drainQueue takes each wakeup, kept rather than rebuilt. - batch: Queue.Batch = .{}, - pipe_tasks: *PipeTasks, - job_tasks: PipeTasks = .{}, - inotify_fd: c_int, - watches: *file_watch.Table, - threads_ok: bool = false, - test_mode: bool = false, - feed: StdinFeed = .{}, - presented: bool = false, - skipped_presents: u8 = 0, - surface: ?*const pardes.Surface = null, - /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), in test mode. - test_clock: ?u64 = null, - /// The display rate a virtual clock stands in for (PARDES_TEST_HZ). - test_hz: u64 = 60, - /// The tick a paced frame is sampled at (waitInput): the clock the - /// core is advanced to while anything moves. - paced_ns: ?u64 = null, - /// The view the window shows (views.zig); a second window on the - /// session is a replica client of it (`pardes-gui --attach`). - gview: u8 = 0, - /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). - upgrade_asked: ?u8 = null, - /// This window a replica client of a session elsewhere (`runClient`). - client: ?*Client = null, - /// The session's replica clients (src/replica.zig), on sockets: views - /// of their own with no window here. - 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 (tui.zig's `mail_only`). - mail_only: bool = false, - waited: bool = false, - /// 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, - - fn closePaneShell(ctx: ?*anyopaque, pane: u8) void { - shellOf(ctx).closePty(pane); - } - - fn closePty(s: *Shell, pane: u8) void { - const pt = if (s.ptys[pane]) |*pt| pt else return; - // Out of the queue first, which lets go a reader waiting for room - // in it; then its read is canceled (or, at its end, it is joined). - s.queue.cancelReader(pane, s.gens[pane]); - if (pt.reader) |*reader| { - reader.cancel(s.queue.io); // the Io it was started on (startReader) - pt.reader = null; - } - _ = libc.close(pt.fd); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - s.ptys[pane] = null; - } - - fn stopPtys(s: *Shell) void { - for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); - for (s.gens) |*gen| gen.* +%= 1; - } - - fn shutdownPtys(s: *Shell) void { - s.stopPtys(); - host_io.waitRetired(); - } - - fn reconcilePtys(s: *Shell) void { - for (s.ptys, 0..) |slot, pane| if (slot) |pt| { - const current = s.core.panes[pane]; - if (current == null or current.?.serial != pt.serial or !current.?.isTerminal()) - s.closePty(@intCast(pane)); - }; - } - - fn host(s: *Shell) pardes.Host { - return .{ .ctx = s, .vtable = &vtable }; - } - - /// Detach: the window closed, the session left running with no - /// window, for `pardes-gui --attach` to open one again. - fn detachWindow(ctx: ?*anyopaque) void { - const s = shellOf(ctx); - // A replica client's: its link ends. - if (s.peers.detach(s.core.live)) return; - if (s.gui == null) return s.core.reportFailure(s.core.view().active, "Detach: no window is open"); - if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session; closing its window ends it"); - s.closeTheWindow(); - } - - /// The window's own clock: the test's virtual one, the paced tick, else - /// SDL's. - fn ownNow(s: *const Shell) u64 { - return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); - } - - /// The Gui's window's view live, for what the window does to its own - /// (its size, its scroll): a replica client's input may have been the - /// last. True when it was not, and is now. - fn windowView(s: *Shell) bool { - if (s.core.live == s.gview or !pardes.views.isOpen(s.core, s.gview)) return false; - s.core.toView(s.gview); - return true; - } - - /// With replica clients, a wait takes one person's input and its pump - /// 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; - if (!s.peers.recording) return false; - const native_gesture = if (comptime builtin.os.tag == .macos) sev.type == c.ui_macos_trackpad_event_type() else false; - if (!native_gesture) switch (sev.type) { - c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP, c.SDL_EVENT_MOUSE_MOTION, c.SDL_EVENT_MOUSE_WHEEL, c.SDL_EVENT_WINDOW_FOCUS_GAINED, c.SDL_EVENT_WINDOW_FOCUS_LOST, c.SDL_EVENT_WINDOW_MOUSE_LEAVE, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP => {}, - else => return false, - }; - if (s.took_input) { - s.held = sev.*; - return true; - } - s.took_input = true; - return false; - } - - fn closeTheWindow(s: *Shell) void { - const g = s.gui orelse return; - closeWindow(g); - s.detached = g; - s.gui = null; - s.presented = false; - s.surface = null; - // Its clients look at it still (Peers keeps it attended). - s.peers.detached = true; - s.core.unattended = s.peers.count() == 0; - daemon.setState(true); - } - - fn openTheWindow(s: *Shell) void { - const g = s.detached orelse return; - if (!reopenWindow(g)) { - log.err("--attach: no window: {s}", .{c.SDL_GetError()}); - return daemon.setState(true); - } - s.gui = g; - s.detached = null; - s.peers.detached = false; - s.core.unattended = false; - s.core.needs_frame = true; - resetScroll(g); - daemon.setState(false); - } - - fn watched(ctx: ?*anyopaque) bool { - return shellOf(ctx).gui != null; - } - - fn adopt(ctx: ?*anyopaque, pane: u8) void { - const s = shellOf(ctx); - s.adoptions.ask(s.core, pane); - } - - fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { - const s = shellOf(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 and - /// daemon link kept open across (upgrade.zig); the new process opens - /// its windows again. Returns only when it could not be, as it was. - fn upgradeNow(s: *Shell, pane: u8) void { - 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"); - // The new process starts SDL's video afresh, and that fails with no - // display at all (the screen off and its outputs gone): it ended the - // session (a detached one's hidden window needs one too). - var displays: c_int = 0; - if (c.SDL_GetDisplays(&displays)) |list| c.SDL_free(list); - if (displays == 0) return core.reportFailure(pane, "Upgrade: the display has no screen now (off, or gone), and the new build could not open its window; this session stays as it is until one is back"); - // 9P is served while the new binary is asked, 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, and what was read goes in: drained, - // the readers stopped (a reader waiting for room has it then), and - // what they pushed meanwhile drained. - s.drainQueue(); - for (s.ptys) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| { - r.cancel(s.queue.io); - pt.reader = null; - }; - s.drainQueue(); - 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, .window = s.gui != null, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd); - var at_buf: [1024:0]u8 = undefined; - const failed = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why); - // As it was: its ptys read on. - for (s.ptys, 0..) |*slot, id| if (slot.*) |*pt| if (pt.fd >= 0 and pt.reader == null) { - pt.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), s.gens[id]) catch null; - }; - 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.adoptions.adoptShell(s.core, k.pid, k.fd); - continue; - } - s.ptys[k.pane] = .{ .fd = k.fd, .pid = k.pid, .serial = pane.?.serial, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - - /// An upgraded session's window, its view's again; every other view - /// but a replica client's, kept for its rejoin (views.away), closes. - fn resumeWindow(s: *Shell) void { - s.gview = s.core.live; - for (0..pardes.views.max) |i| { - const k: u8 = @intCast(i); - if (k != s.gview and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.core.closeView(k); - } - } - - const vtable: pardes.Host.VTable = .{ - .wait_input = waitInput, - .now = guiNow, - .present = present, - .post_present = postPresent, - .poll_frame = pollFrame, - .watched = watched, - .detach = detachWindow, - .adopt = adopt, - .upgrade = upgradeAsked, - .spawn = spawnPane, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePaneShell, - .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, - .start = host_io.startDetached, - .lsp = lsp, - .pipe = pipe, - .search = search, - .hand_over = handOver, - .job = kindJob, - }; - - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *Shell) void { - host_io.takeExits(s.core, s.ptys, s, closeWatched); - } - - fn closeWatched(s: *Shell, id: usize) void { - s.closePty(@intCast(id)); - } - - /// A client's queue holds its draws alone: each landed for its pane's - /// next paint. Whether any came. - fn takeDraws(s: *Shell) bool { - s.queue.takeInto(&s.batch); - for (s.batch.slice()) |m| switch (m) { - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(s.core); - }, - else => m.deinit(s.gpa, s.lsp_allocator), - }; - return s.batch.slice().len > 0; - } - - fn drainQueue(s: *Shell) void { - s.reconcilePtys(); - // After this batch's output, which an exit is told behind. - defer s.takeExits(); - s.queue.takeInto(&s.batch); - const msgs = &s.batch; - if (msgs.len > 0) s.mail_only = false; - var check_files = false; - for (msgs.slice()) |m| switch (m) { - .output => |o| { - if (s.gens[o.pane] == o.gen) - s.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); - s.gpa.free(o.bytes); - }, - .eof => |e| { - if (s.gens[e.pane] == e.gen) eof: { - if (e.failure) |err| { - s.closePty(e.pane); - s.core.readerFailed(e.pane, err); - break :eof; - } - const pt = if (s.ptys[e.pane]) |*pt| pt else { - s.core.update(.{ .eof = .{ .pane = e.pane } }); - break :eof; - }; - // 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(s.core, s.ptys, e.pane, s, closeWatched); - break :eof; - } - // 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 unwatched = if (s.core.panes[e.pane]) |pane| pane.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status != null) pt.pid = 0; // reaped: no shell to retire - s.closePty(e.pane); - if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); - s.core.update(.{ .eof = .{ .pane = e.pane } }); - } - }, - .lsp => |l| { - s.core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } }); - if (l.rows) |rows| s.lsp_allocator.free(rows); - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - s.core.setStatus(s.core.view().active, message.stamp(&mbuf, "lsp", text)); - s.lsp_allocator.free(text); - }, - .pipe => |response_value| { - var response = response_value; - s.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 => |b| { - s.core.update(.{ .search = b }); - b.deinit(s.gpa); - }, - .handed => |h| { - s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); - s.gpa.free(h.words); - }, - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(s.core); - }, - .files_changed => check_files = true, - .fs_ready => {}, - .window => if (s.gui == null) s.openTheWindow(), - .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), - }; - if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) - s.queue.push(.files_changed); - } -}; - -fn wakeFs(ctx: ?*anyopaque) void { - const q: *Queue = @ptrCast(@alignCast(ctx.?)); - q.push(.fs_ready); -} - -fn shellOf(ctx: ?*anyopaque) *Shell { - return @ptrCast(@alignCast(ctx.?)); -} - -fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { - const s = shellOf(ctx); - const core = s.core; - var in: Input = .{ .core = core, .shell = s }; - s.mail_only = true; - s.took_input = false; - defer s.waited = true; - if (s.gui) |g| { - if (s.surface != null) startGamepads(g); - var sev = std.mem.zeroes(c.SDL_Event); - // Idle is asleep until an event: SDL's own, and the user events the - // shell's queue raises for a terminal's output, a completion, a file - // system request. What the shell moves or times itself polls every - // frame: a smooth scroll, a gamepad's sticks, the test stdin feed, - // a present to retry. A minimized window sleeps through the core's animation - // too: nothing shows it, and it is caught up at once when the window - // is back. - const polls = g.scroll_lag != 0 or g.scroll_delta != 0 or g.scroll_notch != 0 or frontendMoving(g) or g.gamepad != null or s.test_mode or core.needs_frame; - const minimized = !s.test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; - // A latency trace is fed on stdin, whose poll below paces the loop: - // waiting here too would make every tick cost two frames. - const poll_ms: c_int = 16; - const waited: c_int = if (latency_fd >= 0) 0 else if (minimized) -1 else if (timeout_ms != 0) @min(@as(c_int, @intCast(@min(timeout_ms, std.math.maxInt(c_int)))), if (polls) poll_ms else std.math.maxInt(c_int)) else if (polls) poll_ms else -1; - // The cursor's blink is the window's to time (Gui.input_ns): - // a frame a loop through an edge, else a wake at the next one; none - // while the window is minimized or unfocused. A virtual clock never - // blinks, so goldens hold still. - const blink = if (s.test_clock != null or minimized or s.surface == null) null else blinkNow(g, s.core.settings.cursor_blink); - const blink_ms: ?c_int = if (blink) |b| (if (b.edge) 1 else if (b.next_ns) |next| @as(c_int, @intCast(@min(std.math.maxInt(c_int), next / std.time.ns_per_ms + 1))) else null) else null; - const blinked: c_int = if (blink_ms) |b| (if (waited < 0) b else @min(waited, b)) else waited; - // The timedemo's next step is a wake too. - var ms: c_int = if (demoDue(g)) |due| (if (blinked < 0) due else @min(blinked, due)) else blinked; - // While anything moves, frames are paced as a game's are: one a - // display refresh, on a grid of ticks a period apart, each sampled - // at its tick (guiNow), however early or late the loop got there. - // Input that comes between two ticks is acted on as it comes (the - // core's state is never held back) and drawn at the next tick. Not - // paced, the loop ran as fast as it could present (the soft present - // has no vsync), ~230 frames a second on a 60 Hz display, and the - // compositor showed whichever was newest at each refresh: motion - // sampled at random phase, uneven steps, a judder in every scroll. - // ponytail: the period is the display mode's refresh and the grid's - // phase is our own, not the display's (no vblank time to read on the - // soft present); a 59.94 Hz display drifts a tick every 17 s. The - // upgrade: the presentation feedback protocol's timestamps. - const paced = s.test_clock == null and latency_fd < 0 and !s.test_mode and !minimized and frontendMoving(g); - var tick: u64 = 0; - if (paced) { - const period = refreshNs(g); - const now = c.SDL_GetTicksNS(); - // A motion from rest draws at once; one under way, at its next - // tick, skipping (never bunching) the ticks a slow frame missed. - tick = if (g.pace_ns != 0 and now -| g.pace_ns < 2 * period) g.pace_ns + period else now; - if (tick < now) tick += (now - tick) / period * period; - // Waited out polling, below. - ms = 0; - } - g.input_seen = false; - // An input held from the last wait (`split`) is this one's, at once. - const held = s.held; - s.held = null; - if (held) |h| sev = h; - // The wait is the 9P connections' turn with the core. - pardes.turn.rest(); - const got = held != null or c.SDL_WaitEventTimeout(&sev, ms); - pardes.turn.wake(); - // A virtual clock: while a render-time animation moves, each loop - // is a presented frame and moves it by one display frame - // (PARDES_TEST_HZ), events or not, as a real display's present - // would; otherwise a wait that ran out moves it exactly to the - // core's wake. - // Through an edge, or woken for the next: the shell redraws the last - // frame with the new alpha, no core render. - if (blink_ms != null and (blink.?.edge or !got)) g.blink_due = true; - if (s.test_clock) |*virtual| { - if (frontendMoving(g)) { - const display = virtual.* + std.time.ns_per_s / s.test_hz; - virtual.* = if (core.nextWake()) |due| @max(virtual.*, @min(due, display)) else display; - } else if (timeout_ms != 0 and (!got or !core.needs_frame)) { - // A wait that ran out, or one a stray event cut short while - // nothing owes a frame: time moves to the core's wake all - // the same, so a steady trickle of events (a pty's, the - // test feed's) cannot hold a virtual clock still forever. - virtual.* = @max(virtual.*, core.nextWake() orelse virtual.*); - } - } - if (got) { - // A run of queued motions is one move to its last position (the - // handler reads only absolute x/y and held buttons): acting on - // each would repeat hover and selection work the next undoes. - var motion: ?c.SDL_Event = null; - while (true) { - if (s.split(&sev)) break; - if (sev.type == c.SDL_EVENT_MOUSE_MOTION and (motion == null or motion.?.motion.windowID == sev.motion.windowID)) { - motion = sev; - } else { - if (motion) |*m| { - _ = s.windowView(); - dispatch(g, &in, m); - } - motion = null; - if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { - motion = sev; - } else { - _ = s.windowView(); - dispatch(g, &in, &sev); - } - } - if (!c.SDL_PollEvent(&sev)) break; - } - if (motion) |*m| { - _ = s.windowView(); - dispatch(g, &in, m); - } - } - runDemo(g, &in, core); - // Paced: what came before the tick is in; wait out the rest of it, - // unless an input came: its frame is drawn at once (the paced loop - // never adds a tick to an input's latency), and the ticks after it - // run from it. A stream's repeat too: the picture it moves is on - // the stream's straight line wherever it is sampled, so drawing it - // between two ticks costs no evenness, and holding it to the tick - // cost a held key 7 ms of latency. - if (paced and g.input_seen) tick = c.SDL_GetTicksNS(); - // The tick is waited out polling, not asleep, as a game's frame - // limiter spins: asleep between 60 Hz frames, the CPU's clock fell - // (intel_pstate, 4.9 GHz down toward 0.8) and every frame, an - // input's first among them, took 2-5x as long: input-to-present p50 - // 1.9 ms spinning against 7-8 ms asleep. - // ponytail: a core while something moves (~250 ms a scroll); a - // sleep to a millisecond short of the tick if the power matters more. - while (paced and !g.input_seen and s.held == null) { - if (tick -| c.SDL_GetTicksNS() < 50 * std.time.ns_per_us) break; - pardes.turn.rest(); - const more = c.SDL_PollEvent(&sev); - pardes.turn.wake(); - if (more) { - if (!s.split(&sev)) { - _ = s.windowView(); - dispatch(g, &in, &sev); - while (c.SDL_PollEvent(&sev)) { - if (s.split(&sev)) break; - _ = s.windowView(); - dispatch(g, &in, &sev); - } - } - } else { - // The events asked for every 100 µs, the core busy between. - const until = c.SDL_GetTicksNS() + 100 * std.time.ns_per_us; - while (c.SDL_GetTicksNS() < @min(until, tick)) std.atomic.spinLoopHint(); - } - runDemo(g, &in, core); - if (g.input_seen) tick = c.SDL_GetTicksNS(); - } - s.paced_ns = if (paced) tick else null; - if (paced) g.pace_ns = tick; - } else waitDetached(core, timeout_ms); - if (s.test_mode) { - if (s.feed.pump(s.gpa, &in, s.gui) catch true) { - core.quit = true; - return; - } - } - s.drainQueue(); - if (s.gui) |g| pollGamepad(g, &in); -} - -/// Detached: no window, asleep until the queue's wake (an SDL user event: -/// a pty's output, the daemon's window request), the core's next wake, or a -/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them, -/// messages go on the clock (the pump's, after this wait), which wakes it. -fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { - var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1; - for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { - ms = if (ms < 0) 100 else @min(ms, 100); - break; - }; - var sev = std.mem.zeroes(c.SDL_Event); - pardes.turn.rest(); - var got = c.SDL_WaitEventTimeout(&sev, ms); - pardes.turn.wake(); - while (got) : (got = c.SDL_PollEvent(&sev)) { - if (sev.type == c.SDL_EVENT_QUIT) core.quit = true; - } -} - -fn pollFrame(ctx: ?*anyopaque) void { - const s = shellOf(ctx); - s.reconcilePtys(); - const core = s.core; - if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); - // The authority owns its terminals even with its window closed. - pollCwds(core, s.ptys); - const g = s.gui orelse { - if (core.settings.window_opacity_pending) { - var unchanged_opacity: u8 = 100; - finishWindowOpacity(core, &unchanged_opacity, if (core.settings.window_opacity == 100) null else "requires a native SDL window"); - } - return; - }; - // A replica client's view live: the window's own view back before what - // the window does to it (its size, its scroll, its font). - if (core.live != s.gview) { - const geom = windowCells(g); - const due = g.scroll_pane != null or g.scroll_notch != 0 or g.glide.moving() or - core.settings.font.tagline_percent != g.tagline_percent or core.settings.font.pending or - (if (core.views[s.gview]) |*own| resizeOf(own, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height) != null else false); - if (due) _ = s.windowView(); - } - syncWindowOpacity(g, core); - core.frames.period_ns = refreshNs(g); - syncTaglineFont(g, core); - if (core.takeFontRequest()) |path| blk: { - const bytes = filesystem.readFile(s.gpa, path) catch { - core.rejectFont(); - break :blk; - }; - if (!g.atlas.setFont(s.gpa, bytes)) { - log.err("ui_font_new failed: {s}", .{path}); - core.rejectFont(); - break :blk; - } - if (core.settings.font.requested_size_hundredths != 0) - g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100; - setGuiFontName(g, core.settings.font.requested_name.get()); - refitFont(g, core); - acknowledgeGuiFont(g, core); - } - const geom = windowCells(g); - if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g); - stepScroll(g, core, s.gpa); - if (s.test_mode) writeTestStatus(g, core, s.presented); - // A blink edge, or the window's own motion (its glide, its caret, a - // jump's trail): the last frame again, moved on, no core render. - if ((g.blink_due or frontendMoving(g)) and !core.needs_frame and s.presented) if (s.surface) |frame| { - g.blink_due = false; - g.now_ns = s.ownNow(); - s.presented = renderFrame(g, s.gpa, core, frame) catch false; - }; -} - -/// PARDES_FRAMES_CAPTURE's directory, and how many frames it has. -var frame_capture_dir: ?[]const u8 = null; -var frame_capture_count: u32 = 0; - -fn captureSeries(pixels: []const u8, w: u32, h: u32) void { - const dir = frame_capture_dir orelse return; - var path_buf: [4096]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{d:0>6}.bgra", .{ dir, frame_capture_count }, 0) catch return; - const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, pixels.ptr, pixels.len); - _ = libc.close(fd); - const times = std.fmt.bufPrintSentinel(&path_buf, "{s}/times.txt", .{dir}, 0) catch return; - const tf = libc.open(times, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, @as(libc.mode_t, 0o644)); - if (tf < 0) return; - var line_buf: [96]u8 = undefined; - const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}\n", .{ frame_capture_count, monoNs(), w, h }) catch unreachable; // four numbers fit 96 - _ = libc.write(tf, line.ptr, line.len); - _ = libc.close(tf); - frame_capture_count += 1; -} - -/// The core's frame probe (FrameStats), for the latency of the inputs the -/// shell reads and the zones its own work goes in; null in tests. -var frame_probe: ?*pardes.FrameStats = null; - -/// How long until the timedemo's next step, ms; null when none runs. -fn demoDue(g: *const Gui) ?c_int { - const next = g.demo_next orelse return null; - if (g.demo_start_ns == 0 or next >= g.demo.len) return 0; - const at = g.demo_start_ns + @as(u64, g.demo[next].at_ms) * std.time.ns_per_ms; - return @intCast(@min(std.math.maxInt(c_int), (at -| monoNs()) / std.time.ns_per_ms)); -} - -/// PARDES_FRAMES_DEMO: the steps of FrameStats.demo whose time has come, -/// through the paths the window's own wheel and keys take, over the -/// focused pane's body; its clock starts at the first loop. Its end -/// ends the session (PARDES_FRAMES has the timings then). -fn runDemo(g: *Gui, in: *Input, core: *pardes.Pardes) void { - const v = core.view(); - const steps = g.demo; - var next = g.demo_next orelse return; - const now = monoNs(); - if (g.demo_start_ns == 0) { - g.demo_start_ns = now; - core.frames.demo_ns = now; - core.frames.demo = g.demo; - } - defer g.demo_next = next; - while (next < steps.len and g.demo_start_ns + @as(u64, steps[next].at_ms) * std.time.ns_per_ms <= now) : (next += 1) { - const r = v.rects[v.active]; - if (steps[next].act != .phase) g.input_seen = true; - switch (steps[next].act) { - .wheel => |notches| { - core.frames.input(now); - wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); - }, - .touch => |lines| { - core.frames.input(now); - wheelAt(g, in, .{ .y = -lines }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); - }, - .key => |key| { - core.frames.input(now); - in.post(.{ .key = key }); - }, - .phase => {}, - .click => |click| { - core.frames.input(now); - const pane = core.panes[v.active] orelse continue; - const top = core.bodyTop(pane, r); - const row: u16 = top + @as(u16, @intFromFloat(click.at * @as(f32, @floatFromInt(r.h -| pane.tag_rows -| 1)))); - const col: u16 = if (click.rail) r.x else r.x + config.GUTTER + 4; - for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| in.post(.{ .mouse = .{ .button = click.button, .kind = kind, .col = col, .row = row } }); - }, - .rail_wheel => |notches| { - core.frames.input(now); - wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x, .row = r.y + r.h / 2 }); - }, - .paste => |text| { - core.frames.input(now); - in.post(.{ .paste = text }); - }, - .exec => |line| { - core.frames.input(now); - var newest: u32 = 0; - for (core.panes) |slot| if (slot) |pane| { - newest = @max(newest, pane.serial); - }; - _ = pardes.exec.executeFrom(core, v.active, line, false); - // What it opened is what the next steps scroll. - for (core.panes, 0..) |slot, id| if (slot) |pane| if (pane.serial > newest) { - v.active = id; - core.needs_frame = true; - }; - }, - .end => in.close(), - } - } -} - -/// The blink now, from the frame's time since input and how long ago it -/// arrived; null where nothing blinks (off, idle, an unfocused window). -/// The cursor's opacity under blink: solid while typing and for -/// `hold_ns` after, then on and off with an eased edge, solid again after -/// `idle_ns` of no input. `edge` says whether it is mid-edge (a frame is -/// owed), `next_ns` when the next edge starts (a wake). -pub const Blink = struct { - pub const hold_ns: u64 = 500 * std.time.ns_per_ms; - pub const idle_ns: u64 = 10 * std.time.ns_per_s; - pub const half_ns: u64 = 530 * std.time.ns_per_ms; - pub const edge_ns: u64 = 80 * std.time.ns_per_ms; - - alpha: f32, - edge: bool, - next_ns: ?u64, - - pub fn at(now_ns: u64, input_ns: u64) Blink { - const since = now_ns -| input_ns; - if (since < hold_ns) return .{ .alpha = 1, .edge = false, .next_ns = input_ns + hold_ns + half_ns - edge_ns }; - if (since >= hold_ns + idle_ns) return .{ .alpha = 1, .edge = false, .next_ns = null }; - const t = (since - hold_ns) % (2 * half_ns); - const cycle_start = now_ns - t; - // On for a half, easing out over its last `edge_ns`; off for a half, - // easing back in over its last. - if (t < half_ns - edge_ns) return .{ .alpha = 1, .edge = false, .next_ns = cycle_start + half_ns - edge_ns }; - if (t < half_ns) return .{ .alpha = 1 - smooth(@as(f32, @floatFromInt(t - (half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; - if (t < 2 * half_ns - edge_ns) return .{ .alpha = 0, .edge = false, .next_ns = cycle_start + 2 * half_ns - edge_ns }; - return .{ .alpha = smooth(@as(f32, @floatFromInt(t - (2 * half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; - } - - fn smooth(x: f32) f32 { - const u = std.math.clamp(x, 0, 1); - return u * u * (3 - 2 * u); - } -}; - -fn blinkNow(g: *const Gui, on: bool) ?Blink { - if (g.no_blink or !on or !g.caret.placed) return null; - if (c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_INPUT_FOCUS == 0) return null; - const since = monoNs() -| g.input_ns; - // Relative to now: `next_ns` is how long until the next edge. - const b = Blink.at(since, 0); - return .{ .alpha = b.alpha, .edge = b.edge, .next_ns = if (b.next_ns) |next| next -| since else null }; -} - -/// One refresh of the display the window is on, in ns; a frame of the -/// core's where the display does not say. -fn refreshNs(g: *const Gui) u64 { - const mode = c.SDL_GetCurrentDisplayMode(c.SDL_GetDisplayForWindow(g.window)) orelse return pardes.frame_ns; - if (!(mode.*.refresh_rate > 1)) return pardes.frame_ns; - return @intFromFloat(@as(f64, std.time.ns_per_s) / mode.*.refresh_rate); -} - -fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8) void { - core.windowOpacityDone(applied.*, failure); - applied.* = core.settings.window_opacity; -} - -fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void { - if (!core.settings.window_opacity_pending) return; - // The first opacity under 100 on Wayland: the window made again, - // transparent, presenting through SDL_Renderer from then on (the - // capture's format, the swapchain's, is one it uploads). At a start's - // own WindowOpacity this is before its first frame, so unseen. - const unorm = g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM or g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; - if (g.wayland and !g.present.surface_opacity and core.settings.window_opacity < 100 and unorm) { - // A `--detach` session's window stays hidden. - const hidden = c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_HIDDEN; - const mode = g.present.present_mode; - closeWindow(g); - g.present.soft_present = true; - g.present.surface_opacity = true; - g.present.present_mode = c.SDL_GPU_PRESENTMODE_VSYNC; - g.win_flags |= c.SDL_WINDOW_TRANSPARENT | hidden; - log.info("WindowOpacity under 100: the window made again, transparent, presenting through SDL_Renderer", .{}); - if (!reopenWindow(g)) { - // No renderer for it: opaque again, as it was. - g.present.soft_present = false; - g.present.surface_opacity = false; - g.present.present_mode = mode; - g.win_flags &= ~@as(c.SDL_WindowFlags, c.SDL_WINDOW_TRANSPARENT); - if (!reopenWindow(g)) core.quit = true; - } - g.win_flags &= ~hidden; - } - // Offscreen captures also support per-pixel alpha. Never approximate this - // with SDL_SetWindowOpacity: that would make foreground text translucent. - finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100) - null - else - "background transparency requires a native Wayland or alpha-capable SDL window"); -} - -fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { - const s = shellOf(ctx); - const core = s.core; - // A replica client draws outside the pump, which marks it there. - if (s.client != null) core.frames.mark_render = pardes.FrameStats.nowNs(); - const g = s.gui orelse return; - frame_started_ns = monoNs(); - const frame = surface; - s.surface = frame; - g.frame_arrival_ns = monoNs(); - g.now_ns = s.ownNow(); - s.presented = renderFrame(g, s.gpa, core, frame) catch |err| blk: { - log.err("render: {t}", .{err}); - break :blk false; - }; - // A skipped swapchain image would otherwise hide this input's frame until - // the next event. A few retries only: a minimized window never gets one. - s.skipped_presents = if (s.presented) 0 else s.skipped_presents +| 1; - if (!s.presented and s.skipped_presents <= 3) core.present_skipped = true; -} - -/// The gamepad subsystem, started once the first frame is drawn, as the -/// loop first waits: its scan (udev, hidapi, libusb) took 40 ms of a start. -/// A pad plugged in already is added by it (GAMEPAD_ADDED). -fn startGamepads(g: *Gui) void { - if (g.gamepads) return; - g.gamepads = true; - if (!c.SDL_InitSubSystem(c.SDL_INIT_GAMEPAD)) log.warn("SDL_InitSubSystem(GAMEPAD): {s}", .{c.SDL_GetError()}); -} - -fn postPresent(ctx: ?*anyopaque) void { - const s = shellOf(ctx); - const g = s.gui orelse return; - // No image (a minimized window): nothing was drawn to point at. - if (!s.presented) return; - // A client's view live: the window's frame counts when its own view is - // live and drawn. - if (s.core.live != s.gview) return; - var in: Input = .{ .core = s.core }; - refreshPresentedPointer(g, &in); - s.core.presented(); -} - -fn guiNow(ctx: ?*anyopaque) u64 { - const s = shellOf(ctx); - if (s.waited) { - s.waited = false; - if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns; - } - return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); -} - -fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { - const s = shellOf(ctx); - if (s.adoptions.take(pane)) |a| return takeShell(s, 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.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(pane, err); - return s.core.shellFailed(pane, err); - }; - s.closePty(pane); - if (s.ptys[pane] != null) { - _ = libc.close(child.file.handle); - host_io.retireShell(child.pid); - return s.core.reportError(pane, "shell", error.WorkersBusy); - } - s.gens[pane] +%= 1; - const command = s.core.panes[pane].?.command != null; - const pt: Pty = .{ .fd = child.file.handle, .pid = child.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - s.ptys[pane] = pt; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - if (!s.threads_ok) return; - s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { - s.closePty(pane); - return s.core.reportError(pane, "terminal reader", err); - }; -} - -/// An adopted shell, running already, as pane `pane`'s: told the size twice -/// (one it never had, then the pane's), which makes it redraw. -fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { - s.closePty(pane); - s.gens[pane] +%= 1; - s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .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) return; - s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { - s.closePty(pane); - return s.core.reportError(pane, "terminal reader", err); - }; -} - -/// The daemon's thread: what it says, onto the queue (drainQueue). -fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const s: *Shell = @ptrCast(@alignCast(ctx)); - const q = s.queue; - switch (note) { - .attach => |a| { - // A terminal for a window session: the daemon refuses that kind - // before it is sent, so only an old one's would be here. - if (a.tty >= 0) _ = libc.close(a.tty); - if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a window session takes no terminal"}); - if (a.tty < 0) q.push(.window); - }, - .adopted => |a| { - for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); - q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); - }, - // Joined at the next step boundary (Peers, any thread). - .replica => |j| s.peers.handed(j.fd, j.view), - } -} - -fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { - const s = shellOf(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.fd, bytes); -} - -fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { - const s = shellOf(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); - } -} - -fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { - const s = shellOf(ctx); - // A command whose exit is recorded is reaped: its group may be another's. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); -} - -fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.fd); -} - -fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.fd, buf); -} - -fn killJob(ctx: ?*anyopaque, pane: u8) bool { - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.fd); -} - -fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { - const s = shellOf(ctx); - host_io.writeFile(s.core, s.watches, pane, path, bytes); -} - -fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - host_io.writeDump(shellOf(ctx).core, bytes); -} - -fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const s = shellOf(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, s.watches, pane, on, mode)) - s.queue.push(.files_changed); -} - -fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = shellOf(ctx); - if (file_watch.applyThemeEffect( - s.core, - s.gpa, - s.inotify_fd, - s.watches, - generation, - on, - )) s.queue.push(.files_changed); -} - -fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { - const s = shellOf(ctx); - host_io.dumpThemes(s.core, s.io, s.gpa, pane); -} - -fn putClipboard(gpa: std.mem.Allocator, text: []const u8) void { - const z = gpa.dupeSentinel(u8, text, 0) catch return; - defer gpa.free(z); - _ = c.SDL_SetClipboardText(z.ptr); -} - -fn takeClipboard() ?[:0]u8 { - const raw = c.SDL_GetClipboardText() orelse return null; - const text = std.mem.span(raw); - if (text.len == 0) { - c.SDL_free(raw); - return null; - } - return text; -} - -fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { - putClipboard(shellOf(ctx).gpa, text); -} - -fn readClipboard(ctx: ?*anyopaque) void { - const text = takeClipboard() orelse return; - defer c.SDL_free(text.ptr); - shellOf(ctx).core.update(.{ .paste = text }); -} - -fn openLink(ctx: ?*anyopaque, url: []const u8) void { - _ = ctx; - look.openLink(url); // desktop browser -} - -fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { - const s = shellOf(ctx); - if (s.threads_ok) return s.queue.startLsp(s.core, req); - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); -} - -fn pipe(ctx: ?*anyopaque, id: u32) void { - const s = shellOf(ctx); - if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe); - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); -} - -/// A draw (api.draw) on a worker, as a job is. -fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { - const s = shellOf(ctx); - return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob); -} - -fn kindJob(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { - const s = shellOf(ctx); - if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob); - host_io.KindJob.runHere(s.core, pane, serial, token); -} - -fn search(ctx: ?*anyopaque, gen: u32) void { - const s = shellOf(ctx); - if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.queue, Queue.pushSearch); - pardes.Stream.runHere(s.core, gen); -} - -/// Handover `seq`'s dump to its file, and a worker to carry it to another -/// window (Handover.start). A new window is as big as this one, and where -/// the pointer let go of it when the display lets a window say where it -/// goes (X11; on Wayland the compositor places it). -fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { - const s = shellOf(ctx); - const Handover = pardes.Handover; - const path = Handover.dumpPath(s.gpa, seq) catch |err| return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); - // A dump not written, or not carried, goes: what failed is said. - const cwd = std.Io.Dir.cwd(); - cwd.writeFile(s.io, .{ .sub_path = path, .data = bytes, .flags = .{ .permissions = .fromMode(0o600) } }) catch { - cwd.deleteFile(s.io, path) catch {}; - s.gpa.free(path); - return s.core.update(.{ .handed = .{ .seq = seq, .failure = "cannot write its dump" } }); - }; - const job = s.gpa.create(Handover.Job) catch { - cwd.deleteFile(s.io, path) catch {}; - s.gpa.free(path); - return s.core.update(.{ .handed = .{ .seq = seq, .failure = "out of memory" } }); - }; - job.* = .{ .gpa = s.gpa, .seq = seq, .path = path, .post = Queue.pushHanded, .post_ctx = s.queue }; - if (s.fs) |f| { - job.own_len = @min(f.path().len, job.own.len); - @memcpy(job.own[0..job.own_len], f.path()[0..job.own_len]); - } - if (s.gui) |g| { - var w: c_int = 0; - var h: c_int = 0; - _ = c.SDL_GetWindowSize(g.window, &w, &h); - var gx: f32 = 0; - var gy: f32 = 0; - _ = c.SDL_GetGlobalMouseState(&gx, &gy); - const placed = !std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); - const geometry = (if (placed) - std.fmt.bufPrint(&job.geometry, "{d}x{d}+{d}+{d}", .{ w, h, @as(i32, @intFromFloat(gx)) - 40, @as(i32, @intFromFloat(gy)) - 10 }) - else - std.fmt.bufPrint(&job.geometry, "{d}x{d}", .{ w, h })) catch unreachable; // four c_ints fit 64 - job.geometry_len = geometry.len; - } - s.core.handover.start(s.io, job) catch |err| { - cwd.deleteFile(s.io, path) catch {}; - s.gpa.free(path); - s.gpa.destroy(job); - return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); - }; -} - -fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { - for (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.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(id, cwd); - }; -} - -fn accumulateWheelDelta(pending: f32, raw_y: f32) f32 { - if (!std.math.isFinite(raw_y)) return pending; - const next = pending - raw_y; - return if (std.math.isFinite(next)) next else pending; -} - -fn boundScrollDelta(lag: f32, delta: f32, body_rows: u16) f32 { - const limit: f32 = @floatFromInt(body_rows); - return std.math.clamp(lag + delta, -limit, limit) - lag; -} - -fn applyScrollDelta(lag: f32, delta: f32) struct { lag: f32, rows: i32 } { - var l = lag + delta; - var rows: i32 = 0; - while ((delta > 0 and l > 0) or (delta < 0 and l < 0)) { - const down = l > 0; - l += if (down) -1 else 1; - rows += if (down) 1 else -1; - } - return .{ .lag = l, .rows = rows }; -} - -/// A mouse wheel's step as whole lines (down positive), or null for a -/// touchpad's fraction, which follows the finger as it is. -fn notchOf(raw_y: f32, integer_y: i32) ?i32 { - if (!std.math.isFinite(raw_y) or integer_y == 0 or raw_y != @round(raw_y)) return null; - return @intFromFloat(std.math.clamp(-raw_y, -64, 64)); -} - -const Glide = pardes.glide.Glide; - -/// Feeds a wheel's notches to the core, and keeps what moved the view for -/// the frame's glide (Glide.frame). -fn stepGlide(g: *Gui, core: *pardes.Pardes) void { - const notch = g.scroll_notch; - g.scroll_notch = 0; - var wheeled: ?usize = null; - if (notch != 0) wheel: { - const id = g.scroll_pane orelse break :wheel; - const pane = core.panes[id] orelse { - resetScroll(g); - break :wheel; - }; - const r = core.view().rects[id]; - if (r.h <= pane.tag_rows or r.w <= config.GUTTER) { - resetScroll(g); - break :wheel; - } - var left = notch; - while (left != 0) { - const down = left > 0; - left += if (down) -1 else 1; - const was = pane.scroll(); - // Shift: pardes's own scroll, never a program's wheel. - core.update(.{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = g.scroll_col, .row = g.scroll_row, .shift = true } }); - if (pane.scroll() == was) break; - wheeled = id; - } - if (wheeled != null) core.needs_frame = true; - } - if (wheeled != null) g.glide_wheeled = wheeled; - // Not a view a touchpad is moving by the pixel. - g.glide_direct = if (g.scroll_lag != 0 or g.scroll_delta != 0) g.scroll_pane else null; -} - -/// The window's own motions under way (its glide, its caret, a jump's -/// trail): it draws their frames itself, on its own clock. -fn frontendMoving(g: *const Gui) bool { - return g.glide.moving() or g.caret.moving() or g.trail.active; -} - -/// The frame's glide (Glide.frame) on the window's clock, with what moved -/// its view since the last. -fn glideFrame(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { - g.glide.frame(gpa, surface, g.now_ns, g.glide_wheeled, g.glide_direct); - g.glide_wheeled = null; -} - -/// The window's loop over a text pane under a wheel, as waitInput and the -/// pump run it but with no window: a frame's turns (wheelAt), pollFrame's -/// stepScroll, and a frame drawn only when one is owed (the core's -/// needs_frame, or the window's own motion). `drawn` is the picture the -/// window shows, its first line and its offset, as of the last frame drawn; -/// `now` the picture as the window holds it. -const WheelRun = struct { - g: Gui, - core: *pardes.Pardes, - arena: std.heap.ArenaAllocator, - mc: MouseCell, - drawn: f32 = 0, - now_ns: u64 = std.time.ns_per_s, - - fn init(gpa: std.mem.Allocator, core: *pardes.Pardes) !WheelRun { - var wr: WheelRun = .{ .g = testGui(10, 20, 6, 12), .core = core, .arena = .init(gpa), .mc = undefined }; - const r = core.view().rects[core.view().active]; - wr.mc = .{ .col = r.x + 10, .row = r.y + r.h / 2 }; - core.advance(wr.now_ns); - _ = try core.render(wr.arena.allocator()); - try wr.frame(gpa, &.{}); - return wr; - } - - fn deinit(wr: *WheelRun, gpa: std.mem.Allocator) void { - wr.g.glide.deinit(gpa); - gpa.free(wr.g.scroll_edge); - wr.arena.deinit(); - } - - /// The picture as the window holds it now, in lines. - fn picture(wr: *const WheelRun) f32 { - const line: f32 = @floatFromInt(wr.core.panes[wr.core.view().active].?.scroll()); - return line + if (wr.g.glide.follow.offset != 0) wr.g.glide.follow.offset else wr.g.scroll_lag; - } - - /// One frame: SDL's turns (up positive), then a frame if one is owed. - fn frame(wr: *WheelRun, gpa: std.mem.Allocator, turns: []const f32) !void { - var in: Input = .{ .core = wr.core }; - for (turns) |y| wheelAt(&wr.g, &in, .{ .y = y, .integer_y = @intFromFloat(@trunc(y)) }, wr.mc); - wr.now_ns += std.time.ns_per_s / 60; - wr.core.advance(wr.now_ns); - stepScroll(&wr.g, wr.core, gpa); - if (!wr.core.needs_frame and !frontendMoving(&wr.g)) return; - _ = wr.arena.reset(.retain_capacity); - const s = try wr.core.render(wr.arena.allocator()); - wr.g.now_ns = wr.now_ns; - glideFrame(&wr.g, gpa, s); - wr.core.needs_frame = false; - wr.drawn = wr.picture(); - } -}; - -/// The scripted scroll sequence of the glide tests: a frame a 60 Hz -/// refresh, as the paced loop draws them (waitInput, then stepGlide, the -/// core's render and the frame's measure), an input on the frames `script` -/// names; each frame's picture offset and the core's first line. -const GlideRun = struct { - const Step = struct { frame: usize, key: pardes.Key }; - offsets: [600]f32 = undefined, - lines: [600]i64 = undefined, - carets: [600]f32 = undefined, - cells: [600]f32 = undefined, - frames: usize = 0, - - fn play(seq: *GlideRun, g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator, arena: *std.heap.ArenaAllocator, script: []const Step, frames: usize) !void { - var now: u64 = core.clock.now_ns; - var next: usize = 0; - for (0..frames) |frame| { - while (next < script.len and script[next].frame == frame) : (next += 1) core.update(.{ .key = script[next].key }); - now += std.time.ns_per_s / 60; - core.advance(now); - stepGlide(g, core); - _ = arena.reset(.retain_capacity); - const s = try core.render(arena.allocator()); - g.now_ns = now; - glideFrame(g, gpa, s); - seeCaret(g, s, fixedCellLayout(g), @floatFromInt(@as(u32, s.rows) * g.cell_h), now); - seq.offsets[frame] = g.glide.follow.offset; - seq.lines[frame] = @intCast(core.panes[core.view().active].?.file.?.scroll); - seq.carets[frame] = caretRow(g, s, now) orelse -1; - seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; - } - seq.frames = frames; - } - - /// The caret's invariants over the run: while its cell stays and it is - /// on it, it does not move a pixel; it only ever closes on its cell (a - /// twentieth of a row of play for a jump's bow); it lands within half a - /// second of its last change. - fn checkCaret(seq: *const GlideRun) !void { - var changed: usize = 0; - for (1..seq.frames) |k| { - if (seq.cells[k] < 0 or seq.cells[k - 1] < 0) continue; - if (seq.cells[k] != seq.cells[k - 1]) changed = k; - if (seq.cells[k] == seq.cells[k - 1] and seq.carets[k - 1] == seq.cells[k - 1]) try std.testing.expectEqual(seq.carets[k - 1], seq.carets[k]); - try std.testing.expect(@abs(seq.carets[k] - seq.cells[k]) <= @abs(seq.carets[k - 1] - seq.cells[k]) + 0.05); - if (k - changed == 30) try std.testing.expectEqual(seq.cells[k], seq.carets[k]); - } - } - - /// Frames from `from` until the picture is still: the scroll's glide. - fn settle(seq: *const GlideRun, from: usize) usize { - var k = from; - while (k < seq.frames and seq.offsets[k] != 0) k += 1; - return k - from; - } -}; - -fn resetScroll(g: *Gui) void { - g.scroll_pane = null; - g.scroll_delta = 0; - g.scroll_lag = 0; - g.scroll_idle = 0; - g.scroll_edge_len = 0; - g.scroll_notch = 0; - g.glide.stop(); -} - -/// Loop steps with no turn before a resting fraction settles; the share of -/// what is left a step takes (the glide's spring over a 60 Hz frame, -/// Follow.omega); and what is close enough to land on at once (under a -/// pixel of a row). -const settle_after = 2; -const settle_step: f32 = 1 - @exp(-pardes.glide.Follow.omega / 60.0); -const settle_land: f32 = 0.02; - -fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { - stepGlide(g, core); - var in: Input = .{ .core = core }; - _ = scrollRows(g, &in, gpa); -} - -/// A touchpad's fraction: the picture moved by it, and each whole row it -/// crosses posted to `in` (a replica client's go to its link, applied -/// after its view is parked again). True when the picture moved. -fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { - const core = in.core; - const id = g.scroll_pane orelse return false; - const pane = core.panes[id] orelse { - resetScroll(g); - return false; - }; - // A fine wheel's or a touchpad's turns stopped (SDL tells no gesture's - // end): the picture eases the rest of the way onto the core's row, on - // the glide's law, a step a frame, so it never rests a fraction of a - // row off its cells. The core's row is the next whole row the way the - // turns went (the lag is behind it going down, ahead going up), so the - // settle never moves against them; a turn mid-settle goes on from it. - if (g.scroll_delta != 0) { - g.scroll_idle = 0; - } else if (g.scroll_lag != 0 and g.glide.follow.offset == 0) { - g.scroll_idle +|= 1; - if (g.scroll_idle > settle_after) - g.scroll_delta = if (@abs(g.scroll_lag) < settle_land) -g.scroll_lag else -g.scroll_lag * settle_step; - } - const queued_delta = g.scroll_delta; - g.scroll_delta = 0; - if (queued_delta == 0) { - if (g.scroll_lag == 0 and g.scroll_notch == 0 and !g.glide.moving()) resetScroll(g); - return false; - } - const r = core.view().rects[id]; - if (r.h <= pane.tag_rows) { - resetScroll(g); - return false; - } - const delta = boundScrollDelta(g.scroll_lag, queued_delta, r.h - pane.tag_rows); - const st = applyScrollDelta(g.scroll_lag, delta); - var left = st.rows; - while (left != 0) { - const down = left > 0; - left += if (down) -1 else 1; - const was = pane.scroll(); - in.post(.{ - .mouse = .{ - .button = if (down) .wheel_down else .wheel_up, - .kind = .press, - .col = g.scroll_col, - .row = g.scroll_row, - .shift = true, // pardes's own scroll, never a program's wheel - }, - }); - // A replica client's rows apply after its view is parked again: - // its scroll has not moved yet. - if (in.client == null and pane.scroll() == was) { - resetScroll(g); - return false; - } - } - // The picture moved, by a fraction or back onto the core's row with - // the core where it was: that is a frame too, or the window rests on - // the last one, a fraction of a row off, and the next turn's frame - // jumps from there (against the turn when it reverses). - const moved = st.rows != 0 or st.lag != g.scroll_lag; - if (moved and in.client == null) core.needs_frame = true; - g.scroll_lag = st.lag; - g.scroll_rect = r; - const body_y = core.bodyTop(pane, r); - g.scroll_body_y = body_y; - g.scroll_body_h = r.h -| pane.tag_rows; - if (st.rows != 0) { - const s = &core.surface; - g.scroll_edge_len = 0; - if (r.w > config.GUTTER and r.h > pane.tag_rows and r.x + r.w <= s.cols) { - const bw = r.w - config.GUTTER; - const bh = g.scroll_body_h; - const k: u16 = @intCast(@min(@abs(st.rows), @as(i32, bh))); - const held = @min(pane.context_rows, bh - k); - const srow = body_y + (if (st.rows > 0) held + k - 1 else bh - k); - if (srow < s.rows) { - if (g.scroll_edge.len < bw) { - gpa.free(g.scroll_edge); - g.scroll_edge = gpa.alloc(pardes.Cell, bw) catch &.{}; - } - if (g.scroll_edge.len >= bw) { - @memcpy(g.scroll_edge[0..bw], s.cells[@as(usize, srow) * s.cols + r.x + config.GUTTER ..][0..bw]); - g.scroll_edge_len = bw; - } - } - } - } - if (g.scroll_lag == 0) resetScroll(g); - return moved; -} - -/// A scrolling body's picture: its rows moved by the lag, a glide's or a -/// touchpad's fraction of a row, and in the gap that opens the rows that -/// left. -fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: [3]u8, held: u16) u32 { - g.scroll_held_px = 0; - const glide = &g.glide; - const gliding = glide.follow.offset != 0; - const pane = if (gliding) glide.pane else g.scroll_pane orelse return 0; - const lag = if (gliding) glide.follow.offset else g.scroll_lag; - if (lag == 0) return 0; - const r = if (gliding) glide.rect else g.scroll_rect; - const bh = if (gliding) glide.body_h else g.scroll_body_h; - const y0 = if (gliding) glide.body_y else g.scroll_body_y; - const bw = r.w -| config.GUTTER; - const x0 = r.x + config.GUTTER; - if (bw == 0 or bh == 0 or x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us - // The scissor the shifted rows are drawn in is the scroll's. - g.scroll_rect = r; - g.scroll_body_y = y0; - g.scroll_body_h = bh; - var shifted = layout; - shifted.y_off -= lag * layout.h; - const kept = holdContext(g, surface, pane, held, bh, layout); - shifted.y_off += kept.lift; - // Only the rows the scissor shows: lagging a body or more, every body - // row is past the edge, and drawing them all was twice the frame's - // instances for the length of a long glide. - const gone: u16 = @intFromFloat(@min(@floor(@abs(lag)), @as(f32, @floatFromInt(bh)))); - var row = y0 + kept.rows + if (lag > 0) gone else 0; - const row_end = y0 + bh - if (lag < 0) gone else 0; - // A touchpad's block caret moves with its row; a glide's is drawn from - // its own springs (the quad), never carried by the text. - const caret: u32 = if (surface.cursor) |cu| (if (gliding or cu.bar) std.math.maxInt(u32) else @as(u32, cu.y) * surface.cols + cu.x) else std.math.maxInt(u32); - var n: u32 = 0; - while (row < row_end) : (row += 1) { - const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; - const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; - var col = x0; - while (col < x0 + bw) : (col += 1) { - emitInstance(g, instances, base + n, col, row, shifted, win_w, win_h, cellFontRole(&line[col]), line, col, row_cursor, @as(u32, row) * surface.cols + col == caret, page); - n += 1; - } - } - // A body layer's held rows are compact, so it has rows past the grid's - // (lifted into the body by what they save): the moving rows go on with - // them, or the band under the grid's last row shows the layer's, still. - if (pane < surface.body_layers.len and surface.body_layers[pane].context_rows != 0) { - const layer = &surface.body_layers[pane]; - if (layer.cols == bw) for (bh..layer.rows) |k| { - const line = layer.cells[k * layer.cols ..][0..layer.cols]; - for (0..bw) |c_i| { - emitInstance(g, instances, base + n, x0 + @as(u16, @intCast(c_i)), y0 + @as(u16, @intCast(k)), shifted, win_w, win_h, cellFontRole(&line[c_i]), line, c_i, null, false, page); - n += 1; - } - }; - } - if (!gliding) { - // A touchpad's fraction opens one row, the one that left: under the - // held rows, where the moving rows start. - if (g.scroll_edge_len >= bw) { - const erow: u16 = if (lag > 0) y0 + bh else y0 + kept.rows - 1; - var i: u16 = 0; - while (i < bw) : (i += 1) { - emitInstance(g, instances, base + n, x0 + i, erow, shifted, win_w, win_h, cellFontRole(&g.scroll_edge[i]), g.scroll_edge[0..bw], i, null, false, page); - n += 1; - } - } - return n; - } - // A glide's: rows past the top while the picture lags a move down, past - // the bottom for one up; as many as it opens. - const gap: u16 = @intFromFloat(@min(@ceil(@abs(lag)), @as(f32, @floatFromInt(@as(u32, bh) * Glide.reach)))); - const nkept = if (lag < 0) glide.nabove else glide.nbelow; - const rows = if (lag < 0) glide.above else glide.below; - for (0..@min(gap, nkept)) |i| { - const cells = rows[i * bw ..][0..bw]; - // Row -1 - i above the moving rows (under the held ones), or bh + i - // below the body, in grid rows. - const at_row: i32 = if (lag < 0) @as(i32, y0 + kept.rows) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); - var at = shifted; - // emitInstance takes an unsigned row: move the layout instead. - at.y_off += @as(f32, @floatFromInt(at_row - @as(i32, y0))) * layout.h; - for (0..bw) |c_i| { - emitInstance(g, instances, base + n, x0 + @as(u16, @intCast(c_i)), y0, at, win_w, win_h, cellFontRole(&cells[c_i]), cells, c_i, null, false, page); - n += 1; - } - } - return n; -} - -/// A scrolling body's tree-sitter context rows hold still: the shifted -/// rows start under them and are clipped below their band, and where a -/// body layer stacks them at the tagline's height -/// the rows under them are drawn up to meet them, where the layer has them. -fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh: u16, layout: CellLayout) struct { rows: u16, lift: f32 } { - const rows = @min(held, bh); - const layered = id < surface.body_layers.len and surface.body_layers[id].rows != 0 and surface.body_layers[id].context_rows != 0; - const row_px = if (layered) std.math.clamp(@as(f32, @floatFromInt(g.tagline_height)), 1, @max(1, layout.h)) else layout.h; - g.scroll_held_px = @as(f32, @floatFromInt(rows)) * row_px; - return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; -} - -fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { - const r = g.scroll_rect; - const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; - const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px; - const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px); - const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); - const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); - const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); - const y1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(py + ph))), y0, @as(i32, @intCast(sh))); - return .{ .x = x0, .y = y0, .w = x1 - x0, .h = y1 - y0 }; -} - -/// A placement the window shows as a texture: pixels, not glyph art. -fn texturePlacement(place: pardes.Placement) bool { - return !place.art.glyph and validImageBytes(place) != null; -} - -fn surfaceHasNativeKey(surface: *const pardes.Surface, key: u64) bool { - for (surface.placements.items) |place| { - if (texturePlacement(place) and place.key == key) return true; - } - return false; -} - -fn validImageBytes(place: pardes.Placement) ?u32 { - const r = place.raster; - // Rows packed: a texture upload takes no stride. - if (r.w == 0 or r.h == 0 or r.stride != r.w * 4) return null; - const bytes = std.math.mul(usize, r.stride, r.h) catch return null; - if (bytes > std.math.maxInt(u32)) return null; - return @intCast(bytes); -} - -/// Where the placement's pixels go in its cells: where it says, or fitted -/// there (no larger than it is, at the top left). -fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.NativeGeometry { - if (place.at) |at| return .{ .src = place.src, .dst = at }; - const bound_w = std.math.mul(u32, place.dst.w, g.cell_w) catch return null; - const bound_h = std.math.mul(u32, place.dst.h, g.cell_h) catch return null; - const fit = pardes.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null; - return .{ .src = place.src, .dst = fit.dst }; -} - -fn uploadNativeTexture( - g: *Gui, - gpa: std.mem.Allocator, - cmd: *c.SDL_GPUCommandBuffer, - place: pardes.Placement, -) !void { - const byte_len = validImageBytes(place) orelse return error.BadImage; - const r = place.raster; - const dirty: ?Cells.Dirty = if (place.dirty) |d| .{ .from = d.from, .y = d.y, .h = d.h } else null; - try g.cells.image(gpa, cmd, place.key, r.bytes()[0..byte_len], r.w, r.h, r.stride, dirty); -} - -fn appendPreparedImage(g: *Gui, gpa: std.mem.Allocator, place: pardes.Placement) void { - const texture = g.cells.native_images.get(place.key) orelse return; - if (nativePlaceGeometry(g, place) == null) return; - g.prepared_images.append(gpa, .{ .place = place, .texture = texture }) catch {}; -} - -fn emitPreparedImage( - g: *Gui, - surface: *const pardes.Surface, - instance: *ImageInstance, - prepared: PreparedImage, - win_w: f32, - win_h: f32, -) bool { - const place = prepared.place; - const body_x = @as(u32, place.dst.x) * g.cell_w; - const body_y = @as(u32, place.dst.y) * g.cell_h; - const geometry = nativePlaceGeometry(g, place) orelse return false; - // A strip's pictures lie at its whole pixel: up by the fraction left. - var scroll: f64 = 0; - for (surface.regionList()) |r| if (r.kind == .body and r.owner == place.pane) { - scroll = r.scroll_px; - break; - }; - const px0 = @as(f32, @floatFromInt(body_x + geometry.dst.x)); - const py0 = @as(f32, @floatFromInt(body_y + geometry.dst.y)) - @as(f32, @floatCast(scroll - @floor(scroll))); - const px1 = px0 + @as(f32, @floatFromInt(geometry.dst.w)); - const py1 = py0 + @as(f32, @floatFromInt(geometry.dst.h)); - const image_w: f32 = @floatFromInt(place.raster.w); - const image_h: f32 = @floatFromInt(place.raster.h); - instance.* = .{ - .x0 = (px0 / win_w) * 2.0 - 1.0, - .y0 = 1.0 - (py0 / win_h) * 2.0, - .x1 = (px1 / win_w) * 2.0 - 1.0, - .y1 = 1.0 - (py1 / win_h) * 2.0, - .u0 = @as(f32, @floatFromInt(geometry.src.x)) / image_w, - .v0 = @as(f32, @floatFromInt(geometry.src.y)) / image_h, - .u1 = @as(f32, @floatFromInt(geometry.src.x + geometry.src.w)) / image_w, - .v1 = @as(f32, @floatFromInt(geometry.src.y + geometry.src.h)) / image_h, - }; - return true; -} - -fn prepareNativeImages( - g: *Gui, - gpa: std.mem.Allocator, - cmd: *c.SDL_GPUCommandBuffer, - surface: *const pardes.Surface, - groups: *Groups, - sw: u32, - sh: u32, -) bool { - for (surface.placements.items) |place| { - if (!texturePlacement(place)) continue; - uploadNativeTexture(g, gpa, cmd, place) catch continue; - } - - while (true) { - var stale: [pardes.MAX_PANES]u64 = undefined; - var stale_len: usize = 0; - var iterator = g.cells.native_images.iterator(); - while (iterator.next()) |entry| { - if (surfaceHasNativeKey(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| g.cells.releaseImage(key); - if (stale_len < stale.len) break; - } - - g.prepared_images.clearRetainingCapacity(); - // The pictures are the page's: the other groups float over them. - for (surface.placements.items) |place| - if (texturePlacement(place)) appendPreparedImage(g, gpa, place); - prepareAddonGpu(g, gpa, cmd, surface); - groups.items[0].image_start = 0; - groups.items[0].image_count = std.math.cast(u32, g.prepared_images.items.len) orelse return false; - - const capacity = std.math.cast(u32, g.prepared_images.items.len) orelse return false; - if (capacity == 0) return true; - const instances = g.cells.mapImages(gpa, capacity) orelse return false; - const win_w: f32 = @floatFromInt(sw); - const win_h: f32 = @floatFromInt(sh); - var idx: u32 = 0; - for (g.prepared_images.items) |prepared| { - // Drawn in this order, instance by instance (Cells.drawImages). - g.cells.images.appendAssumeCapacity(.{ .premultiplied = prepared.premultiplied, .texture = prepared.texture, .clip = imageScissor(g, prepared.place) }); - if (!emitPreparedImage(g, surface, &instances[idx], prepared, win_w, win_h)) continue; - idx += 1; - } - std.debug.assert(idx == capacity); - g.cells.uploadImages(cmd, idx); - return true; -} - -fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect { - return .{ - .x = @intCast(@as(u32, place.dst.x) * g.cell_w), - .y = @intCast(@as(u32, place.dst.y) * g.cell_h), - .w = @intCast(@as(u32, place.dst.w) * g.cell_w), - .h = @intCast(@as(u32, place.dst.h) * g.cell_h), - }; -} - -fn renderFrame( - g: *Gui, - gpa: std.mem.Allocator, - core: *pardes.Pardes, - canonical: *const pardes.Surface, -) !bool { - // The pictures a pane asks to see as glyph art, drawn into a copy of - // the frame (Art.zig); the rest are textures. - if (g.art_arena == null) g.art_arena = .init(gpa); - _ = g.art_arena.?.reset(.retain_capacity); - const surface = g.art.frame(gpa, g.art_arena.?.allocator(), canonical, true, g.cell_h) catch canonical; - if (surface.pointer_shape != g.pointer_shape) { - g.pointer_shape = surface.pointer_shape; - const cursor = switch (g.pointer_shape) { - .link => g.link_cursor, - .box => g.box_cursor orelse g.arrow_cursor, - else => g.arrow_cursor orelse c.SDL_GetDefaultCursor(), - }; - if (cursor) |value| _ = c.SDL_SetCursor(value); - } - g.words.memo = .{}; // positional, and this frame's cells are new - const cmd = g.cells.begin() orelse return false; - var command_consumed = false; - defer if (!command_consumed) { - Cells.submit(cmd); - }; - const frame_target = try g.present.acquireTarget(cmd, g.window, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse { - command_consumed = true; - Cells.submit(cmd); - return false; - }; - const target = frame_target.texture; - const sw = frame_target.w; - const sh = frame_target.h; - const win_w: f32 = @floatFromInt(sw); - const win_h: f32 = @floatFromInt(sh); - - // The frame's CPU side: groups, decor, cover and every instance, up to - // their upload. - const build_zone = tracy.zone(@src(), "gui frame build"); - const probe_build = monoNs(); - var building = true; - defer if (building) build_zone.end(); - const layout = fixedCellLayout(g); - const chrome = &surface.chrome; - // G6: what the scroll just done moved the pane's rows by, measured on - // this frame against the last (the glide follows it from there). - for (core.panes, &g.glide.held) |slot, *held| held.* = if (slot) |pane| pane.context_rows else 0; - glideFrame(g, gpa, surface); - var groups: Groups = .{}; - const now = g.now_ns; - seeCaret(g, surface, layout, win_h, now); - // While the cursor glides or blinks the cells' cursors are not drawn; - // the focused one is the overlay's quad. One or the other every frame - // (none only at a blink's off half). - const blink_alpha: f32 = if (blinkNow(g, core.settings.cursor_blink)) |b| b.alpha else 1; - // While a glide moves the text, the caret is its quad, drawn from its - // own springs, not a cell of the moving rows. - const gliding = g.caret.moving(); - const quad_mode = g.caret.placed and (gliding or blink_alpha < 1 or g.glide.follow.offset != 0); - // A little less than solid while it glides, so the glyphs it passes - // stay legible; solid again as it lands. - const caret_alpha: f32 = if (gliding) 0.85 + 0.15 * std.math.clamp(1 - g.caret.remaining(now) / 0.5, 0, 1) else 1; - g.cursor_quad_alpha = if (quad_mode) caret_alpha * blink_alpha else 0; - // The probe's view of this frame's motion (FrameStats.Frame). - core.frames.scroll = g.glide.follow.offset; - core.frames.caret = caretRow(g, surface, now) orelse 0; - const cursors_shown = !quad_mode; - var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh); - if (overlay_count != 0 and !g.cells.uploadOverlay(cmd, g.overlay_vertices[0..overlay_count])) - overlay_count = 0; - if (!prepareNativeImages(g, gpa, cmd, surface, &groups, sw, sh)) { - g.prepared_images.clearRetainingCapacity(); - for (groups.items[0..groups.len]) |*group| { - group.image_start = 0; - group.image_count = 0; - } - } - - const cells: u32 = @as(u32, surface.cols) * surface.rows; - try g.cover.resize(gpa, cells); - const covered = g.cover.items[0..cells]; - dim.begin(core.settings.inactive_dim, surface.regionList()); - coverFrame(covered, surface.cols, surface.rows, surface.bodyLayers(), surface.tagLayers(), surface.regionList()); - try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - - const page = chrome.page orelse bg_default; - const background_opacity = backgroundOpacity(g.applied_window_opacity); - const clear: c.SDL_FColor = .{ - .r = @as(f32, @floatFromInt(page[0])) / 255.0 * background_opacity, - .g = @as(f32, @floatFromInt(page[1])) / 255.0 * background_opacity, - .b = @as(f32, @floatFromInt(page[2])) / 255.0 * background_opacity, - .a = background_opacity, - }; - - var shifted: u32 = 0; - var row: u16 = 0; - while (row < surface.rows) : (row += 1) { - var col: u16 = 0; - while (col < surface.cols) : (col += 1) { - const at = @as(usize, row) * surface.cols + col; - if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.debug else 0; - groups.items[group_index].cell_count = std.math.add(u32, groups.items[group_index].cell_count, cellInstanceCount(&surface.cells[at])) catch return error.GpuCapacity; - } - } - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - const group = &groups.items[0]; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; - for (0..layer.rows) |lr| { - if (layer.rowTop(@intCast(lr), layout.h, @floatFromInt(g.tagline_height)) >= bottom) break; - group.cell_count += layer.cols + @as(u32, if (lr < layer.context_rows) 1 else 0) + @as(u32, @intFromBool(layer.hasContextBorderAfter(lr))); - } - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - const group_index = if (layer.kind == .notice) groups.notices else 0; - groups.items[group_index].cell_count += (tagLayerCellCount(g, layer) + 1) * layer.rows; - } - var cell_next: [4]u32 = @splat(0); - var cell_total: u32 = 0; - for (groups.items[0..groups.len], 0..) |*group, index| { - group.cell_start = cell_total; - cell_next[index] = cell_total; - cell_total = std.math.add(u32, cell_total, group.cell_count) catch return error.GpuCapacity; - } - const decor_len: u32 = @intCast(g.decor.items.len); - if (cell_total != 0 or decor_len != 0) { - // The shifted rows of a scroll: its body, a glide's rows past it, and - // a body layer's rows past the grid's. - const capacity = std.math.add(u32, cell_total, 3 * cells + decor_len) catch return error.GpuCapacity; - const instances = try g.cells.mapCells(capacity) orelse { - command_consumed = true; - Cells.submit(cmd); - return false; - }; - const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else cells; - const cursor_bar = if (surface.cursor) |cu| cu.bar else false; - row = 0; - while (row < surface.rows) : (row += 1) { - const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; - const line_cover = covered[@as(usize, row) * surface.cols ..][0..surface.cols]; - const line_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; - var col: u16 = 0; - while (col < surface.cols) : (col += 1) { - const at = @as(usize, row) * surface.cols + col; - if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.debug else 0; - emitSurfaceCell( - g, - chrome, - instances, - &cell_next[group_index], - col, - row, - layout, - win_w, - win_h, - line, - line_cover, - col, - line_cursor, - cursors_shown and at == cursor_idx and !cursor_bar and bodyLayerIn(surface.bodyLayers(), col, row) == null, - page, - ); - } - } - // Body layers first: a notice chip over a tree-sitter context band - // is a tag layer, and instances paint in emission order. - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - emitBodyLayer(g, instances, &cell_next[0], layer, win_w, win_h, page, cursors_shown, chrome.topbar_rule); - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - // A notice floats over the panes. - const group_index = if (layer.kind == .notice) groups.notices else 0; - emitTagLayer(g, instances, &cell_next[group_index], layer, win_w, win_h, page, cursors_shown); - } - for (groups.items[0..groups.len], 0..) |group, index| - std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); - // The body's context rows, which its scroll leaves where they are. - const scrolling: ?usize = if (g.glide.follow.offset != 0) g.glide.pane else g.scroll_pane; - const held: u16 = if (scrolling) |id| if (core.panes[id]) |pane| pane.context_rows else 0 else 0; - shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); - @memcpy(instances[cell_total + shifted ..][0..decor_len], g.decor.items); - g.cells.uploadCells(cmd, cell_total + shifted + decor_len, &g.atlas); - } - - build_zone.end(); - building = false; - if (frame_probe) |probe| probe.zone(.gui_build, probe_build); - // Drawn only over a scroll's shifted rows (scrollScissor asks a scroll). - const scroll_clip = if (shifted != 0) scrollScissor(g, layout, sw, sh) else std.mem.zeroes(c.SDL_Rect); - g.cells.record(cmd, target, sw, sh, clear, background_opacity, groups.items[0..groups.len], groups.ink, cell_total, shifted, scroll_clip, overlay_count); - - command_consumed = true; - return finishFrame(g, gpa, cmd, frame_target); -} - -/// Submits the frame: captured, handed to the soft presenter, or presented. -fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Present.Target) !bool { - if (g.present.capture) { - try captureFrame(g, gpa, cmd, target.texture, target.w, target.h); - return true; - } - var took: Present.Timings = .{}; - const presented = try g.present.finishFrame(cmd, target, &captureSeries, &took); - // A soft present's wait for the GPU, its upload of the frame and its flip. - if (g.present.soft_present) if (frame_probe) |probe| { - const now = monoNs(); - probe.zone(.gui_wait, now -| took.wait_ns); - probe.zone(.gui_upload, now -| took.upload_ns); - probe.zone(.gui_flip, now -| took.flip_ns); - }; - return presented; -} - -const ResolvedCell = struct { - slot: Slot, - fg: [3]u8, - bg: [3]u8, - role: pardes.FontRole, -}; - -const taglineBandOffset = pardes.Layer.taglineBandOffset; - -/// The colours and atlas slot of `line[at]`. `cursor` is where the cursor sits -/// in `line`, block or bar: shaping breaks around it. -fn resolveCell(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole, is_cursor: bool, page: [3]u8) ResolvedCell { - const cell = &line[at]; - var fg = fg_default; - var bg = page; - var reverse = is_cursor; - if (!cell.default) { - const st = cell.style; - fg = switch (st.fg) { - .default => fg_default, - .index => |i| pardes.colors.xterm[i], - .rgb => |rgb| rgb, - }; - switch (st.bg) { - .default => {}, - .index => |i| bg = pardes.colors.xterm[i], - .rgb => |rgb| bg = rgb, - } - if (st.reverse) reverse = !reverse; - if (st.invisible) { - fg = bg; - // With a translucent background, painting bg-colored glyphs at - // full opacity would expose text that the terminal concealed, so - // cellSlot draws a concealed cell blank. - } - if (st.dim) for (&fg) |*ch| { - ch.* = @intCast(@as(u16, ch.*) * 6 / 10); - }; - } - if (reverse) std.mem.swap([3]u8, &fg, &bg); - - return .{ - .slot = cellSlot(g, line, at, cursor, role), - .fg = fg, - .bg = bg, - .role = role, - }; -} - -fn cellFontRole(cell: *const pardes.Cell) pardes.FontRole { - return if (cell.default) .body else cell.style.font_role; -} - -fn cellInstanceCount(cell: *const pardes.Cell) u32 { - return if (cellFontRole(cell) == .tagline) 2 else 1; -} - -fn tagLayerCellCount(g: *const Gui, layer: *const pardes.Layer) u32 { - const pixels = @as(u32, layer.viewport.w) * g.cell_w; - return @min(layer.cols, (pixels + g.tagline_width - 1) / g.tagline_width); -} - -fn emitTagLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const pardes.Layer, win_w: f32, win_h: f32, page: [3]u8, show_cursor: bool) void { - const bw: f32 = @floatFromInt(g.cell_w); - const bh: f32 = @floatFromInt(g.cell_h); - const tw: f32 = @floatFromInt(g.tagline_width); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; - const background: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = layer.bg } } }; - // A window is rarely a whole number of cells wide: a band that ends at - // the last column runs on through the leftover pixels to the edge. - const band_right = if (win_w - right < bw) @max(right, win_w) else right; - const faded = (layer.kind == .pane or layer.kind == .notice) and dim.of(layer.id); - // A row to each line, each a grid row with the tagline's glyphs. - for (0..layer.rows) |index| { - const y = layer.viewport.y + @as(u16, @intCast(index)); - emitInstance(g, instances, next.*, 0, y, .{ .w = band_right - left, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, .body, (&background)[0..1], 0, null, false, page); - next.* += 1; - const cells = layer.cells[index * layer.cols ..][0..layer.cols]; - const line_cursor: ?usize = if (layer.cursor) |cu| (if (cu.y == index) cu.x else null) else null; - for (0..tagLayerCellCount(g, layer)) |col| { - const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == index else false; - emitInstance(g, instances, next.*, @intCast(col), y, .{ .w = tw, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, .tagline, cells, col, line_cursor, cursor, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, 1e9 }, win_w, win_h); - if (faded and !cursor) dim.fade(&instances[next.*]); - next.* += 1; - } - } -} - -fn bodyLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { - for (layers) |*layer| { - const r = layer.viewport; - if (layer.rows > 0 and col >= r.x and col - r.x < r.w and row >= r.y and row - r.y < r.h) return layer; - } - return null; -} - -fn emitBodyLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const pardes.Layer, win_w: f32, win_h: f32, page: [3]u8, show_cursor: bool, border_rgb: [3]u8) void { - const bw: f32 = @floatFromInt(g.cell_w); - const bh: f32 = @floatFromInt(g.cell_h); - const tw: f32 = @floatFromInt(g.tagline_width); - const th: f32 = @floatFromInt(g.tagline_height); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * bh; - const faded = dim.of(layer.id); - for (0..layer.rows) |index| { - const row: u16 = @intCast(index); - const top = layer.rowTop(row, bh, th); - if (top >= bottom) break; - const height = layer.rowHeight(row, bh, th); - const header = row < layer.context_rows; - const role: pardes.FontRole = if (header) .tagline else .body; - const width = if (header) tw else bw; - if (header) { - var background: pardes.Cell = .{ .default = false, .style = layer.cells[index * layer.cols].style }; - background.style.font_role = .body; - emitInstance(g, instances, next.*, 0, 0, .{ .w = @as(f32, @floatFromInt(layer.viewport.w)) * bw, .h = height, .x_off = left, .y_off = top }, win_w, win_h, .body, (&background)[0..1], 0, null, false, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); - next.* += 1; - } - const line = layer.cells[index * layer.cols ..][0..layer.cols]; - const line_cursor: ?usize = if (layer.cursor) |cu| if (cu.y == row) cu.x else null else null; - for (0..layer.cols) |col| { - if (left + @as(f32, @floatFromInt(col)) * width >= right) break; - const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == row else false; - const glyph_top = top - (if (header) @as(f32, @floatFromInt(taglineBandOffset(0, win_h, g.cell_h, g.tagline_height))) else 0); - emitInstance(g, instances, next.*, 0, 0, .{ .w = width, .h = height, .x_off = left + @as(f32, @floatFromInt(col)) * width, .y_off = glyph_top }, win_w, win_h, role, line, col, line_cursor, cursor, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); - if (faded and !cursor) dim.fade(&instances[next.*]); - next.* += 1; - } - if (layer.hasContextBorderAfter(row)) { - const border: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = border_rgb } } }; - emitInstance(g, instances, next.*, 0, 0, .{ - .w = @as(f32, @floatFromInt(layer.viewport.w)) * bw, - .h = 1, - .x_off = left, - .y_off = top + height - 1, - }, win_w, win_h, .body, (&border)[0..1], 0, null, false, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); - next.* += 1; - } - } -} - -/// acme's Scrollwid column at a pane's or column's left edge, in window -/// pixels: where its button sits over its scrollbar, one width for both -/// (`rail_px` at acme's 17px font, scaled with the tagline, and always -/// short of the cell so the text keeps a gap), right of the column's rule. -fn scrollColumn(g: *const Gui, chrome: *const pardes.Chrome, col: u16, layout: CellLayout) [2]f32 { - const rule: f32 = if (col == 0) 0 else rulePx(chrome); - const x0 = @round(@as(f32, @floatFromInt(col)) * layout.w + rule); - const scaled: f32 = @round(@as(f32, @floatFromInt(@max(1, chrome.rail_px))) * @as(f32, @floatFromInt(g.tagline_height)) / 17); - // The rail and the grip are GUTTER cells wide; the text starts after. - const w = std.math.clamp(scaled, dp(4), @max(dp(4), @floor(layout.w * @as(f32, @floatFromInt(config.GUTTER))) - rule - dp(3))); - return .{ x0, x0 + w }; -} - -/// acme's button for the grip whose first cell is (col, row), in window -/// pixels: the scroll column wide, its tag row tall, from the rule above to -/// the rule below, so button and scrollbar read as one strip. -fn gripButton(g: *const Gui, chrome: *const pardes.Chrome, col: u16, row: u16, layout: CellLayout) [4]f32 { - const x = scrollColumn(g, chrome, col, layout); - const y0 = @round(@as(f32, @floatFromInt(row)) * layout.h); - return .{ x[0], y0, x[1], @round(@as(f32, @floatFromInt(row + 1)) * layout.h) }; -} - -/// A pane's button fill, from its region's state, not the grid's cells -/// (which are drawn for cell shells): dirty, focused, or the tag's ground. -fn gripFill(chrome: *const pardes.Chrome, focus: bool, dirty: bool) [3]u8 { - if (dirty) return chrome.grip_dirty; - return if (focus) chrome.grip_focus_ring else chrome.tag_bg; -} - -fn inkOn(bg: [3]u8) [3]u8 { - const lum = (@as(u16, bg[0]) * 3 + @as(u16, bg[1]) * 6 + @as(u16, bg[2])) / 10; - return if (lum > 140) .{ 0x00, 0x00, 0x00 } else .{ 0xff, 0xff, 0xff }; -} - -/// Cuts an instance's quad to a pixel rectangle (left, top, right, bottom), -/// its atlas window in proportion, so the glyph neither moves nor stretches -/// (a band is a stretched quad); nothing left, an empty quad. -fn clipInstance(instance: *CellInstance, r: [4]f32, win_w: f32, win_h: f32) void { - // In clip space, where y grows up: a quad's y0 is its top. - const left = r[0] / win_w * 2 - 1; - const right = r[2] / win_w * 2 - 1; - const top = 1 - r[1] / win_h * 2; - const bottom = 1 - r[3] / win_h * 2; - if (instance.x1 <= left or instance.x0 >= right or instance.y0 <= bottom or instance.y1 >= top) { - instance.x1 = instance.x0; - instance.y1 = instance.y0; - return; - } - if (instance.x0 < left) { - const fraction = (instance.x1 - left) / (instance.x1 - instance.x0); - instance.u0 = instance.u1 + (instance.u0 - instance.u1) * fraction; - instance.x0 = left; - } - if (instance.x1 > right) { - const fraction = (right - instance.x0) / (instance.x1 - instance.x0); - instance.u1 = instance.u0 + (instance.u1 - instance.u0) * fraction; - instance.x1 = right; - } - if (instance.y0 > top) { - const fraction = (top - instance.y1) / (instance.y0 - instance.y1); - instance.v0 = instance.v1 + (instance.v0 - instance.v1) * fraction; - instance.y0 = top; - } - if (instance.y1 < bottom) { - const fraction = (instance.y0 - bottom) / (instance.y0 - instance.y1); - instance.v1 = instance.v0 + (instance.v1 - instance.v0) * fraction; - instance.y1 = bottom; - } -} - -fn emitSurfaceCell( - g: *Gui, - chrome: *const pardes.Chrome, - instances: [*]CellInstance, - next: *u32, - col: u16, - row: u16, - body_layout: CellLayout, - win_w: f32, - win_h: f32, - line: []const pardes.Cell, - line_cover: []const Cover, - at: usize, - cursor: ?usize, - is_cursor: bool, - page: [3]u8, -) void { - const role = cellFontRole(&line[at]); - if (role == .tagline) { - const here = line_cover[at]; - // The workspace row's underlay is its own ground (a theme's status - // bar), else the focused or plain tag's. - const band_base: pardes.Cell = .{ - .style = .{ .bg = .{ .rgb = if (row < chrome.tagline_rows) chrome.tagline_bg else if (here.focus) chrome.tag_focus_bg else chrome.tag_bg }, .font_role = .tagline }, - .default = false, - }; - // The smaller font changes the ink, not the chrome's coverage. Painting - // this underlay at tagline height leaves page-colored gutters between - // adjacent workspace, column and pane tags at TaglineSize < 100. - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .body, (&band_base)[0..1], 0, null, false, page); - next.* += 1; - // Tag glyphs keep their font size inside a full physical-width grip. - // A pane's grip cells are the cell shells' form (a dirty `*`): the - // button draws its own glyph over a blank of them. - var blank = line[at]; - blank.text[0] = ' '; - blank.len = 1; - if (here.pane_grip) - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .tagline, (&blank)[0..1], 0, null, false, page) - else - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .tagline, line, at, cursor, is_cursor, page); - // A grip's glyph is the cell at its left edge, and a blank one is - // no glyph: its marks are decor. - const glyph = &line[at - @min(here.grip_offset, at)]; - const grip = here.grip and here.grip_top and !glyph.default and glyph.printableAscii() != ' ' and !glyph.style.invisible; - const offset: u16 = if (grip) @min(here.grip_offset, at) else 0; - // An anchor starts at its column's rule: its left edge is inset by - // its top margin so the band frames it on the left as above and - // below, and its mark moves right by half that to stay centered. - const inset: u32 = if (line_cover[at - offset].anchor) taglineBandOffset(row, win_h, g.cell_h, g.tagline_height) else 0; - // A grip is acme's button: its fill is this cell's ground, cut to - // the button (and a dirty one's inset a pixel inside its ring, so - // the ring reads round it), its glyph centered in it. - const button = if (here.grip and here.grip_top) gripButton(g, chrome, col - @min(here.grip_offset, @as(u16, @intCast(at))), row, body_layout) else null; - if (grip) { - // A grip is one glyph centered across the gutter, not text: it is - // looked up by its codepoint's glyph, never shaped. - const drawn = g.atlas.glyphForCodepoint(cellCodepoint(glyph)); - const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = @bitCast(GlyphDecoration.fromCell(glyph)), .centered = true }); - const slot = cached orelse g.atlas.space_slot; - const b = button.?; - const center = (b[0] + b[2]) / 2 - @as(f32, @floatFromInt(col - offset)) * body_layout.w; - const shift: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, offset) * g.cell_w)) + @as(f32, @floatFromInt(config.GUTTER * g.cell_w)) / 2 - center else 0; - const resolved = resolveCell(g, glyph[0..1], 0, null, .tagline, false, page); - const ink = if (here.pane_grip) inkOn(gripFill(chrome, here.focus, here.dirty)) else resolved.fg; - instances[next.*].fr = @as(f32, @floatFromInt(ink[0])) / 255; - instances[next.*].fg = @as(f32, @floatFromInt(ink[1])) / 255; - instances[next.*].fb = @as(f32, @floatFromInt(ink[2])) / 255; - instances[next.*].u0 = (@as(f32, @floatFromInt(slot.u)) + shift) / atlas_w; - instances[next.*].v0 = @as(f32, @floatFromInt(slot.v)) / atlas_h; - instances[next.*].v1 = @as(f32, @floatFromInt(slot.v + g.tagline_height)) / atlas_h; - } - instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; - if (button) |b| { - // acme's button fills its tag row from the rule above to the rule - // below: the underlay is its fill, cut to its columns; a pane's - // from its region's state, not the grid's cell form (whose dirty - // `*` is the cell shells'), a column's its cell's own ground. - const base = &instances[next.* - 1]; - const own: [3]f32 = .{ instances[next.*].br, instances[next.*].bg, instances[next.*].bb }; - if (here.pane_grip) { - const fill = gripFill(chrome, here.focus, here.dirty); - base.br = @as(f32, @floatFromInt(fill[0])) / 255; - base.bg = @as(f32, @floatFromInt(fill[1])) / 255; - base.bb = @as(f32, @floatFromInt(fill[2])) / 255; - } else { - base.br = own[0]; - base.bg = own[1]; - base.bb = own[2]; - } - clipInstance(base, .{ b[0], -1e9, b[2], 1e9 }, win_w, win_h); - // Over it, only its own glyph; the band round it and the ring - // are decor (gripDecor). - if (here.pane_grip and !grip) { - instances[next.*].u0 = @as(f32, @floatFromInt(g.atlas.space_slot.u)) / atlas_w; - instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; - instances[next.*].v0 = @as(f32, @floatFromInt(g.atlas.space_slot.v)) / atlas_h; - instances[next.*].v1 = @as(f32, @floatFromInt(g.atlas.space_slot.v + g.tagline_height)) / atlas_h; - } - // Its ground is the fill again. - instances[next.*].br = base.br; - instances[next.*].bg = base.bg; - instances[next.*].bb = base.bb; - clipInstance(&instances[next.*], b, win_w, win_h); - } else if (inset > 0) { - instances[next.*].x0 += @as(f32, @floatFromInt(inset)) / win_w * 2; - instances[next.*].u0 += @as(f32, @floatFromInt(inset)) / atlas_w; - } - if (here.dim and !is_cursor) dim.fade(&instances[next.*]); - next.* += 1; - return; - } - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, role, line, at, cursor, is_cursor, page); - if (line_cover[at].dim and !is_cursor) dim.fade(&instances[next.*]); - next.* += 1; -} - -fn emitInstance( - g: *Gui, - instances: [*]CellInstance, - idx: u32, - col: u16, - row: u16, - layout: CellLayout, - win_w: f32, - win_h: f32, - role: pardes.FontRole, - line: []const pardes.Cell, - at: usize, - cursor: ?usize, - is_cursor: bool, - page: [3]u8, -) void { - const resolved = resolveCell(g, line, at, cursor, role, is_cursor, page); - - const px0 = layout.x_off + @as(f32, @floatFromInt(col)) * layout.w; - const visual_h: f32 = if (resolved.role == .tagline) - @floatFromInt(g.tagline_height) - else - layout.h; - const band_offset: f32 = if (resolved.role == .tagline) - @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height)) - else - 0; - const py0 = layout.y_off + @as(f32, @floatFromInt(row)) * layout.h + band_offset; - const x0 = (px0 / win_w) * 2.0 - 1.0; - const x1 = ((px0 + layout.w) / win_w) * 2.0 - 1.0; - const y0 = 1.0 - (py0 / win_h) * 2.0; - const y1 = 1.0 - ((py0 + visual_h) / win_h) * 2.0; - const aw_f: f32 = @floatFromInt(atlas_w); - const ah_f: f32 = @floatFromInt(atlas_h); - const uv_w: u32 = if (resolved.role == .tagline) g.tagline_width else g.cell_w; - const uv_h: u32 = if (resolved.role == .tagline) g.tagline_height else g.cell_h; - - instances[idx] = .{ - .x0 = x0, - .y0 = y0, - .x1 = x1, - .y1 = y1, - .u0 = @as(f32, @floatFromInt(resolved.slot.u)) / aw_f, - .v0 = @as(f32, @floatFromInt(resolved.slot.v)) / ah_f, - .u1 = @as(f32, @floatFromInt(resolved.slot.u + uv_w)) / aw_f, - .v1 = @as(f32, @floatFromInt(resolved.slot.v + uv_h)) / ah_f, - .fr = @as(f32, @floatFromInt(resolved.fg[0])) / 255.0, - .fg = @as(f32, @floatFromInt(resolved.fg[1])) / 255.0, - .fb = @as(f32, @floatFromInt(resolved.fg[2])) / 255.0, - .br = @as(f32, @floatFromInt(resolved.bg[0])) / 255.0, - .bg = @as(f32, @floatFromInt(resolved.bg[1])) / 255.0, - .bb = @as(f32, @floatFromInt(resolved.bg[2])) / 255.0, - }; - // A block cursor is foreground UI ink, even though its color is carried - // in the reversed cell background. Keep it visible at WindowOpacity 0. - if (is_cursor) instances[idx].effect |= opaque_bg_bit; -} - -fn cellCodepoint(cell: *const pardes.Cell) u32 { - const grapheme = cell.grapheme(); - return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); -} - -fn firstCp(s: []const u8) u32 { - if (s.len == 0) return ' '; - const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return ' '; - if (n > s.len) return ' '; - return std.unicode.utf8Decode(s[0..n]) catch ' '; -} - -fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { - var cw: c_int = 10; - var chh: c_int = 20; - var asc: c_int = 16; - g.atlas.cellMetrics(g.px, &cw, &chh, &asc); - g.cell_w = @intCast(@max(cw, 1)); - g.cell_h = @intCast(@max(chh, 1)); - g.ascent = @intCast(@max(asc, 1)); - const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, g.tagline_percent); - g.tagline_px = tagline.px; - g.tagline_width = tagline.width; - g.tagline_baseline = tagline.baseline; - g.tagline_height = tagline.height; - - resetGlyphAtlas(g); - - if (core) |p| { - const geom = windowCells(g); - _ = updateCoreResize(p, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); - } - - resetScroll(g); -} - -// The first cell of the cleared atlas stays blank: the space slot. -fn resetGlyphAtlas(g: *Gui) void { - g.atlas.reset(g.cell_w); - g.words.clear(); -} - -fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { - if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return; - const geom = windowCells(g); - _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); -} - -/// The tagline's face at `percent` of the body's: whether it changed. -fn fitTaglineFont(g: *Gui, percent: u8) bool { - if (percent == g.tagline_percent) return false; - g.tagline_percent = percent; - const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, percent); - g.tagline_px = tagline.px; - g.tagline_width = tagline.width; - g.tagline_baseline = tagline.baseline; - g.tagline_height = tagline.height; - resetGlyphAtlas(g); - return true; -} - -/// What text draws, so a frame does not work it out again. `cells` is the -/// atlas slot of a codepoint no ligature can touch (`shape_slot` for one that -/// is shaped with its word); `map` is the atlas slot of every cell of a word -/// holding one, found by the word's text. Bounded: past `max_cells` word cells -/// it starts over, and the next frames look up what they show again (the -/// glyphs stay in the atlas). -const Words = struct { - cells: std.AutoHashMapUnmanaged(CellKey, Slot) = .empty, - map: std.AutoHashMapUnmanaged(u64, Word) = .empty, - /// Every word's codepoints and slots, end to end; a Word indexes both. - text: std.ArrayListUnmanaged(u32) = .empty, - slots: std.ArrayListUnmanaged(Slot) = .empty, - shaped: std.ArrayListUnmanaged(c.UIShapedCell) = .empty, - /// The word the last cell was in, so the rest of it costs a compare. It - /// is positional, so every frame forgets it: the cells change under it. - memo: Memo = .{}, - - const max_cells = 1 << 17; - const CellKey = packed struct(u64) { cp: u21, role: pardes.FontRole, decoration: GlyphDecoration, _: u30 = 0 }; - const shape_slot: Slot = .{ .u = std.math.maxInt(u32), .v = std.math.maxInt(u32) }; - const Word = struct { start: u32, len: u32, decoration: GlyphDecoration }; - const Memo = struct { - line: ?[*]const pardes.Cell = null, - len: usize = 0, - start: usize = 0, - end: usize = 0, - cursor: ?usize = null, - slots: usize = 0, - }; - - fn clear(w: *Words) void { - w.cells.clearRetainingCapacity(); - w.map.clearRetainingCapacity(); - w.text.clearRetainingCapacity(); - w.slots.clearRetainingCapacity(); - w.memo = .{}; - } - - fn deinit(w: *Words, gpa: std.mem.Allocator) void { - w.cells.deinit(gpa); - w.map.deinit(gpa); - w.text.deinit(gpa); - w.slots.deinit(gpa); - w.shaped.deinit(gpa); - } -}; - -/// What decides where a word ends, for one cell. A concealed cell is a space. -const WordCell = struct { cp: u32, decoration: GlyphDecoration, role: pardes.FontRole }; - -fn wordCell(cell: *const pardes.Cell) WordCell { - return .{ - .cp = if (!cell.default and cell.style.invisible) ' ' else cellCodepoint(cell), - .decoration = GlyphDecoration.fromCell(cell), - .role = cellFontRole(cell), - }; -} - -/// Whether a word ends between `a`, cell `i`, and `b`, cell `i + 1`: at a -/// space, a decoration or role change, either side of the cursor (Ghostty's -/// rule: the cell being edited shows its own glyph, so a ligature under the -/// cursor comes apart), and inside f|i, f|l and s|t, whose typographic -/// ligatures do not belong on a grid (Ghostty again). Colours never end a -/// word: a ligature spans a syntax colour change or a selection edge, and each -/// cell tints its own slice. -fn wordBreak(a: WordCell, b: WordCell, i: usize, cursor: ?usize) bool { - if (a.cp == ' ' or b.cp == ' ') return true; - // A rule is drawn by hand (ruleArms), never a slice of a shaped word. - if (ruleArms(a.cp) != null or ruleArms(b.cp) != null) return true; - if (cursor) |at| if (at == i or at == i + 1) return true; - if (a.role != b.role or !std.meta.eql(a.decoration, b.decoration)) return true; - return (a.cp == 'f' and (b.cp == 'i' or b.cp == 'l')) or (a.cp == 's' and b.cp == 't'); -} - -/// The atlas slot `line[at]` draws: blank for a plain space (or concealed -/// text), its own glyph when no ligature could replace that glyph (every -/// cell, in a font without ligatures), else its slice -/// of the word around it, shaped once and cached by the word's text. The -/// cells of a word being walked cost a compare. Taglines are not shaped: they are drawn at two pitches -/// (tagline_width in a tag layer, a whole cell in the grid), and a strip would -/// not line up in one of them. -fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole) Slot { - const words = &g.words; - const memo = words.memo; - if (memo.line == line.ptr and memo.len == line.len and memo.cursor == cursor and at >= memo.start and at < memo.end and role == .body) - return words.slots.items[memo.slots + at - memo.start]; - var here = wordCell(&line[at]); - // An underlined or struck-out space is a glyph of its own: it draws its line. - if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot; - if (ruleArms(here.cp) != null) - return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @fromBackingInt(@intCast(@backingInt(role))), .rule = true }) orelse g.atlas.space_slot; - const gpa = g.atlas.glyphs.allocator; - const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; - const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot; - if (!known.found_existing) { - const drawn = g.atlas.glyphForCodepoint(here.cp); - known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph)) - Words.shape_slot - else - cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @fromBackingInt(@intCast(@backingInt(role))), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot; - } - const plain = known.value_ptr.*; - if (!std.meta.eql(plain, Words.shape_slot)) return plain; - - if (words.text.items.len > Words.max_cells) words.clear(); - var start = at; - while (start > 0) { - const before = wordCell(&line[start - 1]); - if (wordBreak(before, here, start - 1, cursor)) break; - start -= 1; - here = before; - } - // The word's text goes on the end of `text`: a new word keeps it there, - // a known one gives it back. - const text_start = words.text.items.len; - var end = start; - while (true) { - words.text.append(gpa, here.cp) catch return g.atlas.space_slot; - end += 1; - if (end == line.len) break; - const next = wordCell(&line[end]); - if (wordBreak(here, next, end - 1, cursor)) break; - here = next; - } - const text = words.text.items[text_start..]; - const decoration = here.decoration; - const hash = std.hash.Wyhash.hash(@as(u5, @bitCast(decoration)), std.mem.sliceAsBytes(text)); - if (words.map.get(hash)) |word| { - if (word.len == text.len and std.meta.eql(word.decoration, decoration) and - std.mem.eql(u32, words.text.items[word.start..][0..word.len], text)) - { - words.text.shrinkRetainingCapacity(text_start); - words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = word.start }; - return words.slots.items[word.start + at - start]; - } - } - - // A new word (a hash collision takes the map entry over). Runs of one - // face are shaped in that face; fallback faces shape like the primary. - const probe_shape = monoNs(); - defer if (frame_probe) |probe| { - probe.zone(.gui_shape, probe_shape); - probe.shaped +|= 1; - }; - const n = text.len; - words.slots.ensureUnusedCapacity(gpa, n) catch { - words.text.shrinkRetainingCapacity(text_start); - return g.atlas.space_slot; - }; - words.shaped.resize(gpa, n) catch { - words.text.shrinkRetainingCapacity(text_start); - return g.atlas.space_slot; - }; - const shaped = words.shaped.items; - var run_start: usize = 0; - var face = g.atlas.glyphForCodepoint(text[0]).face; - while (run_start < n) { - var run_end = run_start + 1; - var next_face = face; - while (run_end < n) : (run_end += 1) { - next_face = g.atlas.glyphForCodepoint(text[run_end]).face; - if (next_face != face) break; - } - g.atlas.shape(face, g.px, g.cell_w, text[run_start..run_end], shaped[run_start..]); - for (shaped[run_start..run_end]) |cell| { - const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = @bitCast(decoration), .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; - const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.atlas.space_slot; - words.slots.appendAssumeCapacity(slot); - } - run_start = run_end; - face = next_face; - } - words.map.put(gpa, hash, .{ .start = @intCast(text_start), .len = @intCast(n), .decoration = decoration }) catch {}; - words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = text_start }; - return words.slots.items[text_start + at - start]; -} - -/// A Gui for the tests that build cells, decor or a scroll without a -/// window: these metrics, every other field its default. What needs SDL, a -/// font or the atlas is undefined (textTestGui adds a font and an atlas). -fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui { - return .{ - .window = undefined, - .present = undefined, - .cells = undefined, - .overlay_vertices = &.{}, - .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined }, - .px = 0, - .tagline_px = 0, - .tagline_percent = 0, - .tagline_width = tagline_width, - .tagline_height = tagline_height, - .cell_w = cell_w, - .cell_h = cell_h, - .ascent = 0, - .tagline_baseline = 0, - }; -} - -/// The atlas slot of `key` (Atlas.cachedGlyph), rasterized on first use at -/// the window's sizes, a grip glyph GUTTER cells wide, its rules and -/// decorations a logical pixel thick (dp): a raster is the frame probe's. -/// Null when the atlas is full. -fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { - if (g.atlas.glyphs.get(key)) |s| return s; - const probe_raster = monoNs(); - const body: Atlas.Size = .{ .px = g.px, .cell_w = g.cell_w, .height = g.cell_h, .baseline = g.ascent }; - const tagline: Atlas.Size = .{ .px = g.tagline_px, .cell_w = g.tagline_width, .height = g.tagline_height, .baseline = g.tagline_baseline }; - const s = g.atlas.cachedGlyph(key, body, tagline, config.GUTTER, @intFromFloat(dp(1))) orelse return null; - if (frame_probe) |probe| { - probe.zone(.gui_raster, probe_raster); - probe.rastered +|= 1; - } - return s; -} - -fn backgroundOpacity(percent: u8) f32 { - std.debug.assert(percent <= 100); - return @as(f32, @floatFromInt(percent)) / 100; -} - -/// PARDES_TEST_LATENCY trace for an external driver, CLOCK_MONOTONIC ns: -/// `R t` when stdin input is read, `F start fence submit` per captured frame -/// (present entry, the GPU fence of that frame, and its submission: submit - -/// start is the frame's CPU cost). Nothing is written without it. -var latency_fd: c_int = -1; -var frame_started_ns: u64 = 0; - -fn monoNs() u64 { - var ts: libc.timespec = undefined; - if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); -} - -fn latencyNote(comptime fmt: []const u8, args: anytype) void { - if (latency_fd < 0) return; - var buf: [64]u8 = undefined; - const line = std.fmt.bufPrint(&buf, fmt, args) catch return; - _ = libc.write(latency_fd, line.ptr, line.len); -} - -/// Writes the frame to latest.ppm in the capture directory, and in a -/// series to frame-.ppm too. -fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { - const frame = try g.present.readFrame(cmd, target, sw, sh); - defer g.present.releaseFrame(frame); - latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, frame.fence_ns, frame.submit_ns }); - - try writeCapturePpm(g, gpa, frame.pixels, sw, sh, "latest", false); - var name: [24]u8 = undefined; - // unreachable below: "frame-" and a u32 fit 24 - if (g.capture_series) try writeCapturePpm(g, gpa, frame.pixels, sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable, true); - g.captured +%= 1; -} - -/// A test window's state for a harness (test/process/window.zig), in the -/// capture directory's `status`: " ". -/// Idle is 1 once the frame last captured is the one that stays: nothing -/// owes a frame, nothing moves, nothing waits on a clock. A harness that -/// sees a step past the one it acted on, idle, has its frame, however slow -/// the machine is. -var test_status_step: u64 = 0; -fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) void { - test_status_step +%= 1; - if (g.capture_dir.len == 0) return; - const idle = presented and !core.needs_frame and !frontendMoving(g) and core.nextWake() == null and - !g.glide.moving() and g.scroll_lag == 0 and g.scroll_delta == 0 and g.scroll_notch == 0; - var line_buf: [64]u8 = undefined; - // What keeps it busy, after: owes a frame, moves, waits, not shown. - const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(frontendMoving(g)), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch unreachable; // seven numbers fit 64 - var tmp_buf: [4096]u8 = undefined; - var final_buf: [4096]u8 = undefined; - const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/status.tmp", .{g.capture_dir}, 0) catch return; - const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/status", .{g.capture_dir}, 0) catch return; - const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - _ = libc.rename(tmp_path, final_path); -} - -/// `.ppm`, RGB; with `alpha`, `.pam` (P7 RGB_ALPHA) instead: a -/// series keeps the alpha a blend writes, which the window's transparency -/// shows and an RGB capture cannot. -fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8, alpha: bool) !void { - // A latency trace times frames, and an 8 MB file write per frame would - // stall the loop it is timing. - if (g.capture_dir.len == 0 or latency_fd >= 0) return; - const bgr = try g.present.bgr(); - - var tmp_buf: [4096]u8 = undefined; - var final_buf: [4096]u8 = undefined; - const ext = if (alpha) "pam" else "ppm"; - const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.{s}.tmp", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong; - const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.{s}", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong; - - const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return error.CaptureWriteFailed; - defer _ = libc.close(fd); - - var header: [96]u8 = undefined; - const hdr = if (alpha) - std.fmt.bufPrint(&header, "P7\nWIDTH {d}\nHEIGHT {d}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", .{ width, height }) catch unreachable // two u32s fit 96 - else - std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 96 - _ = host_io.writeFd(fd, hdr); - - const depth: usize = if (alpha) 4 else 3; - const row_rgb = try gpa.alloc(u8, @as(usize, width) * depth); - defer gpa.free(row_rgb); - for (0..height) |row| { - const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4]; - for (0..width) |x| { - const si = x * 4; - const di = x * depth; - row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0]; - row_rgb[di + 1] = src[si + 1]; - row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2]; - if (alpha) row_rgb[di + 3] = src[si + 3]; - } - _ = host_io.writeFd(fd, row_rgb); - } - if (libc.rename(tmp_path, final_path) != 0) return error.CaptureWriteFailed; -} - -/// One flat, hard-edged rectangle of decor, in window pixels: clipped to the -/// window and dropped when empty, as the triangle overlay drew it. -fn addDecor(g: *Gui, gpa: std.mem.Allocator, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, rgb: [3]u8, alpha: f32, win_w: f32, win_h: f32) !void { - const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, win_w); - const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, win_w); - const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, win_h); - const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, win_h); - if (x1 <= x0 or y1 <= y0) return; - // decor.frag.glsl reads the colour from the ground and the coverage - // from the ink's red. - try g.decor.append(gpa, .{ - .x0 = (x0 / win_w) * 2.0 - 1.0, - .y0 = 1.0 - (y0 / win_h) * 2.0, - .x1 = (x1 / win_w) * 2.0 - 1.0, - .y1 = 1.0 - (y1 / win_h) * 2.0, - .u0 = 0, - .v0 = 0, - .u1 = 0, - .v1 = 0, - .fr = alpha, - .fg = 0, - .fb = 0, - .br = @as(f32, @floatFromInt(rgb[0])) / 255.0, - .bg = @as(f32, @floatFromInt(rgb[1])) / 255.0, - .bb = @as(f32, @floatFromInt(rgb[2])) / 255.0, - }); -} - -/// A body region in window pixels. -fn bodyPixels(region: pardes.Region, layout: CellLayout) [4]f32 { - return .{ - @as(f32, @floatFromInt(region.rect.x)) * layout.w, - @as(f32, @floatFromInt(region.rect.y)) * layout.h, - @as(f32, @floatFromInt(region.rect.x + region.rect.w)) * layout.w, - @as(f32, @floatFromInt(region.rect.y + region.rect.h)) * layout.h, - }; -} - -/// The frame's decor, group by group (docs/render-pipeline.md), all of it -/// read from the regions and the palette: the page's rules and the panes' -/// rails, rules and grip marks with the page, notice rules with the -/// notices, bar cursors with the ink. -fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, groups: *Groups, layout: CellLayout, win_w: f32, win_h: f32, cursors_shown: bool) !void { - g.decor.clearRetainingCapacity(); - const chrome = &surface.chrome; - const regions = surface.regionList(); - for (groups.items[0..groups.len], 0..) |*group, index| { - group.decor_start = @intCast(g.decor.items.len); - defer group.decor_count = @as(u32, @intCast(g.decor.items.len)) - group.decor_start; - if (index == 0) { - // The grips' buttons before any rule: the rules over their rows - // cut them, and the band round them never covers a rule. - try gripDecor(g, gpa, regions, surface.cells, chrome, layout, surface.cols, surface.rows, win_w, win_h); - const top = for (regions) |region| { - if (region.kind == .workspace_tag) break region.rect.h; - } else 0; - // The workspace tag is ruled off from the tags right under it. - const tag_under = for (regions) |region| switch (region.kind) { - .grip, .tag, .column_grip, .column_tag => if (region.rect.y == top) break true, - else => {}, - } else false; - // As wide as the other rules, where the tagline leaves the room. - const height: u32 = @intFromFloat(@max(1, @min(rulePx(chrome), @as(f32, @floatFromInt((g.cell_h -| g.tagline_height) * 2))))); - if (top != 0 and top < surface.rows and tag_under and height != 0) { - const y0: f32 = @floatFromInt(top * g.cell_h - height / 2); - try addDecor(g, gpa, 0, y0, win_w, y0 + @as(f32, @floatFromInt(height)), chrome.topbar_rule, 1, win_w, win_h); - } - // The column bar is ruled off from the panes under it. - for (regions) |bar| { - if (bar.kind != .column_grip) continue; - const y = @as(f32, @floatFromInt(bar.rect.y + bar.rect.h)) * layout.h; - try addDecor(g, gpa, 0, y - rulePx(chrome), win_w, y, chrome.border, 1, win_w, win_h); - break; - } - // A tag on the last row runs on through the pixels under the grid. - const grid_bottom = @as(f32, @floatFromInt(surface.rows)) * layout.h; - const tag_last = for (regions) |region| switch (region.kind) { - .grip, .tag, .column_grip, .column_tag, .workspace_tag => if (region.rect.h != 0 and region.rect.y + region.rect.h == surface.rows) break true, - else => {}, - } else false; - if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); - try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h); - // A single spine runs down each column, through every tag and body. - for (regions) |column| { - if (column.kind != .column) continue; - const x = @as(f32, @floatFromInt(column.rect.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(column.rect.y)) * layout.h; - const grid_y1 = @as(f32, @floatFromInt(surface.rows)) * layout.h; - const y1 = if (win_h - grid_y1 < layout.h) @max(grid_y1, win_h) else grid_y1; - // None at the window's edge: nothing to rule apart there. - if (column.rect.x == 0) continue; - if (y1 > y0) try addDecor(g, gpa, x, y0, x + rulePx(chrome), y1, chrome.border, 1, win_w, win_h); - } - } - // A notice chip is tagline hung over the body's top rows, so it is - // ruled off from the text beneath it the way a tag is: the same - // colour and thickness along its bottom, running to the window's - // edge when it does. - if (index == groups.notices) for (surface.tagLayers()) |*layer| { - if (layer.rows == 0 or layer.kind != .notice) continue; - const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; - const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; - const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; - const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h; - const rule_y = top + layout.h; - try addDecor(g, gpa, x0, rule_y - dp(1), rule_x1, rule_y, chrome.border, 1, win_w, win_h); - }; - if (index == groups.ink and cursors_shown) try cursorDecor(g, gpa, surface, layout, win_w, win_h); - } -} - -/// Each pane's rule between its tag and body, and its scroll rail: a page -/// coloured gutter with a thin track and its thumb, running down through the -/// pixels past the last whole row. -fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - const page = chrome.page orelse bg_default; - for (regions) |rail| { - if (rail.kind != .rail or rail.rect.h == 0) continue; - const tag = for (regions) |region| { - if (region.kind == .tag and region.owner == rail.owner) break region; - } else continue; - if (@as(u32, tag.rect.x) + tag.rect.w > cols or @as(u32, tag.rect.y) + tag.rect.h > rows or - @as(u32, rail.rect.y) + rail.rect.h > rows) continue; - const x0 = @as(f32, @floatFromInt(rail.rect.x)) * layout.w; - const x1 = @as(f32, @floatFromInt(tag.rect.x + tag.rect.w)) * layout.w; - // Like the band above it, the rule of a pane at the right edge runs - // on through the pixels past the last whole cell. Under a tag on - // top, over one below its body. - const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; - const tag_bottom = tag.rect.y > rail.rect.y; - const rule_y = @as(f32, @floatFromInt(if (tag_bottom) tag.rect.y else tag.rect.y + tag.rect.h)) * layout.h; - try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule orelse mixRgb(chrome.tag_bg, page), 1, win_w, win_h); - // Stacked panes are ruled apart as columns are, where one pane's - // body meets the next one's tag (acme's Border). - { - const pane_top = @min(tag.rect.y, rail.rect.y); - const stacked = for (regions) |other| { - if ((other.kind == .body or other.kind == .tag) and other.owner != rail.owner and other.rect.y + other.rect.h == pane_top and - other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; - } else false; - // Inside the tag band's slack, never over its glyphs: the top - // slack of a tag on top, the bottom slack of the one above when - // tags are at the bottom; a pixel at least. - const y = @as(f32, @floatFromInt(pane_top)) * layout.h; - const spare = g.cell_h -| g.tagline_height; - if (stacked and !tag_bottom) { - const room = taglineBandOffset(pane_top, win_h, g.cell_h, g.tagline_height); - try addDecor(g, gpa, x0, y, rule_x1, y + @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), chrome.border, 1, win_w, win_h); - } else if (stacked and pane_top > 0) { - const room = spare - taglineBandOffset(pane_top - 1, win_h, g.cell_h, g.tagline_height); - try addDecor(g, gpa, x0, y - @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), rule_x1, y, chrome.border, 1, win_w, win_h); - } - } - - const y0 = @as(f32, @floatFromInt(rail.rect.y)) * layout.h; - const body_end = rail.rect.y + rail.rect.h; - const body_y1 = @as(f32, @floatFromInt(body_end)) * layout.h; - const y1 = if (body_end == rows and win_h - body_y1 < layout.h) @max(body_y1, win_h) else body_y1; - // A theme's own track fills its width, the thumb one pixel short - // of it so the track edges it (acme's scrollbar); else a thin rail. - // acme's scrollbar: the track fills the scroll column, under the - // grip's button; the thumb is a pixel short of its right edge, so - // the track edges it. - const column = scrollColumn(g, chrome, rail.rect.x, layout); - try addDecor(g, gpa, x0, y0, x0 + layout.w, y1, page, 1, win_w, win_h); - try addDecor(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, 1, win_w, win_h); - if (rail.thumb_h != 0 and rail.thumb_span > 0) { - // In pixels, not rows, and with the picture while it glides - // or lags behind the core's rows (both in rows of the body). - const lag: f32 = if (g.glide.follow.offset != 0 and g.glide.pane == rail.owner) - g.glide.lagLines() - else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; - const track_px = body_y1 - y0; - const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); - const at = rail.thumb_at + lag * rail.thumb_span / @as(f32, @floatFromInt(rail.rect.h)); - const thumb_y0 = y0 + std.math.clamp(at * track_px, 0, track_px - size); - const thumb_y1 = if (thumb_y0 + size >= body_y1 - 0.5) y1 else thumb_y0 + size; - try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); - } else if (rail.thumb_h != 0) { - const thumb_y0 = @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y)) * layout.h; - const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; - try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); - } - // A query's places' ticks over the track and thumb, where its matches - // are in the file (Places.addTicks); the current one last, on top. - const track_px = body_y1 - y0; - for (0..2) |pass| for (ticks) |tick| { - if (tick.owner != rail.owner or tick.current != (pass == 1)) continue; - const at = @as(f32, @floatFromInt(tick.at)) / @as(f32, @floatFromInt(pardes.panes.Places.tick_scale)); - const h = if (tick.current) dp(3) else dp(2); - const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h); - try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, win_w, win_h); - }; - } -} - -/// Halfway between two colours. -const mixRgb = pardes.colors.mix; - -/// A rule's width: the theme's own, or one pixel. -fn rulePx(chrome: *const pardes.Chrome) f32 { - return dp(@floatFromInt(@max(1, chrome.rule_px))); -} - -/// The display's density (SDL's window display scale: 2 on a 2x screen), -/// by which every size given in logical pixels is drawn, as acme scales its -/// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is -/// measured in them are already the display's pixels and are not scaled. -/// One per process, as its window is. -var display_scale: f32 = 1; - -/// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x); -/// a test window is 1x unless forced, whatever display it lands on, so its -/// captures are the same on any machine. -fn updateDisplayScale(window: *c.SDL_Window) void { - if (std.c.getenv("PARDES_TEST_SCALE")) |forced| { - display_scale = std.fmt.parseFloat(f32, std.mem.span(forced)) catch 1; - } else if (std.c.getenv("PARDES_TEST") != null) { - display_scale = 1; - } else { - const scale = c.SDL_GetWindowDisplayScale(window); - display_scale = if (scale > 0 and std.math.isFinite(scale)) scale else 1; - } - display_scale = std.math.clamp(display_scale, 1, 4); -} - -/// InactiveDim: the unfocused panes' text faded toward its ground by the -/// setting's percent, never below the pair's own contrast or 4.5, whichever -/// is lower. The window's alone, from the regions' focus: renderFrame -/// begins it each frame. ponytail: one window per process, as display_scale. -var dim: Dim = .{}; - -const Dim = struct { - amount: f32 = 0, - /// The pane with the keyboard, from its regions. - focused: u16 = pardes.Region.none, - /// The few ink and paper pairs a frame has, each faded once. - keys: [32]?[6]u8 = @splat(null), - values: [32][3]u8 = undefined, - - fn begin(d: *Dim, percent: u8, regions: []const pardes.Region) void { - d.* = .{ .amount = @as(f32, @floatFromInt(@min(percent, 100))) / 100 }; - for (regions) |region| if (region.active and (region.kind == .grip or region.kind == .tag or region.kind == .body)) { - d.focused = region.owner; - break; - }; - if (d.focused == pardes.Region.none) d.amount = 0; - } - - /// Whether pane `owner`'s text fades this frame. - fn of(d: *const Dim, owner: u16) bool { - return d.amount > 0 and owner != d.focused; - } - - /// A cell instance's ink faded toward its ground. - fn fade(d: *Dim, instance: *CellInstance) void { - const ink = d.faded(byteRgb(.{ instance.fr, instance.fg, instance.fb }), byteRgb(.{ instance.br, instance.bg, instance.bb })); - instance.fr = @as(f32, @floatFromInt(ink[0])) / 255.0; - instance.fg = @as(f32, @floatFromInt(ink[1])) / 255.0; - instance.fb = @as(f32, @floatFromInt(ink[2])) / 255.0; - } - - fn faded(d: *Dim, ink: [3]u8, paper: [3]u8) [3]u8 { - const key = ink ++ paper; - const slot = (@as(usize, ink[0]) *% 31 +% @as(usize, ink[1]) *% 7 +% ink[2] +% @as(usize, paper[0]) *% 13 +% @as(usize, paper[1]) *% 3 +% paper[2]) % d.keys.len; - if (d.keys[slot]) |held| if (std.mem.eql(u8, &held, &key)) return d.values[slot]; - // Contrast falls as the ink nears its paper: the most of `amount` - // that keeps the pair at its own contrast or 4.5, whichever is lower. - const floor = @min(pardes.colors.contrast(ink, paper), 4.5); - var t = d.amount; - if (pardes.colors.contrast(blendLinear(ink, paper, t), paper) < floor) { - var lo: f32 = 0; - var hi: f32 = t; - for (0..8) |_| { - const mid = (lo + hi) / 2; - if (pardes.colors.contrast(blendLinear(ink, paper, mid), paper) >= floor) lo = mid else hi = mid; - } - t = lo; - } - d.keys[slot] = key; - d.values[slot] = blendLinear(ink, paper, t); - return d.values[slot]; - } - - fn byteRgb(rgb: [3]f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, rgb) |*o, v| o.* = @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255)); - return out; - } -}; - -/// `t` of the way from one colour to the other in linear light, so a -/// coloured ink does not muddy on its way to the paper. -fn blendLinear(from: [3]u8, to: [3]u8, t: f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, from, to) |*o, a, b| { - const l = pardes.colors.to_linear[a] * (1 - t) + pardes.colors.to_linear[b] * t; - o.* = encoded[@intFromFloat(@round(std.math.clamp(l, 0, 1) * (encoded.len - 1)))]; - } - return out; -} - -/// Linear light back to an sRGB channel, in 4096 steps. -const encoded: [4096]u8 = blk: { - @setEvalBranchQuota(1_000_000); - var table: [4096]u8 = undefined; - for (&table, 0..) |*out, i| { - const l = @as(f64, @floatFromInt(i)) / 4095; - const v = if (l <= 0.0031308) l * 12.92 else 1.055 * std.math.pow(f64, l, 1.0 / 2.4) - 0.055; - out.* = @intFromFloat(@round(v * 255)); - } - break :blk table; -}; - -/// A logical pixel size in the display's pixels: rounded, at least one. -fn dp(logical: f32) f32 { - return @max(1, @round(logical * display_scale)); -} - -/// The two short bars on each row of a grip with no mode glyph there, -/// centered in its anchor. -fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, cells: []const pardes.Cell, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - if (g.tagline_height < 6 or g.tagline_width < 3) return; - for (regions) |grip| { - if (grip.kind != .grip and grip.kind != .column_grip) continue; - if (grip.rect.h == 0 or grip.rect.y >= rows) continue; - const button = gripButton(g, chrome, grip.rect.x, grip.rect.y, layout); - // Round the button, its first row is the tag's band: nothing of the - // cells under it shows there. - const band = if (grip.active) chrome.tag_focus_bg else chrome.tag_bg; - const left = @as(f32, @floatFromInt(grip.rect.x)) * layout.w; - const right = @as(f32, @floatFromInt(grip.rect.x + grip.rect.w)) * layout.w; - try addDecor(g, gpa, left, button[1], button[0], button[3], band, 1, win_w, win_h); - try addDecor(g, gpa, button[2], button[1], right, button[3], band, 1, win_w, win_h); - if (grip.kind != .grip) continue; - // acme's button ring, two pixels (ButtonBorder) inside the button: - // the focused one's in its own fill. An unfocused dirty one keeps a - // pixel of band inside its ring, so the four states differ in shape - // whatever a theme's colours (a focused dirty one is acme's - // modbutton, filled up to its ring). - { - // The rules drawn over the row (paneDecor, after this) cut into - // it: the ring runs inside them, from rule to rule. - const tag = for (regions) |part| { - if (part.kind == .tag and part.owner == grip.owner) break part; - } else grip; - const tag_bottom = for (regions) |part| { - if (part.kind == .rail and part.owner == grip.owner) break part.rect.y < tag.rect.y; - } else false; - const stacked = !tag_bottom and for (regions) |other| { - if ((other.kind == .body or other.kind == .tag) and other.owner != grip.owner and other.rect.y + other.rect.h == grip.rect.y and - other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; - } else false; - const top_rule: f32 = if (tag_bottom) dp(1) else if (stacked) @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(taglineBandOffset(grip.rect.y, win_h, g.cell_h, g.tagline_height))))) else 0; - const bottom_rule: f32 = if (!tag_bottom and grip.rect.h == 1) dp(1) else 0; - const x0 = button[0]; - const x1 = button[2]; - const y0 = button[1] + top_rule; - const y1 = button[3] - bottom_rule; - const ring = if (grip.active) chrome.grip_focus_ring else chrome.grip_border; - // acme's ButtonBorder: two logical pixels. - const b = dp(2); - try addDecor(g, gpa, x0, y0, x1, y0 + b, ring, 1, win_w, win_h); - try addDecor(g, gpa, x0, y1 - b, x1, y1, ring, 1, win_w, win_h); - try addDecor(g, gpa, x0, y0 + b, x0 + b, y1 - b, ring, 1, win_w, win_h); - try addDecor(g, gpa, x1 - b, y0 + b, x1, y1 - b, ring, 1, win_w, win_h); - if (grip.dirty and !grip.active) { - const gap = b + dp(1); - try addDecor(g, gpa, x0 + b, y0 + b, x1 - b, y0 + gap, band, 1, win_w, win_h); - try addDecor(g, gpa, x0 + b, y1 - gap, x1 - b, y1 - b, band, 1, win_w, win_h); - try addDecor(g, gpa, x0 + b, y0 + gap, x0 + gap, y1 - gap, band, 1, win_w, win_h); - try addDecor(g, gpa, x1 - gap, y0 + gap, x1 - b, y1 - gap, band, 1, win_w, win_h); - } - } - // The marks are the first row's alone, where its cell is blank (no - // mode glyph), centered in the button, in its ink from the region's - // state. - const x = grip.rect.x; - const y = grip.rect.y; - if (x >= cols) continue; - const cell = &cells[@as(usize, y) * cols + x]; - if (cell.default or cell.printableAscii() != ' ') continue; - const rgb = inkOn(gripFill(chrome, grip.active, grip.dirty)); - const center_x = @floor((button[0] + button[2]) / 2); - const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; - const half_w = @max(dp(1), @min(dp(3), @floor((button[2] - button[0] - 2 * dp(3)) / 2))); - // The mode's two bars: a logical pixel thick, a pixel either side of - // the middle. - const bar = dp(1); - try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y - bar - dp(1)), @floor(center_x + half_w), @floor(center_y - dp(1)), rgb, 1, win_w, win_h); - try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y + dp(1)), @floor(center_x + half_w), @floor(center_y + dp(1) + bar), rgb, 1, win_w, win_h); - } -} - -const CursorBox = struct { x0: f32, y0: f32, x1: f32, y1: f32, rgb: [3]u8, bar: bool }; -const max_cursors = 1 + pardes.MAX_PANES + pardes.MAX_TAG_LAYERS; - -/// Where the frame draws the focused caret, its top in grid rows: from its -/// own springs (the quad's, while it moves or while a glide moves the text) -/// or its cell; carried by the text's glide when its line rode it. The probe -/// records it and the glide tests hold its invariants. -fn caretRow(g: *const Gui, surface: *const pardes.Surface, now_ns: u64) ?f32 { - const cursor = surface.cursor orelse return null; - const quad = g.caret.placed and (g.caret.moving() or g.glide.follow.offset != 0); - return if (quad) g.caret.sample(now_ns)[0][1] - caretRide(g, surface) else @floatFromInt(cursor.y); -} - -/// What the caret's ease sees in the frame about to be drawn (Caret.see): -/// the focused cursor's box in cells (its own cell's, or the layer's that -/// draws it), and the focused body's pane, first line and place. -fn seeCaret(g: *Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, now_ns: u64) void { - const box: ?Caret.Box = if (surface.cursor) |cursor| box: { - var boxes: [max_cursors]CursorBox = undefined; - const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; - if (all.len == 0) break :box null; - const cx = (@as(f32, @floatFromInt(cursor.x)) + 0.5) * layout.w; - const cy = (@as(f32, @floatFromInt(cursor.y)) + 0.5) * layout.h; - var best = all[0]; - var nearest = std.math.inf(f32); - for (all) |b| { - const dx = (b.x0 + b.x1) / 2 - cx; - const dy = (b.y0 + b.y1) / 2 - cy; - if (dx * dx + dy * dy < nearest) { - nearest = dx * dx + dy * dy; - best = b; - } - } - break :box .{ .x = best.x0 / layout.w, .y = best.y0 / layout.h, .w = (best.x1 - best.x0) / layout.w, .h = (best.y1 - best.y0) / layout.h }; - } else null; - for (surface.regionList()) |region| if (region.kind == .body and region.active) - return g.caret.see(box, region.owner, region.line, region.rect.x, region.rect.y, now_ns); - g.caret.see(box, pardes.Region.none, 0, 0, 0, now_ns); -} - -/// The caret's ease (G3), the window's own: the focused cursor's quad on -/// critically damped springs at its box's corners, in grid cells, on the -/// window's clock, from the cursor the Surface shows. A jump glides, its -/// leading corners first, bowing a little on a long one; a step eases, and -/// a stream of them (typing, a held key) keeps up; a scroll or a pane's move -/// carries it with its text; a focus change glides from where it was drawn. -/// The quad is drawn only while it moves: at rest the cells draw the cursor. -const Caret = struct { - /// Top left, top right, bottom right, bottom left; x then y. - corners: [4][2]Spring = @splat(@splat(.{})), - target: Box = .{}, - from_centre: [2]f32 = .{ 0, 0 }, - placed: bool = false, - /// When the last step (a move of a cell or less) came. - step_ns: u64 = 0, - /// The focused body as the last frame showed it: its pane, its first - /// line and its top left, to tell a scroll and a pane's move from the - /// caret's own. - seen: struct { owner: u8 = pardes.Region.none, line: i32 = 0, x: u16 = 0, y: u16 = 0 } = .{}, - - /// The default flavour's spring, as fast again as the caret follows - /// input (it settles in 90-150 ms). - const omega: f32 = 34 * 2.4; - /// The trailing corners of a jump, a little behind the leading ones. - const follow: f32 = 0.85; - /// A step's spring, stiffer than a jump's. - const step_pace: f32 = 1.5; - /// A jump longer than this, in cells, bows, by this much of its length. - const arc_from: f32 = 8; - const arc: f32 = 0.04; - /// Steps this close are a stream: each lands. - const stream_ns: u64 = 150 * std.time.ns_per_ms; - - const Box = struct { x: f32 = 0, y: f32 = 0, w: f32 = 0, h: f32 = 0 }; - - /// One axis on a critically damped spring, closed form: a new target - /// keeps the value and its speed; settled, it is its target. - const Spring = struct { - omega: f32 = omega, - target: f32 = 0, - from: f32 = 0, - velocity: f32 = 0, - from_ns: u64 = 0, - settled: bool = true, - - fn at(s: *const Spring, now_ns: u64) [2]f32 { - if (s.settled) return .{ s.target, 0 }; - const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| s.from_ns)) / std.time.ns_per_s); - const x0 = s.from - s.target; - const k = s.velocity + s.omega * x0; - const decay = @exp(-s.omega * t); - return .{ s.target + (x0 + k * t) * decay, (s.velocity - s.omega * t * k) * decay }; - } - - fn value(s: *const Spring, now_ns: u64) f32 { - return s.at(now_ns)[0]; - } - - fn retarget(s: *Spring, target: f32, now_ns: u64, w: f32) void { - if (target == s.target) return; - const state = s.at(now_ns); - s.* = .{ .omega = w, .target = target, .from = state[0], .velocity = state[1], .from_ns = now_ns, .settled = false }; - } - - /// Settles within half a percent of a cell, barely moving; true - /// while it still moves. - fn step(s: *Spring, now_ns: u64) bool { - if (s.settled) return false; - const state = s.at(now_ns); - if (@abs(state[0] - s.target) < 5e-3 and @abs(state[1]) < 5e-2) s.settled = true; - return !s.settled; - } - }; - - fn cornersOf(box: Box) [4][2]f32 { - return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; - } - - fn centre(box: Box) [2]f32 { - return .{ box.x + box.w / 2, box.y + box.h / 2 }; - } - - /// Heads for `box`: eased, or landed at once (`land`: a scroll moved - /// the text under it, not the caret). - fn aim(caret: *Caret, box: Box, now_ns: u64, land_it: bool) void { - if (caret.placed and std.meta.eql(box, caret.target) and !(land_it and caret.moving())) return; - const to = cornersOf(box); - const from_c = if (caret.placed) caret.centreAt(now_ns) else centre(box); - const to_c = centre(box); - const dx = to_c[0] - from_c[0]; - const dy = to_c[1] - from_c[1]; - const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; - // A step is measured mark to mark, not from where an ease under way - // has got to (a held key's steps would read as jumps from there). - const last = centre(caret.target); - const one_step = caret.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; - const streaming = one_step and caret.step_ns != 0 and now_ns -| caret.step_ns < stream_ns; - if (one_step) caret.step_ns = now_ns; - const land = !caret.placed or land_it or streaming; - caret.from_centre = from_c; - caret.target = box; - caret.placed = true; - for (&caret.corners, to) |*corner, point| { - // Leading: the corner ahead of the move, on the side it goes. - const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; - const w = if (jump) omega * (if (ahead > 0) 1 else follow) else omega * step_pace; - for (corner, point) |*axis, v| { - if (land) axis.* = .{ .omega = w, .target = v, .from = v } else axis.retarget(v, now_ns, w); - } - } - } - - fn centreAt(caret: *const Caret, now_ns: u64) [2]f32 { - var sum: [2]f32 = .{ 0, 0 }; - for (caret.corners) |corner| for (&sum, corner) |*s, axis| { - s.* += axis.value(now_ns) / 4; - }; - return sum; - } - - /// The text under it moved by (dx, dy) cells: so does the quad. - fn shift(caret: *Caret, dx: f32, dy: f32) void { - for (&caret.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| { - axis.from += d; - axis.target += d; - }; - caret.from_centre = .{ caret.from_centre[0] + dx, caret.from_centre[1] + dy }; - caret.target.x += dx; - caret.target.y += dy; - } - - /// The quad at `now_ns`, bowed on a long jump. - fn sample(caret: *const Caret, now_ns: u64) [4][2]f32 { - var out: [4][2]f32 = undefined; - for (&out, caret.corners) |*point, corner| for (point, corner) |*v, axis| { - v.* = axis.value(now_ns); - }; - const to_c = centre(caret.target); - const dx = to_c[0] - caret.from_centre[0]; - const dy = to_c[1] - caret.from_centre[1]; - const length = @sqrt(dx * dx + dy * dy); - if (length < arc_from) return out; - const now_c = caret.centreAt(now_ns); - const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1])); - const travelled = std.math.clamp(1 - left / length, 0, 1); - const bow = arc * length * 4 * travelled * (1 - travelled); - for (&out) |*point| { - point[0] += -dy / length * bow; - point[1] += dx / length * bow; - } - return out; - } - - /// Steps the springs to `now_ns`; true while the quad still moves. - fn step(caret: *Caret, now_ns: u64) bool { - var any = false; - for (&caret.corners) |*corner| for (corner) |*axis| { - if (axis.step(now_ns)) any = true; - }; - return any; - } - - /// How far, in cells, the furthest corner still is from its mark. - fn remaining(caret: *const Caret, now_ns: u64) f32 { - var most: f32 = 0; - for (caret.corners) |corner| for (corner) |axis| { - most = @max(most, @abs(axis.value(now_ns) - axis.target)); - }; - return most; - } - - fn moving(caret: *const Caret) bool { - for (caret.corners) |corner| for (corner) |axis| { - if (!axis.settled) return true; - }; - return false; - } - - /// The frame about to be drawn shows the focused cursor at `box` (grid - /// cells; null: none) in pane `owner`'s body, whose first line is - /// `line` and top left (x, y): carried with that body when it moved or - /// scrolled, eased to its box otherwise. - fn see(caret: *Caret, box: ?Box, owner: u8, line: i32, x: u16, y: u16, now_ns: u64) void { - const b = box orelse { - // Nowhere to land: a glide under way stops; the next cursor - // lands where it is. - caret.* = .{}; - return; - }; - var land = false; - const was = caret.seen; - if (was.owner == owner and owner != pardes.Region.none) { - // The pane moved in the layout: its caret moves with it. - caret.shift(@as(f32, @floatFromInt(x)) - @as(f32, @floatFromInt(was.x)), @as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(was.y))); - // Scrolled: the text moved, not the caret; it lands on its - // cell (the glide draws it with the text, caretRide). - land = line != was.line; - } - caret.seen = .{ .owner = owner, .line = line, .x = x, .y = y }; - caret.aim(b, now_ns, land); - _ = caret.step(now_ns); - } -}; - -/// The rows a caret whose line rode the wheel's glide is drawn above its -/// cell: the text's own offset, so it moves with its line as a glyph does -/// (its springs landed on the cell, Caret.see). -fn caretRide(g: *const Gui, surface: *const pardes.Surface) f32 { - const glide = &g.glide; - const cu = surface.cursor orelse return 0; - if (glide.follow.offset != 0) { - if (!glide.caret_rides) return 0; - const x0 = glide.rect.x + config.GUTTER; - if (cu.x < x0 or cu.x >= x0 + glide.bw() or cu.y < glide.body_y or cu.y >= glide.body_y + glide.body_h) return 0; - return glide.follow.offset; - } - // A fine wheel's or a touchpad's fraction (scroll_lag) holds the whole - // body off its cells, the caret's row with the rest, at rest too. - if (g.scroll_lag == 0 or g.scroll_pane == null) return 0; - const r = g.scroll_rect; - if (cu.x < r.x + config.GUTTER or cu.x >= r.x + r.w or cu.y < g.scroll_body_y or cu.y >= g.scroll_body_y + g.scroll_body_h) return 0; - return g.scroll_lag; -} - -/// The bar cursors as decor; a block cursor is its cell's own colours. -fn cursorDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32) !void { - var boxes: [max_cursors]CursorBox = undefined; - // The focused one is drawn with its line where a wheel's fraction holds - // the text off its cells (a block is a cell of the shifted rows). - // The focused box is the one nearest its cell (a body layer's is lifted - // off the grid), as seeCaret finds it. - const ride = caretRide(g, surface) * layout.h; - const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; - var focused: usize = all.len; - if (surface.cursor) |cu| { - const cx = (@as(f32, @floatFromInt(cu.x)) + 0.5) * layout.w; - const cy = (@as(f32, @floatFromInt(cu.y)) + 0.5) * layout.h; - var nearest = std.math.inf(f32); - for (all, 0..) |b, i| { - const d = ((b.x0 + b.x1) / 2 - cx) * ((b.x0 + b.x1) / 2 - cx) + ((b.y0 + b.y1) / 2 - cy) * ((b.y0 + b.y1) / 2 - cy); - if (d < nearest) { - nearest = d; - focused = i; - } - } - } - for (all, 0..) |box, i| if (box.bar) { - const shift = if (i == focused) ride else 0; - try addDecor(g, gpa, box.x0, box.y0 - shift, box.x1, box.y1 - shift, box.rgb, 1, win_w, win_h); - }; -} - -/// The triangle overlay: the cursor's glide, over everything. -fn buildOverlay( - g: *Gui, - which: pardes.config.Runtime.Pet, - trail_on: bool, - surface: *const pardes.Surface, - now_ns: u64, - sw: u32, - sh: u32, -) u32 { - if (g.overlay_vertices.len == 0 or sw == 0 or sh == 0) return 0; - var builder = OverlayBuilder{ .vertices = g.overlay_vertices, .win_w = @floatFromInt(sw), .win_h = @floatFromInt(sh) }; - appendWorkspacePet(g, which, surface, &builder); - appendJumpTrail(g, trail_on, surface, now_ns, &builder); - appendCursorGlide(g, surface, now_ns, &builder); - return @intCast(builder.len); -} - -/// A jump's trail (jump_trail.zig): the cells behind the cursor in its -/// body, on the page's own ground, drawn over toward the text's colour. -fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { - var at: [5]JumpTrail.Cell = undefined; - const lit = g.trail.see(if (surface.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); - if (lit.len == 0) return; - const cursor = surface.cursor.?; - const body = for (surface.regionList()) |region| { - if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and - cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; - } else return; - const page = surface.chrome.page orelse bg_default; - const w: f32 = @floatFromInt(g.cell_w); - const h: f32 = @floatFromInt(g.cell_h); - for (lit) |cell| { - if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; - const under = &surface.cells[@as(usize, @intCast(cell.y)) * surface.cols + @as(usize, @intCast(cell.x))]; - // On the page's own ground alone: never a selection or a match. - const ground: [3]u8 = if (under.default) page else switch (under.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (!std.mem.eql(u8, &ground, &page)) continue; - var color = overlayRgb(surface.chrome.fg orelse fg_default); - color.a = cell.strength; - const x0 = @as(f32, @floatFromInt(cell.x)) * w; - const y0 = @as(f32, @floatFromInt(cell.y)) * h; - builder.addRect(x0, y0, x0 + w, y0 + h, color); - } -} - -/// The workspace tag's pet (the Pet setting, gui/pet.zig): in the blank -/// end of the grid's first row, past the tag's text, in the tag's colours, -/// on the window's own clock. Nothing of it reaches the core. -fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { - const kind: pet.Kind = @fromBackingInt(@backingInt(which)); - if (kind == .off or surface.rows == 0 or surface.cols == 0) { - g.pet_state = .{}; - return; - } - var occupied: usize = 0; - for (surface.cells[0..surface.cols], 0..) |*cell, i| { - if (cellCodepoint(cell) != ' ') occupied = i + 1; - } - const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); - const region = if (occupied >= surface.cols) null else pet.lane( - occupied, - @floatFromInt(g.tagline_width), - builder.win_w, - band_top, - @floatFromInt(g.tagline_height), - ); - // ponytail: it moves when the window draws; a wake of its own for an - // idle window if a still pet ever matters. - const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; - const ink = overlayRgb(surface.chrome.tag_fg); - const eye = overlayRgb(surface.chrome.tag_bg); - // Behind the cursor: the overlay is over the cells, so the pixels a - // cursor covers are left out. - var boxes: [max_cursors]CursorBox = undefined; - const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; - for (0..pet.height) |y| for (0..pet.width) |x| { - const color = pet.pixel(kind, pose, x, y); - if (color == 0) continue; - const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; - const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; - const covered = for (cursors) |box| { - if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; - } else false; - if (covered) continue; - builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); - }; -} - -fn overlayRgb(rgb: [3]u8) OverlayColor { - return .{ - .r = @as(f32, @floatFromInt(rgb[0])) / 255.0, - .g = @as(f32, @floatFromInt(rgb[1])) / 255.0, - .b = @as(f32, @floatFromInt(rgb[2])) / 255.0, - .a = 1, - }; -} - -/// G3: the focused cursor while it glides or blinks, its quad from the -/// window's caret (Caret, grid cells) in its cursor colour; a little less -/// than solid, so the glyphs it passes over stay legible. -fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { - const chrome = &surface.chrome; - if (g.cursor_quad_alpha <= 0.001) return; - const layout = fixedCellLayout(g); - const ride = caretRide(g, surface); - // Never off the grid, however a long jump bows. - var quad = g.caret.sample(now_ns); - for (&quad) |*point| point.* = .{ std.math.clamp(point[0], 0, @as(f32, @floatFromInt(surface.cols))), std.math.clamp(point[1], 0, @as(f32, @floatFromInt(surface.rows))) }; - if (ride != 0) { - // Carried past the body's edge with its line: clipped as the text is. - const mid = quad[0][1] - ride + 0.5; - const top: f32 = @floatFromInt(g.glide.body_y); - if (mid < top or mid > top + @as(f32, @floatFromInt(g.glide.body_h))) return; - } - var px: [4][2]f32 = undefined; - var centre: [2]f32 = .{ 0, 0 }; - for (&px, 0..) |*point, i| { - point.* = .{ quad[i][0] * layout.w, (quad[i][1] - ride) * layout.h }; - centre[0] += point[0] / 4; - centre[1] += point[1] / 4; - } - // Its colour: the cursor the cells would draw nearest the quad. - var boxes: [max_cursors]CursorBox = undefined; - var rgb: [3]u8 = chrome.fg orelse fg_default; - var nearest: f32 = std.math.inf(f32); - for (boxes[0..cursorBoxes(g, surface, layout, builder.win_h, &boxes)]) |box| { - const dx = (box.x0 + box.x1) / 2 - centre[0]; - const dy = (box.y0 + box.y1) / 2 - centre[1]; - if (dx * dx + dy * dy < nearest) { - nearest = dx * dx + dy * dy; - rgb = box.rgb; - } - } - const color: OverlayColor = .{ .r = @as(f32, @floatFromInt(rgb[0])) / 255, .g = @as(f32, @floatFromInt(rgb[1])) / 255, .b = @as(f32, @floatFromInt(rgb[2])) / 255, .a = g.cursor_quad_alpha }; - builder.addTri(px[0][0], px[0][1], px[1][0], px[1][1], px[2][0], px[2][1], color); - builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color); -} - -const OverlayBuilder = struct { - vertices: []OverlayVertex, - len: usize = 0, - win_w: f32, - win_h: f32, - - fn addVertex(b: *OverlayBuilder, px: f32, py: f32, color: OverlayColor) void { - if (b.len >= b.vertices.len) return; - b.vertices[b.len] = .{ - .x = (px / b.win_w) * 2.0 - 1.0, - .y = 1.0 - (py / b.win_h) * 2.0, - .r = color.r, - .g = color.g, - .b = color.b, - .a = color.a, - }; - b.len += 1; - } - - fn addTri(b: *OverlayBuilder, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, color: OverlayColor) void { - if (b.len + 3 > b.vertices.len) return; - b.addVertex(x0, y0, color); - b.addVertex(x1, y1, color); - b.addVertex(x2, y2, color); - } - - fn addRect(b: *OverlayBuilder, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, color: OverlayColor) void { - if (b.len + 6 > b.vertices.len) return; - const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, b.win_w); - const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, b.win_w); - const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, b.win_h); - const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, b.win_h); - if (x1 <= x0 or y1 <= y0) return; - b.addTri(x0, y0, x1, y0, x1, y1, color); - b.addTri(x0, y0, x1, y1, x0, y1, color); - } -}; - -fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { - const raw = env.get(name) orelse return null; - return std.fmt.parseInt(u16, raw, 10) catch null; -} - -fn pixelCell(px: f32, cell: u32) u16 { - const idx = @floor(@max(px, 0) / @as(f32, @floatFromInt(@max(cell, 1)))); - return @intFromFloat(@min(idx, 10_000)); -} - -fn wheelRunFile(gpa: std.mem.Allocator) !*pardes.Pardes { - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - errdefer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..400) |i| try text.print(gpa, "{d:0>4} a line of the file\n", .{i}); - _ = try core.setTestFile(text.items); - for ("200G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); - return core; -} - -fn tagLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { - for (layers) |*layer| { - const r = layer.viewport; - if (layer.rows > 0 and row >= r.y and row - r.y < layer.rows and col >= r.x and col - r.x < r.w) return layer; - } - return null; -} - -fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer) !void { - for (0..rows) |row| for (0..cols) |col| { - const scan = bodyLayerIn(body_layers, @intCast(col), @intCast(row)) != null or tagLayerIn(tag_layers, @intCast(col), @intCast(row)) != null; - try std.testing.expectEqual(scan, cover[row * cols + col].layer); - }; -} - -/// A Gui that can shape and rasterize the face in `bytes` at `px`, and -/// nothing else. From here on the fonts allocate from std.testing.allocator -/// (the caller puts font_allocator back), so the test counts what they leak. -fn textTestGui(bytes: []const u8, px: f32) !Gui { - var atlas = try Atlas.init(std.testing.allocator, bytes); - atlas.prime(); - font_allocator = std.testing.allocator; - var cw: c_int = 0; - var ch: c_int = 0; - var ascent: c_int = 0; - atlas.cellMetrics(px, &cw, &ch, &ascent); - const tag = taglineRaster(&atlas, px, @intCast(cw), @intCast(ch), 82); - var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); - g.atlas = atlas; - g.px = px; - g.ascent = ascent; - g.tagline_px = tag.px; - g.tagline_baseline = tag.baseline; - resetGlyphAtlas(&g); - return g; -} - -fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell { - var line: [text.len]pardes.Cell = @splat(.{ .default = false }); - for (&line, text) |*cell, byte| cell.text[0] = byte; - return line; -} - -fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { - var it = g.atlas.glyphs.iterator(); - while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; - return error.NoGlyph; -} - -/// Every cursor on the frame where it is drawn, in window pixels: the grid's -/// where no layer has its cell, and each layer's at that layer's pitch. A bar -/// is an eighth of its cell wide, a block the whole cell. -fn cursorBoxes(g: *const Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, out: *[max_cursors]CursorBox) usize { - const chrome = &surface.chrome; - var n: usize = 0; - if (surface.cursor) |cursor| { - if (cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerIn(surface.bodyLayers(), cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { - const cell = &surface.cells[@as(usize, cursor.y) * surface.cols + cursor.x]; - const role = cellFontRole(cell); - const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; - const height = std.math.clamp(if (role == .tagline) @as(f32, @floatFromInt(g.tagline_height)) else layout.h, 1.0, layout.h); - const x0 = @as(f32, @floatFromInt(cursor.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))); - out[n] = .{ .x0 = x0, .y0 = y0, .x1 = x0 + if (cursor.bar) @max(dp(1), width / 8.0) else width, .y1 = y0 + height, .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; - n += 1; - } - } - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - const cursor = layer.cursor orelse continue; - if (cursor.y >= layer.rows or cursor.x >= layer.cols) continue; - const left = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; - const top = layer.rowTop(cursor.y, layout.h, @floatFromInt(g.tagline_height)); - if (top >= bottom) continue; - const height = layer.rowHeight(cursor.y, layout.h, @floatFromInt(g.tagline_height)); - const role: pardes.FontRole = if (cursor.y < layer.context_rows) .tagline else .body; - const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; - const x = left + @as(f32, @floatFromInt(cursor.x)) * width; - const cell = &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x]; - out[n] = .{ .x0 = x, .y0 = top, .x1 = x + if (cursor.bar) @max(dp(1), width / 8) else width, .y1 = @min(bottom, top + height), .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; - n += 1; - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - const cursor = layer.cursor orelse continue; - if (cursor.x >= layer.cols or cursor.y >= layer.rows) continue; - const width: f32 = @floatFromInt(g.tagline_width); - const span = layer.caretSpan(cursor.x, layout.w, width, if (cursor.bar) @max(dp(1), width / 8) else width); - const y = layer.viewport.y + cursor.y; - const top = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))); - out[n] = .{ .x0 = span[0], .y0 = top, .x1 = span[1], .y1 = top + @as(f32, @floatFromInt(g.tagline_height)), .rgb = cursorColor(chrome, &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x], .tagline), .bar = cursor.bar }; - n += 1; - } - return n; -} - -fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { - return if (role == .tagline) switch (cell.style.fg) { - .rgb => |rgb| rgb, - else => chrome.tag_fg, - } else chrome.fg orelse fg_default; -} - -test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { - // HarfBuzz's process-wide objects come from the default heap, as in runNative. - var primer = try Atlas.init(std.testing.allocator, font_ttf); - primer.prime(); - primer.deinit(std.testing.allocator); - font_allocator = std.testing.allocator; - defer font_allocator = std.heap.smp_allocator; - - var atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer atlas.deinit(std.testing.allocator); - atlas.reset(32); - const size: Atlas.Size = .{ .px = 27, .cell_w = 32, .height = 48, .baseline = 30 }; - const g_slot = atlas.cachedGlyph(.{ .face = 0, .glyph = atlas.glyphForCodepoint('g').glyph, .role = .body, .decoration = .{ .bold = true } }, size, size, config.GUTTER, 1).?; - try std.testing.expect(Atlas.inkBounds(atlas.atlas_stage[@as(usize, g_slot.v) * atlas_w + g_slot.u ..], atlas_w, 32, 48) != null); - try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph)); - - // A font with ligatures runs the whole HarfBuzz pass. - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(bytes); - var maple = try Atlas.init(std.testing.allocator, bytes); - defer maple.deinit(std.testing.allocator); - var cell_w: c_int = 0; - var cell_h: c_int = 0; - var ascent: c_int = 0; - maple.cellMetrics(27, &cell_w, &cell_h, &ascent); - const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; - var shaped: [text.len]c.UIShapedCell = undefined; - maple.shape(0, 27, @intCast(cell_w), &text, &shaped); - try std.testing.expectEqual(@as(u8, 2), shaped[1].span); - try std.testing.expectEqual(@as(u8, 2), shaped[4].span); -} - -test "every font size step moves the cell, and the ends are reachable exactly" { - var atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer atlas.deinit(std.testing.allocator); - var px = font_px_min + font_px_step; - while (px <= font_px_max) : (px += 1.0) { - var cw: c_int = 0; - var ch: c_int = 0; - var asc: c_int = 0; - var pw: c_int = 0; - var ph: c_int = 0; - atlas.cellMetrics(px, &cw, &ch, &asc); - atlas.cellMetrics(px - font_px_step, &pw, &ph, &asc); - try std.testing.expect(cw > pw and ch > ph); - } - try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max)); - try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max)); -} - -test "tagline glyph shrinks into its own cell and stays vertically centered" { - const body_px: f32 = 27.0; - var g = try textTestGui(font_ttf, body_px); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - _ = fitTaglineFont(&g, config.gui_tagline_font_percent); - const cell_w: c_int = @intCast(g.cell_w); - const cell_h: c_int = @intCast(g.cell_h); - const tag = taglineRaster(&g.atlas, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); - try std.testing.expect(tag.px < body_px); - try std.testing.expect(tag.width < @as(u32, @intCast(cell_w))); - - // Each at its role's size, as a frame draws it. - const h = g.atlas.glyphForCodepoint('H').glyph; - const body = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .body }).?; - const tagline = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .tagline }).?; - const b = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, body.v) * atlas_w + body.u ..], atlas_w, @intCast(cell_w), @intCast(cell_h)).?; - const t = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, tagline.v) * atlas_w + tagline.u ..], atlas_w, @intCast(tag.width), @intCast(tag.height)).?; - try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x); - try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y); - const body_center_x: isize = @intCast(b.min_x + b.max_x); - const tag_center_x: isize = @intCast(t.min_x + t.max_x); - const body_center_y: isize = @intCast(b.min_y + b.max_y); - const centered_top: isize = @intCast((@as(u32, @intCast(cell_h)) - tag.height) / 2); - const tag_center_y: isize = @as(isize, @intCast(t.min_y + t.max_y)) + centered_top * 2; - const body_slot_center: isize = @intCast(@as(u32, @intCast(cell_w)) - 1); - const tag_slot_center: isize = @intCast(tag.width - 1); - try std.testing.expect(@abs((tag_center_x - tag_slot_center) - (body_center_x - body_slot_center)) <= 2); - try std.testing.expect(@abs(tag_center_y - body_center_y) <= 4); - try std.testing.expect(tag.height < @as(u32, @intCast(cell_h))); -} - -test "tagline percentage changes measured band height without body metrics" { - var atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer atlas.deinit(std.testing.allocator); - var cell_w: c_int = 1; - var cell_h: c_int = 1; - var ascent: c_int = 1; - atlas.cellMetrics(27.0, &cell_w, &cell_h, &ascent); - const small = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 40); - const configured = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 82); - const full = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 100); - try std.testing.expect(small.width < configured.width); - try std.testing.expect(configured.width <= full.width); - try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width); - try std.testing.expect(small.height < configured.height); - try std.testing.expect(configured.height <= full.height); - try std.testing.expect(full.height <= @as(u32, @intCast(cell_h))); -} - -test "installed Nerd Symbols fallback covers Yazi directory icons" { - try std.testing.expectEqualStrings("SymbolsNerdFont-Regular", fonts.fallback_names[2]); - - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const candidate = for (fonts.fallbacks(arena_state.allocator())) |font| { - if (std.mem.eql(u8, font.name, "SymbolsNerdFont-Regular")) break font; - } else return; - - const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); - defer std.testing.allocator.free(bytes); - var atlas = try Atlas.init(std.testing.allocator, bytes); - defer atlas.deinit(std.testing.allocator); - try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); -} - -test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); - var bytes: std.ArrayList(u8) = .empty; - defer bytes.deinit(gpa); - var eof = false; - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - for (batch.slice()) |msg| switch (msg) { - .output => |o| { - try std.testing.expect(!eof); - try bytes.appendSlice(gpa, o.bytes); - }, - .eof => |e| { - try std.testing.expect(e.failure == null); - eof = true; - }, - else => return error.UnexpectedMessage, - }; - if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expect(eof); - try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); - shell.closePty(0); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); -} - -test "GUI PTY Restore joins a real reader waiting for queue space" { - const gpa = std.testing.allocator; - var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - try dump.dumpState(core); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - queue.acceptReader(1, 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); - try host_io.PtyTests.waitBlocked(&queue); - const old_serial = core.panes[0].?.serial; - const replacement = try dump.restore(core, core.dump_out.?, "test"); - shell.stopPtys(); - core.deinit(); - core = replacement; - shell.core = replacement; - // The dump's pane, its serial too; its old shell stopped all the same. - try std.testing.expectEqual(old_serial, core.panes[0].?.serial); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - queue.cancelReader(1, 1); - queue.acceptReader(0, gens[0]); - queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - try std.testing.expect(queue.pushOutput(0, gens[0], try gpa.dupe(u8, "fresh"))); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); -} - -test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try core.removePane(0, null); - shell.reconcilePtys(); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - shell.shutdownPtys(); - try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG)); - try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); -} - -test "GUI PTY file watcher stops and joins without closing its watched descriptor" { - if (!file_watch.supported) return error.SkipZigTest; - const gpa = std.testing.allocator; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - const fd = file_watch.init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - const stop = try stopPipe(); - defer for (stop) |pipe_fd| { - _ = libc.close(pipe_fd); - }; - const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue }); - _ = host_io.writeFd(stop[1], "x"); - thread.join(); - try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); -} - -test "GUI completion failure survives backlog and leaves the document unchanged" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - pane.body.cur_col = 1; - core.lspRequest(core.view().active, .completion, ""); - const id = core.lsp_ask.wait.?.id; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = id }; - defer queue.deinit(); - queue.acceptReader(0, 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "output"), - } }); - queue.push(.{ .lsp = .{ .id = id, .rows = null } }); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var shell: Shell = undefined; - shell.core = core; - shell.queue = &queue; - shell.gpa = gpa; - shell.lsp_allocator = gpa; - shell.gens = &gens; - shell.ptys = &ptys; - shell.drainQueue(); - try std.testing.expect(core.lsp_ask.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); -} - -test "GUI 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 queue: Queue = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_allocator = failing.allocator(), - }; - defer queue.deinit(); - var tasks: PipeTasks = .{}; - core.lspRequest(core.view().active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_ask.wait.?.id, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = "", - }; - if (failure == 0) { - queue.lsp_id = req.id -% 1; - queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); - queue.startLsp(core, req); - try std.testing.expectEqual(req.id, queue.lsp_id.?); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - } else { - var shell: Shell = undefined; - shell.core = core; - shell.threads_ok = false; - lsp(&shell, req); - } - try std.testing.expect(core.lsp_ask.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; - selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(queue.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), tasks.len); - try std.testing.expectEqual(@as(usize, 0), queue.len); - } -} - -test "high-density window coordinates map once to render pixels" { - const geometry: WindowGeometry = .{ - .window_w = 560, - .window_h = 360, - .pixel_w = 1120, - .pixel_h = 720, - }; - try std.testing.expectEqual(Point{ .x = 700, .y = 240 }, windowPointToPixels(geometry, 350, 120)); -} - -test "the GUI's stdin keys reach a terminal pane as the tty's do: F5, Insert and the keypad's Up" { - 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 in: Input = .{ .core = core }; - var parser: vaxis.Parser = .{}; - var bytes: []const u8 = "\x1b[15~\x1b[2~\x1b[57419u"; - while (bytes.len > 0) { - const result = try parser.parse(bytes, gpa); - bytes = bytes[result.n..]; - if (result.event) |event| switch (event) { - .key_press => |key| postKey(&in, key, key.text orelse ""), - 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("\x1b[15~\x1b[2~\x1b[A", written.written()); -} - -test "the window's function and editing keys reach a terminal 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 in: Input = .{ .core = core }; - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - const Case = struct { modes: []const u8, sym: c.SDL_Keycode, mod: c.SDL_Keymod = 0, sent: []const u8 }; - const cases = [_]Case{ - .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[A" }, - .{ .modes = "", .sym = c.SDLK_HOME, .sent = "\x1b[H" }, - .{ .modes = "", .sym = c.SDLK_F1, .sent = "\x1bOP" }, - .{ .modes = "", .sym = c.SDLK_F5, .sent = "\x1b[15~" }, - .{ .modes = "", .sym = c.SDLK_F12, .mod = c.SDL_KMOD_LSHIFT, .sent = "\x1b[24;2~" }, - .{ .modes = "", .sym = c.SDLK_INSERT, .sent = "\x1b[2~" }, - // DECCKM: less, vim, htop. - .{ .modes = "\x1b[?1h", .sym = c.SDLK_UP, .sent = "\x1bOA" }, - .{ .modes = "", .sym = c.SDLK_END, .sent = "\x1bOF" }, - .{ .modes = "", .sym = c.SDLK_LEFT, .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[1;5D" }, - // codex's kitty flags (>7u): Ctrl-C and Alt-a are unambiguous. - // (A bare Escape at a shell prompt is pardes's way out of raw input.) - .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, - .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, - // With event types asked for (2), an arrow says it is a press, as - // the emulator's encoder says it. - .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, - }; - for (cases) |case| { - core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); - while (core.nextEffect()) |_| {} - keyDown(&in, case.sym, case.mod); - 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 "tagline pointer mapping retains physical grips and carries logical text coordinates" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); - core.update(.{ .command = "Newcol" }); - core.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 12 }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - _ = try core.render(arena.allocator()); - - const r = core.view().rects[core.view().active]; - const body_w: f32 = 10; - const body_h: f32 = 20; - const tag_w: f32 = 8; - const tag_y = r.y; - const x = @as(f32, @floatFromInt(r.x + pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; - - const tag = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x, 10), tag.col); - try std.testing.expectEqual(tag_y, tag.row); - try std.testing.expectEqual(@as(u16, 3), tag.tag_hit.?.col); - try std.testing.expectEqual(pardes.TagKind.pane, tag.tag_hit.?.kind); - const grip = gridCellAtDimensions(core, @as(f32, @floatFromInt(r.x + config.GUTTER)) * body_w - 0.1, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expect(grip.tag_hit == null); - try std.testing.expectEqual(r.x + config.GUTTER - 1, grip.col); - - const body_y = tag_y + core.panes[core.view().active].?.tag_rows; // a long tag wraps - const body = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(body_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x, 10), body.col); - try std.testing.expectEqual(body_y, body.row); - try std.testing.expect(body.tag_hit == null); - - // The workspace tag's text starts TAG_TEXT_INSET cells in, as a pane's. - const x_top = @as(f32, @floatFromInt(pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; - const topbar = gridCellAtDimensions(core, x_top, 0.5 * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x_top, 10), topbar.col); - try std.testing.expectEqual(@as(u16, 3), topbar.tag_hit.?.col); - try std.testing.expectEqual(pardes.TagKind.workspace, topbar.tag_hit.?.kind); -} - -test "a click at the window's corner lands in the corner cell" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - var g = testGui(10, 20, 6, 12); - const geometry: WindowGeometry = .{ .window_w = 400, .window_h = 240, .pixel_w = 800, .pixel_h = 480 }; - const last = mouseCellWithGeometry(&g, core, 399.9, 239.9, geometry); - try std.testing.expectEqual(@as(u16, 79), last.col); - try std.testing.expectEqual(@as(u16, 23), last.row); - const first = mouseCellWithGeometry(&g, core, 0, 0, geometry); - try std.testing.expectEqual(@as(u16, 0), first.col); - try std.testing.expectEqual(@as(u16, 0), first.row); -} - -test "a blink holds while typing, eases at its edges and stops when idle" { - const ms = std.time.ns_per_ms; - try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); - const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); - try std.testing.expectEqual(@as(f32, 0), out.alpha); - const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); - try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); - try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); - try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); -} - -test "background opacity acknowledges success and rolls back unsupported surfaces" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - var applied: u8 = 100; - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 70")); - try std.testing.expect(core.settings.window_opacity_pending); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 70), applied); - try std.testing.expect(!core.settings.window_opacity_pending); - - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); - finishWindowOpacity(core, &applied, "background transparency requires an alpha-capable SDL window"); - try std.testing.expectEqual(@as(u8, 70), applied); - try std.testing.expectEqual(applied, core.settings.window_opacity); - try std.testing.expect(!core.settings.window_opacity_pending); - const pane = core.panes[0].?; - try std.testing.expectEqualStrings("WindowOpacity: background transparency requires an alpha-capable SDL window", pane.msg[0..pane.msg_len]); - - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); - try std.testing.expect(core.settings.window_opacity_pending); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 40), applied); - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 100")); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 100), applied); -} - -test "the clipboard pasted into a terminal reaches its pty as xterm pastes: bracketed when asked, no ESC[201~ smuggled through" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var shell: Shell = undefined; - shell.core = core; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const take = struct { - fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }.f; - _ = try take(core, &sent); - // The clipboard is SDL's own with no display to hold one. - _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "dummy"); - defer _ = c.SDL_ResetHint(c.SDL_HINT_VIDEO_DRIVER); - if (!c.SDL_InitSubSystem(c.SDL_INIT_VIDEO)) return error.SkipZigTest; - defer c.SDL_QuitSubSystem(c.SDL_INIT_VIDEO); - putClipboard(gpa, "ls\x1b[201~; rm -rf ~\nx"); - readClipboard(&shell); - try std.testing.expectEqualStrings("ls [201~; rm -rf ~\rx", try take(core, &sent)); - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - _ = try take(core, &sent); - readClipboard(&shell); - try std.testing.expectEqualStrings("\x1b[200~ls [201~; rm -rf ~\nx\x1b[201~", try take(core, &sent)); -} - -test "fractional wheel delta moves the picture by the same fraction" { - const delta = accumulateWheelDelta(0, -0.125); - const s = applyScrollDelta(0, delta); - const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; - try std.testing.expectEqual(@as(f32, 0.125), delta); - try std.testing.expectEqual(@as(f32, 0.125), picture); - try std.testing.expectEqual(@as(i32, 1), s.rows); - try std.testing.expectEqual(@as(f32, -0.875), s.lag); -} - -test "repeated fractional deltas cross exactly one core row" { - var core_row: i32 = 0; - var lag: f32 = 0; - var crossed: u32 = 0; - for (0..8) |_| { - const s = applyScrollDelta(lag, 0.125); - core_row += s.rows; - crossed += @intCast(@abs(s.rows)); - lag = s.lag; - } - try std.testing.expectEqual(@as(u32, 1), crossed); - try std.testing.expectEqual(@as(i32, 1), core_row); - try std.testing.expectEqual(@as(f32, 0), lag); -} - -test "wheel magnitude is preserved without quantization" { - const delta = accumulateWheelDelta(0, -2.75); - const s = applyScrollDelta(0, delta); - const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; - try std.testing.expectEqual(@as(f32, 2.75), delta); - try std.testing.expectEqual(@as(f32, 2.75), picture); - try std.testing.expectEqual(@as(i32, 3), s.rows); - try std.testing.expectEqual(@as(f32, -0.25), s.lag); - try std.testing.expectEqual(@as(f32, 0), accumulateWheelDelta(0, std.math.inf(f32))); - - const bounded = boundScrollDelta(0, 3.0e38, 24); - const safe = applyScrollDelta(0, bounded); - try std.testing.expectEqual(@as(f32, 24), bounded); - try std.testing.expectEqual(@as(i32, 24), safe.rows); -} - -test "fractional scroll reversals preserve signed distance" { - var core_row: i32 = 0; - const forward = applyScrollDelta(0, 0.375); - core_row += forward.rows; - try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(core_row)) + forward.lag); - - const reverse = applyScrollDelta(forward.lag, -0.125); - core_row += reverse.rows; - try std.testing.expectEqual(@as(i32, -1), reverse.rows); - try std.testing.expectEqual(@as(f32, 0.25), @as(f32, @floatFromInt(core_row)) + reverse.lag); - try std.testing.expect(reverse.lag >= 0 and reverse.lag < 1); -} - -test "a wheel's notch is whole lines, a touchpad's fraction is not" { - try std.testing.expectEqual(@as(?i32, 1), notchOf(-1, -1)); - try std.testing.expectEqual(@as(?i32, -3), notchOf(3, 3)); - try std.testing.expectEqual(@as(?i32, null), notchOf(-0.25, 0)); - try std.testing.expectEqual(@as(?i32, null), notchOf(-1.5, -1)); - try std.testing.expectEqual(@as(?i32, null), notchOf(std.math.nan(f32), 1)); -} - -test "a click over codex in a terminal reaches its pty with its modifiers; Shift swaps B1 to pardes and B2 to the program" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try core.render(frame.allocator()); - var in: Input = .{ .core = core }; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const take = struct { - fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }.f; - _ = try take(core, &sent); - const pane = core.panes[0].?; - const r = core.view().rects[0]; - const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; - const next: MouseCell = .{ .col = mc.col + 1, .row = mc.row }; - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); - _ = try take(core, &sent); - in.post(.{ .mouse = pointerMouse(.none, .motion, mc, .{}) }); - try std.testing.expectEqualStrings("\x1b[<35;6;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .ctrl = true }) }); - try std.testing.expectEqualStrings("\x1b[<16;6;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .drag, next, .{}) }); - try std.testing.expectEqualStrings("\x1b[<32;7;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .release, next, .{}) }); - try std.testing.expectEqualStrings("\x1b[<0;7;4m", try take(core, &sent)); - // Shift-B1 is pardes's select; B2 is pardes's execute and Shift-B2 - // the program's, reported without the Shift. - in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .shift = true }) }); - in.post(.{ .mouse = pointerMouse(.left, .release, mc, .{ .shift = true }) }); - try std.testing.expectEqualStrings("", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{}) }); - in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{}) }); - try std.testing.expectEqualStrings("", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{ .shift = true }) }); - in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{ .shift = true }) }); - try std.testing.expectEqualStrings("\x1b[<1;6;4M\x1b[<1;6;4m", try take(core, &sent)); -} - -test "a wheel over codex in a terminal reaches its pty as the mouse reports it asked for" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try core.render(frame.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - var in: Input = .{ .core = core }; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const Sent = struct { - fn take(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }; - _ = try Sent.take(core, &sent); - const pane = core.panes[0].?; - const r = core.view().rects[0]; - const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; - // What codex 0.159's chat sets on start. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h\x1b[>7u\x1b[?1004h\x1b[?1049h\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); - _ = try Sent.take(core, &sent); - // A notch up, then a fast turn of three down: each its report, none - // left behind for a glide. - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); - try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = -3, .integer_y = -3 }, mc); - try std.testing.expectEqualStrings(std.mem.asBytes(&@as([3][10]u8, @splat("\x1b[<65;6;4M".*))), try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, 0), g.scroll_notch); - try std.testing.expect(g.scroll_pane == null); - // A touchpad's fractions add up to a turn. - wheelAt(&g, &in, .{ .y = 0.5 }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = 0.5 }, mc); - try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); - // Alt is meta, 8; Shift keeps the turn pardes's own, a glide. - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .alt = true } }, mc); - try std.testing.expectEqualStrings("\x1b[<72;6;4M", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .shift = true } }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); - stepGlide(&g, core); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - resetScroll(&g); - // Its sign-in screen: mouse off, alternate scroll on, so arrow keys. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1007h" } }); - _ = try Sent.take(core, &sent); - wheelAt(&g, &in, .{ .y = -1, .integer_y = -1 }, mc); - try std.testing.expectEqualStrings("\x1b[B", try Sent.take(core, &sent)); - // Back on the main screen a shell's wheel is ours: a notch to glide, - // nothing to the pty. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l" } }); - _ = try Sent.take(core, &sent); - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); -} - -test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - // Lines of two rows each at this width, numbered so no two rows match. - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..60) |i| { - try text.print(gpa, "{d:0>4} ", .{i}); - try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); - try text.append(gpa, '\n'); - } - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const ms = std.time.ns_per_ms; - var now: u64 = std.time.ns_per_s; - core.advance(now); - var s = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const r = core.view().rects[core.view().active]; - g.scroll_pane = core.view().active; - g.scroll_col = r.x + 10; - g.scroll_row = r.y + r.h - 2; - const body_y = core.bodyTop(core.panes[core.view().active].?, r); - const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); - defer gpa.free(row_before); - // The window has drawn the view once (Glide.frame finds a view that moved). - g.now_ns = now; - glideFrame(&g, gpa, s); - // One notch down: the core is a line on at once. - g.scroll_notch = 1; - const scrolled = core.panes[core.view().active].?.scroll(); - stepGlide(&g, core); - try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); - _ = arena.reset(.retain_capacity); - s = try core.render(arena.allocator()); - glideFrame(&g, gpa, s); - // The window's own motion: it draws its frames while it moves. - try std.testing.expect(frontendMoving(&g)); - // Its two rows: the picture two rows behind, the rows that left kept, - // nearest first. - try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); - try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); - try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); - // Frame by frame it comes back, never past, and settles. - var frames: usize = 0; - while (g.glide.moving()) : (frames += 1) { - now += 7 * ms; - core.advance(now); - stepGlide(&g, core); - g.now_ns = now; - glideFrame(&g, gpa, s); - try std.testing.expect(g.glide.follow.offset <= 1e-4); - if (frames > 200) return error.NeverSettled; - } - try std.testing.expect(frames > 5); - try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); - try std.testing.expect(!frontendMoving(&g)); -} - -test "a fractional wheel turn that brings the picture back onto the core's row is drawn: the window never rests on a frame half a row off" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - // A high-resolution wheel's half notches (SDL's y, up positive), a - // frame each: the first scrolls the core a line and leaves the picture - // half a row behind it; the second takes the picture onto it. - for (0..2) |_| { - try wr.frame(gpa, &.{-0.5}); - try std.testing.expectEqual(wr.picture(), wr.drawn); - } - try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); -} - -test "a wheel turned down then up never draws the picture moving against the turn" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - // Two half notches down (the picture back on the core's row), then - // quarter notches up, a frame each and frames between: each frame's - // picture is where the last left it or on the way the wheel turns, - // never back against it. - for ([_]struct { f32, usize }{ .{ -0.5, 2 }, .{ 0.25, 4 } }) |phase| { - const turn, const turns = phase; - for (0..turns + 4) |k| { - const was = wr.drawn; - try wr.frame(gpa, if (k < turns) &.{turn} else &.{}); - const moved = wr.drawn - was; - try std.testing.expect(moved * -turn >= -1e-4); - } - } -} - -test "a fine wheel's turns that stop at a fraction leave the text on a whole row, and a turn mid-settle is not lost" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - const line = struct { - fn of(p: *pardes.Pardes) i64 { - return @intCast(p.panes[p.view().active].?.scroll()); - } - }.of; - const first = line(core); - // Three quarter notches down, a frame each: the core a line on, the - // picture a quarter row behind it. Then nothing: it eases onto the - // core's row (never back against the turns) and rests there, drawn. - for (0..3) |_| try wr.frame(gpa, &.{-0.25}); - try std.testing.expect(wr.g.scroll_lag != 0); - var frames: usize = 0; - while (wr.g.scroll_lag != 0) : (frames += 1) { - const was = wr.drawn; - try wr.frame(gpa, &.{}); - try std.testing.expect(wr.drawn >= was); - try std.testing.expect(frames < 20); - } - try std.testing.expectEqual(first + 1, line(core)); - try std.testing.expectEqual(wr.picture(), wr.drawn); - try std.testing.expectEqual(@as(f32, @floatFromInt(first + 1)), wr.drawn); - // Again, and a quarter notch more arrives mid-settle: it counts, and - // the settle ends on the row after it. - for (0..3) |_| try wr.frame(gpa, &.{-0.25}); - for (0..4) |_| try wr.frame(gpa, &.{}); - try std.testing.expect(wr.g.scroll_lag != 0); - try wr.frame(gpa, &.{-0.25}); - for (0..20) |_| try wr.frame(gpa, &.{}); - try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); - try std.testing.expectEqual(first + 3, line(core)); - try std.testing.expectEqual(@as(f32, @floatFromInt(first + 3)), wr.drawn); -} - -test "a bar cursor is drawn on its line while a wheel's fraction holds the text off its row, as a block is" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - core.settings.cursor_blink = false; - core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - defer wr.g.decor.deinit(gpa); - // Half a notch down: the core a line on, the text drawn half a row - // below its cells until the settle. - try wr.frame(gpa, &.{-0.5}); - try std.testing.expectEqual(@as(f32, -0.5), wr.g.scroll_lag); - _ = wr.arena.reset(.retain_capacity); - const s = try core.render(wr.arena.allocator()); - const cu = s.cursor.?; - try std.testing.expect(cu.bar); - const layout = fixedCellLayout(&wr.g); - const win_w: f32 = @floatFromInt(@as(u32, s.cols) * wr.g.cell_w); - const win_h: f32 = @floatFromInt(@as(u32, s.rows) * wr.g.cell_h); - wr.g.decor.clearRetainingCapacity(); - try cursorDecor(&wr.g, gpa, s, layout, win_w, win_h); - try std.testing.expectEqual(@as(usize, 1), wr.g.decor.items.len); - // Its top where its line's top is drawn (emitScrollRows: the row less - // the lag), not on its cell. - const top = (1 - wr.g.decor.items[0].y0) * win_h / 2; - try std.testing.expectApproxEqAbs((@as(f32, @floatFromInt(cu.y)) - wr.g.scroll_lag) * layout.h, top, 0.01); -} - -test "a wheel's caret rides with its line, the text's own glide, never a spring of its own" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); - _ = try core.setTestFile(text.items); - core.settings.cursor_blink = false; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var now: u64 = std.time.ns_per_s; - core.advance(now); - for ("10G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); - _ = try core.render(arena.allocator()); - now += std.time.ns_per_s; - core.advance(now); - _ = arena.reset(.retain_capacity); - var s = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const r = core.view().rects[core.view().active]; - g.scroll_pane = core.view().active; - g.scroll_col = r.x + 10; - g.scroll_row = r.y + r.h - 2; - stepGlide(&g, core); - // The window has drawn the view once (Glide.frame finds a view that moved). - g.now_ns = now; - glideFrame(&g, gpa, s); - const before: f32 = @floatFromInt(s.cursor.?.y); - g.scroll_notch = 1; - stepGlide(&g, core); - var frames: usize = 0; - while (true) : (frames += 1) { - now += 7 * std.time.ns_per_ms; - core.advance(now); - _ = arena.reset(.retain_capacity); - s = try core.render(arena.allocator()); - g.now_ns = now; - glideFrame(&g, gpa, s); - seeCaret(&g, s, fixedCellLayout(&g), 480, now); - if (frames == 0) { - try std.testing.expect(g.glide.caret_rides); - // Where its line is drawn: on the row it was on, the cell a row up. - try std.testing.expectApproxEqAbs(before, caretRow(&g, s, now).?, 1e-3); - } - // Always exactly with its line, the cell less the text's offset. - try std.testing.expectApproxEqAbs(@as(f32, @floatFromInt(s.cursor.?.y)) - g.glide.follow.offset, caretRow(&g, s, now).?, 1e-3); - if (!g.glide.moving()) break; - stepGlide(&g, core); - if (frames > 200) return error.NeverSettled; - } - try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); -} - -test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - // Numbered lines no two alike, short enough never to wrap. - for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - core.advance(std.time.ns_per_s); - _ = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const body_h: f32 = @floatFromInt(core.view().rects[core.view().active].h - core.panes[core.view().active].?.tag_rows); - const ctrl = struct { - fn key(cp: u21) pardes.Key { - return .{ .cp = cp, .ctrl = true }; - } - }; - const script = [_]GlideRun.Step{ - .{ .frame = 2, .key = ctrl.key('d') }, - .{ .frame = 40, .key = ctrl.key('f') }, - .{ .frame = 80, .key = .{ .cp = 'g', .text = "g" } }, - .{ .frame = 80, .key = .{ .cp = 'e', .text = "e" } }, - .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, - .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, - // Faster than they settle: each adds to the glide under way. - .{ .frame = 160, .key = ctrl.key('d') }, - .{ .frame = 165, .key = ctrl.key('d') }, - .{ .frame = 170, .key = ctrl.key('d') }, - .{ .frame = 175, .key = ctrl.key('d') }, - }; - var seq: GlideRun = .{}; - try seq.play(&g, core, gpa, &arena, &script, 240); - try seq.checkCaret(); - // Every one moves the picture on the frame it is drawn in, and the - // picture lags by what the core moved (a far jump, by one body). - var longest: usize = 0; - var shortest: usize = std.math.maxInt(usize); - for ([_]usize{ 2, 40, 80, 120 }) |at| { - const moved: f32 = @floatFromInt(@abs(seq.lines[at] - seq.lines[at - 1])); - try std.testing.expect(moved >= 1); - const lag = @abs(seq.offsets[at]); - try std.testing.expect(lag > 0.5 * @min(moved, body_h)); - try std.testing.expect(lag <= @min(moved, body_h) + 1e-3); - // Settles on the same law whatever the distance: a few frames for - // a half page, not many more for a jump of 3000 lines. - const frames = seq.settle(at); - longest = @max(longest, frames); - shortest = @min(shortest, frames); - try std.testing.expect(frames >= 8 and frames <= 24); - } - try std.testing.expect(longest - shortest <= 5); - // Readable: never more than a quarter of a body a frame once it moves. - for (1..seq.frames) |k| { - if (seq.lines[k] != seq.lines[k - 1]) continue; - try std.testing.expect(@abs(seq.offsets[k] - seq.offsets[k - 1]) <= body_h / 4 + 1e-3); - } - // The seq of half pages: one glide, never at rest between them, and - // done as soon after the last as one half page alone takes. - for (160..180) |k| try std.testing.expect(seq.offsets[k] != 0); - try std.testing.expect(seq.settle(175) <= seq.settle(2) + 4); -} - -test "a held key moves the view at the stream's own rate, never a bounce a line, and settles once it stops" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - core.advance(std.time.ns_per_s); - _ = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - // j held from the top: a repeat every second frame, the view following - // a line a repeat once the caret is at its last rows. - var script: [48]GlideRun.Step = undefined; - for (&script, 0..) |*step, i| step.* = .{ .frame = 20 + 2 * i, .key = .{ .cp = 'j', .text = "j" } }; - var seq: GlideRun = .{}; - try seq.play(&g, core, gpa, &arena, &script, 200); - // Inside the stream the picture moves every frame by about the same - // step: an input's rows over its spacing, not a spring's ease to each. - var least: f32 = std.math.inf(f32); - var most: f32 = 0; - for (90..110) |k| { - const step = (@as(f32, @floatFromInt(seq.lines[k])) + seq.offsets[k]) - (@as(f32, @floatFromInt(seq.lines[k - 1])) + seq.offsets[k - 1]); - least = @min(least, step); - most = @max(most, step); - } - try std.testing.expect(seq.lines[89] > 0 and least > 0.4 and most < 0.6); - // The caret stays on its row, the text moving under it: not a pixel's - // wobble (the glide's fractional lag never reaches it). - for (90..110) |k| try std.testing.expectEqual(seq.carets[89], seq.carets[k]); - // It comes to rest once the keys stop, never past its mark. - for (110..200) |k| try std.testing.expect(seq.offsets[k] <= 0); - try std.testing.expectEqual(@as(f32, 0), seq.offsets[199]); - // Ctrl-d held, then PageDown held: the caret keeps its row the whole - // way, the pages moving under it. - var pages: [40]GlideRun.Step = undefined; - for (&pages, 0..) |*step, i| step.* = .{ .frame = 10 + 2 * i, .key = if (i < 20) .{ .cp = 'd', .ctrl = true } else .{ .cp = pardes.Key.page_down } }; - var held: GlideRun = .{}; - try held.play(&g, core, gpa, &arena, &pages, 100); - try held.checkCaret(); - try seq.checkCaret(); - // (The first of each may move it, one ease: from the last row to where - // a half page keeps it, and from there to a page's.) - for (30..50) |k| try std.testing.expectEqual(held.carets[30], held.carets[k]); - for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); -} - -test "a scroll's shifted rows start under the context rows, and its scissor below their band" { - var surface: pardes.Surface = .{}; - var g = testGui(10, 20, 6, 12); - g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; - g.scroll_body_y = 1; - g.scroll_body_h = 19; - const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; - // On the grid, three body-high rows are held, and nothing moves up. - const grid = holdContext(&g, &surface, 0, 3, 19, layout); - try std.testing.expectEqual(@as(u16, 3), grid.rows); - try std.testing.expectEqual(@as(f32, 0), grid.lift); - const clip = scrollScissor(&g, layout, 400, 400); - try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); - try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); - // In a body layer they are tagline-high: the rows under them move up - // by what each is shorter, to where the layer draws them. - surface.body_layers[0].rows = 30; - surface.body_layers[0].context_rows = 3; - const layered = holdContext(&g, &surface, 0, 3, 19, layout); - try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); - try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); - // None held: the whole body moves. - surface.body_layers[0].rows = 0; - try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); - try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); -} - -test "concealed terminal text emits no ink on its ground" { - var g = testGui(10, 20, 6, 12); - var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - cell.text[0] = 'X'; - const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot); - try std.testing.expectEqual(bg_default, resolved.bg); -} - -test "a block cursor's cell is drawn reversed: the cell's ink its ground, its ground its ink" { - var g = testGui(10, 20, 6, 12); - // A blank, so no glyph is looked up in this atlas-less Gui. - const cell: pardes.Cell = .{ - .text = .{ ' ', ' ', ' ', ' ', ' ', ' ', ' ' }, - .len = 1, - .default = false, - .style = .{ .fg = .{ .rgb = .{ 10, 20, 30 } }, .bg = .{ .rgb = .{ 200, 210, 220 } } }, - }; - const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, bg_default); - try std.testing.expectEqual([3]u8{ 10, 20, 30 }, plain.fg); - try std.testing.expectEqual(plain.fg, cursor.bg); - try std.testing.expectEqual(plain.bg, cursor.fg); -} - -test "the layer cover is the per-cell layer scan, over a core's layouts and random layers" { - // A gui-shaped core: its tagline is narrower and shorter than the body, - // so tags and notices are layers. - const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 97, .rows = 31 }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 97, .rows = 31, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 7, .tagline_h = 13 } } }); - for (1..4) |id| _ = try core.newShell(id, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - pardes.layout.insert(core, 1, 1, 2); - pardes.layout.insert(core, 0, 1, 3); - var cover: [97 * 31]Cover = undefined; - var notices = false; - for (0..32) |step| { - if (step & 3 == 0) try std.testing.expect(core.executeBuiltinLine(2, "Collapse")); - core.view().prefix = if (step & 4 != 0) .leader else .none; - if (step & 8 != 0) { - try std.testing.expect(core.executeBuiltinLine(0, "Msg a message chip over the body")); - try std.testing.expect(core.executeBuiltinLine(3, "Msg another")); - } - const s = try core.render(core.scratch.allocator()); - try std.testing.expectEqual(@as(usize, cover.len), @as(usize, s.cols) * s.rows); - @memset(&cover, .{ .layer = true, .floating = true, .grip = true, .focus = true }); // what an earlier frame left - coverFrame(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); - try expectCoverIsScan(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers()); - // A grip's cells know their way to its glyph, and the focused - // pane's tag rows are the focused ones. - for (s.regionList()) |region| { - if (region.kind != .grip) continue; - for (0..region.rect.w) |offset| { - const cell = cover[@as(usize, region.rect.y) * s.cols + region.rect.x + offset]; - try std.testing.expect(cell.grip); - try std.testing.expectEqual(offset, cell.grip_offset); - try std.testing.expectEqual(region.owner == core.view().active, cell.focus); - } - } - for (s.tagLayers()) |layer| notices = notices or (layer.rows != 0 and layer.kind == .notice); - } - try std.testing.expect(notices); - - // Random layers: overlapping, empty, past the grid's right and bottom - // edges, and at the top of u16, where x + w overflows it. - const gen = struct { - fn coordinate(random: std.Random, limit: u16) u16 { - if (random.uintLessThan(u8, 12) == 0) return std.math.maxInt(u16) - random.uintLessThan(u16, 3); - return random.uintAtMost(u16, limit + 3); - } - fn rect(random: std.Random, cols: u16, rows: u16) pardes.Rect { - return .{ .x = coordinate(random, cols), .y = coordinate(random, rows), .w = coordinate(random, cols), .h = coordinate(random, rows / 2) }; - } - }; - var prng = std.Random.DefaultPrng.init(0x6c61796572); - const random = prng.random(); - var body: [pardes.MAX_PANES]pardes.Layer = undefined; - var tag: [pardes.MAX_TAG_LAYERS]pardes.Layer = undefined; - var grid: [64 * 40]Cover = undefined; - for (0..3000) |_| { - const cols = random.intRangeAtMost(u16, 1, 64); - const rows = random.intRangeAtMost(u16, 1, 40); - const empty = random.intRangeAtMost(u8, 2, 5); // about one layer in `empty` is empty - for (&body) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; - for (&tag) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; - const bodies = body[0..random.uintAtMost(usize, body.len)]; - const tags = tag[0..random.uintAtMost(usize, tag.len)]; - const cells = grid[0 .. @as(usize, cols) * rows]; - @memset(cells, .{ .layer = random.boolean() }); - coverFrame(cells, cols, rows, bodies, tags, &.{}); - try expectCoverIsScan(cells, cols, rows, bodies, tags); - } -} - -test "every pixel of a grip column is band, button or ring, and the button sits over the scrollbar" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([60][5]u8, @splat("text\n".*)))); - pane.tag.own = try gpa.dupe(u8, "second\nthird"); - core.newScratchBelow(0); - for ([_]struct { w: u32, h: u32, tag: u32 }{ .{ .w = 10, .h = 20, .tag = 12 }, .{ .w = 17, .h = 35, .tag = 30 }, .{ .w = 9, .h = 19, .tag = 15 }, .{ .w = 12, .h = 24, .tag = 24 } }) |m| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { - core.view().active = focus; - pane.file.?.revision = pane.file.?.saved_revision + @intFromBool(dirty); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var g = testGui(m.w, m.h, m.w, m.tag); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - const win_w: f32 = @floatFromInt(60 * m.w); - const win_h: f32 = @floatFromInt(20 * m.h); - const cover = try gpa.alloc(Cover, @as(usize, s.cols) * s.rows); - defer gpa.free(cover); - coverFrame(cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, win_w, win_h, true); - const grip = s.region(.grip, 0).?; - // The grip column's pixels, band first, then its cells, then decor. - const x_px: u32 = grip.rect.x * m.w; - const w_px: u32 = config.GUTTER * m.w; - const y_px: u32 = grip.rect.y * m.h; - const h_px: u32 = grip.rect.h * m.h; - const pixels = try gpa.alloc(?[3]f32, w_px * h_px); - defer gpa.free(pixels); - @memset(pixels, null); - const paint = struct { - fn quad(into: []?[3]f32, x0n: f32, y0n: f32, x1n: f32, y1n: f32, rgb: [3]f32, ww: f32, wh: f32, ox: u32, oy: u32, pw: u32, ph: u32) void { - const px0: i64 = @intFromFloat(@round((x0n + 1) / 2 * ww)); - const px1: i64 = @intFromFloat(@round((x1n + 1) / 2 * ww)); - const py0: i64 = @intFromFloat(@round((1 - y0n) / 2 * wh)); - const py1: i64 = @intFromFloat(@round((1 - y1n) / 2 * wh)); - var y = @max(py0, oy); - while (y < @min(py1, oy + ph)) : (y += 1) { - var x = @max(px0, ox); - while (x < @min(px1, ox + pw)) : (x += 1) into[@intCast((y - oy) * pw + (x - ox))] = rgb; - } - } - }; - var instances: [4]CellInstance = undefined; - for (0..grip.rect.h) |line| for (0..config.GUTTER) |dx| { - const col: u16 = grip.rect.x + @as(u16, @intCast(dx)); - const row: u16 = grip.rect.y + @as(u16, @intCast(line)); - const at = @as(usize, row) * s.cols; - var next: u32 = 0; - emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, bg_default); - for (instances[0..next]) |i| paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); - }; - for (g.decor.items) |i| if (i.fr >= 1 and i.clip_x1 < i.clip_x0) paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); - const rgb = struct { - fn of(v: [3]u8) [3]f32 { - return .{ @as(f32, @floatFromInt(v[0])) / 255, @as(f32, @floatFromInt(v[1])) / 255, @as(f32, @floatFromInt(v[2])) / 255 }; - } - }.of; - const chrome = &s.chrome; - const band = if (focus == 0) chrome.tag_focus_bg else chrome.tag_bg; - // Band, fills, rings, the rules between stacked panes and under the - // tag, and the mode marks' ink (the grip's first cell's). - const ink = inkOn(gripFill(chrome, grip.active, grip.dirty)); - const allowed = [_][3]f32{ rgb(band), rgb(core.chromeTheme().box), rgb(pardes.draw.boxDirty(core)), rgb(chrome.grip_border), rgb(chrome.grip_focus_ring), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)) }; - for (pixels, 0..) |pixel, n| { - const got = pixel orelse return error.TestUnpaintedGripPixel; - const known = for (allowed) |a| { - if (std.meta.eql(a, got)) break true; - } else false; - // Under the first row there is no button: band and rules only. - if (n / w_px >= m.h and n / w_px < h_px - 1 and !std.meta.eql(got, rgb(band)) and !std.meta.eql(got, rgb(chrome.border))) - return error.TestButtonUnderFirstRow; - if (!known) std.debug.print("sliver {any} at {d},{d} of {d}x{d} (metrics {d}x{d}/{d}, focus {d}, dirty {}) page {any}\n", .{ got, n % w_px, n / w_px, w_px, h_px, m.w, m.h, m.tag, focus, dirty, s.chrome.page }); - try std.testing.expect(known); - } - // The rule under the tag runs unbroken across the grip column. - for (pixels[(h_px - 1) * w_px ..][0..w_px]) |pixel| - try std.testing.expectEqual(rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)), pixel.?); - // The button's edges are the scrollbar's. - const button = gripButton(&g, chrome, grip.rect.x, grip.rect.y, layout); - const column = scrollColumn(&g, chrome, s.region(.rail, 0).?.rect.x, layout); - try std.testing.expectEqual(column[0], button[0]); - try std.testing.expectEqual(column[1], button[2]); - }; - pane.file.?.revision = pane.file.?.saved_revision; -} - -test "small tagline fonts leave no background gutters between adjacent tags" { - const chrome: pardes.Chrome = .{}; - var g = testGui(10, 20, 8, 16); - const cell: pardes.Cell = .{ .default = false, .style = .{ .font_role = .tagline } }; - var instances: [6]CellInstance = undefined; - var next: u32 = 0; - for (0..3) |row| { - // Column 1: past the anchor's inset edge at the column's left. - emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, bg_default); - const base = instances[row * 2]; - const ink = instances[row * 2 + 1]; - try std.testing.expectApproxEqAbs(@as(f32, 20.0 / 480.0 * 2), base.y0 - base.y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 16.0 / 480.0 * 2), ink.y0 - ink.y1, 0.0001); - try std.testing.expect(ink.y0 <= base.y0 and ink.y1 >= base.y1); - try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), ink.x1 - ink.x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 10) / atlas_w, ink.u1 - ink.u0, 0.0001); - if (row > 0) try std.testing.expectApproxEqAbs(instances[(row - 1) * 2].y1, base.y0, 0.0001); - } - // Column 0 is an anchor's edge: its ink is inset by the band's margin - // (2 px here) and its underlay still covers the whole cell. - next = 0; - emitSurfaceCell(&g, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, bg_default); - try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), instances[0].x1 - instances[0].x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 8.0 / 800.0 * 2), instances[1].x1 - instances[1].x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 8) / atlas_w, instances[1].u1 - instances[1].u0, 0.0001); -} - -test "block cursor alone overrides transparent cell background" { - var g = testGui(10, 20, 6, 12); - const cell: pardes.Cell = .{}; - var instances: [2]CellInstance = undefined; - for ([_]bool{ false, true }, 0..) |cursor, i| { - emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, bg_default); - try std.testing.expectEqual(cursor, instances[i].effect & opaque_bg_bit != 0); - } -} - -test "insert cursor overlays without replacing the character beneath it" { - const cell: pardes.Cell = .{ - .text = .{ 'x', ' ', ' ', ' ', ' ', ' ', ' ' }, - .len = 1, - .default = false, - }; - try std.testing.expectEqual(@as(u32, 'x'), cellCodepoint(&cell)); - - // A bar at a tag cell: tagline-tall, centered in its row, in the - // cell's ink, drawn as decor over it. - var cells: [25]pardes.Cell = @splat(.{}); - cells[3 * 5 + 2] = .{ .default = false, .style = .{ .fg = .{ .rgb = .{ 32, 48, 64 } }, .font_role = .tagline } }; - const surface: pardes.Surface = .{ .cols = 5, .rows = 5, .cells = &cells, .cursor = .{ .x = 2, .y = 3, .bar = true } }; - var g = testGui(10, 20, 8, 8); - defer g.decor.deinit(std.testing.allocator); - try cursorDecor(&g, std.testing.allocator, &surface, fixedCellLayout(&g), 100, 100); - try std.testing.expectEqual(@as(usize, 1), g.decor.items.len); - const bar = g.decor.items[0]; - try std.testing.expectApproxEqAbs(@as(f32, -0.32), bar.y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, -0.48), bar.y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 32.0 / 255.0), bar.br, 0.0001); - try std.testing.expectEqual(@as(f32, 1), bar.fr); -} - -test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(bytes); - var g = try textTestGui(bytes, 27); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - - const line = textTestLine("a->b"); - var slots: [4]Slot = undefined; - for (&slots, 0..) |*slot, i| slot.* = cellSlot(&g, &line, i, null, .body); - // `->` is one glyph strip two cells wide: each cell samples its own half. - try std.testing.expectEqual(slots[1].v, slots[2].v); - try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u); - var strips: usize = 0; - var it = g.atlas.glyphs.iterator(); - while (it.next()) |entry| if (entry.key_ptr.span == 2) { - strips += 1; - try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead); - try std.testing.expectEqual(slots[1], entry.value_ptr.*); - }; - try std.testing.expectEqual(@as(usize, 1), strips); - // The arrow runs through the seam: both halves carry ink at it. - const seam = g.atlas.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; - var left_ink: usize = 0; - var right_ink: usize = 0; - for (0..g.cell_h) |y| { - left_ink += seam[y * atlas_w + slots[2].u - 1]; - right_ink += seam[y * atlas_w + slots[2].u]; - } - try std.testing.expect(left_ink > 0 and right_ink > 0); - // `a` and `b` are their plain glyphs. - try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('a').glyph, .role = .body }).?, slots[0]); - try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('b').glyph, .role = .body }).?, slots[3]); - - // A second line with the same word reuses the shaped slots. - const again = textTestLine("a->b"); - const text_len = g.words.text.items.len; - for (0..4) |i| try std.testing.expectEqual(slots[i], cellSlot(&g, &again, i, null, .body)); - try std.testing.expectEqual(text_len, g.words.text.items.len); - - // The cursor on either half shows plain `-` and `>`. - const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('-').glyph, .role = .body }).?; - const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('>').glyph, .role = .body }).?; - for ([_]usize{ 1, 2 }) |cursor| { - try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body)); - try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body)); - } - // A tagline is never shaped. - try std.testing.expectEqual(g.atlas.glyphForCodepoint('-').glyph, (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); -} - -test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { - var g = try textTestGui(font_ttf, 18); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - // Each glyph as it is drawn unshaped, in an atlas of its own. - var plain = try textTestGui(font_ttf, 18); - defer plain.atlas.deinit(std.testing.allocator); - defer plain.words.deinit(std.testing.allocator); - const text = "a->b != c => d <= e |> www == :: 0x1F"; - var line = textTestLine(text); - line[3].style.bold = true; // a style change inside a word - for (line, 0..) |cell, i| { - if (text[i] == ' ') continue; - const slot = cellSlot(&g, &line, i, null, .body); - const key = try glyphKeyAt(&g, slot); - try std.testing.expectEqual(g.atlas.glyphForCodepoint(text[i]).glyph, key.glyph); - try std.testing.expectEqual(@as(u4, 1), key.span); - const expected = cachedGlyph(&plain, .{ .face = 0, .glyph = key.glyph, .role = .body, .decoration = .{ .bold = cell.style.bold } }).?; - for (0..g.cell_h) |y| - try std.testing.expectEqualSlices(u8, plain.atlas.atlas_stage[(expected.v + y) * atlas_w + expected.u ..][0..g.cell_w], g.atlas.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); - } -} - -test "pane indicator cached ink centers bearings styles and sizes" { - var g = testGui(10, 20, 6, 12); - g.atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer g.atlas.deinit(std.testing.allocator); - for ([_]f32{ 13, 27, 40 }) |px| { - g.px = px; - var cw: c_int = 0; - var ch: c_int = 0; - g.atlas.cellMetrics(px, &cw, &ch, &g.ascent); - g.cell_w = @intCast(cw); - g.cell_h = @intCast(ch); - for ([_]u8{ 40, 82, 100 }) |percent| { - const tag = taglineRaster(&g.atlas, px, g.cell_w, g.cell_h, percent); - g.tagline_width = tag.width; - g.tagline_height = tag.height; - g.tagline_px = tag.px; - g.tagline_baseline = tag.baseline; - resetGlyphAtlas(&g); - try std.testing.expectEqual(@as(usize, 0), g.atlas.glyphs.count()); - for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const key: GlyphKey = .{ .face = 0, .glyph = g.atlas.glyphForCodepoint(cp).glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; - const slot = cachedGlyph(&g, key).?; - const bounds = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; - const center_x: isize = @intCast(bounds.min_x + bounds.max_x); - const center_y: isize = @intCast(bounds.min_y + bounds.max_y); - try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1); - try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1); - const count = g.atlas.glyphs.count(); - const pen = g.atlas.pen_x; - try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); - try std.testing.expectEqual(count, g.atlas.glyphs.count()); - try std.testing.expectEqual(pen, g.atlas.pen_x); - }; - } - } - resetGlyphAtlas(&g); - g.atlas.pen_y = atlas_h; - try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('^').glyph, .role = .tagline, .centered = true })); -} - -test "pane indicator halves are safe on an exhausted atlas" { - var cells: [12]pardes.Cell = @splat(.{ .default = false, .style = .{ .font_role = .tagline } }); - cells[0].text[0] = '$'; - // A grip two cells wide at the top left. - const grip = [_]pardes.Region{.{ .kind = .grip, .serial = 1, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}; - var cover: [12]Cover = undefined; - coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); - try std.testing.expect(cover[0].grip and cover[1].grip and !cover[2].grip); - // A column's grip is a button too, cut the same way (it has no glyph). - coverFrame(&cover, 6, 2, &.{}, &.{}, &.{.{ .kind = .column_grip, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}); - try std.testing.expect(cover[0].grip); - coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); - const chrome: pardes.Chrome = .{}; - - var g = testGui(10, 20, 8, 16); - g.atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer g.atlas.deinit(std.testing.allocator); - g.px = 20; - g.tagline_px = 16; - g.atlas.pen_y = atlas_h; - defer g.words.deinit(std.testing.allocator); - var instances: [4]CellInstance = undefined; - var next: u32 = 0; - for (0..2) |col| { - emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); - try std.testing.expectEqual(@as(f32, 0), instances[col * 2 + 1].u0); - } - try std.testing.expectEqual(@as(u32, 4), next); -} - -test "a concealed cell's underline draws nothing of its own" { - const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); -} - -test "overlapping background layers keep one uniform opacity" { - const blend = Cells.backgroundLayerBlend(); - try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); - try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor); - for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| { - var alpha = opacity; - for ([_]f32{ 1, 0.5, 0.88, 0, 1 }) |coverage| { - alpha = opacity * coverage + alpha * (1 - coverage); - try std.testing.expectApproxEqAbs(opacity, alpha, 0.00001); - } - } -} - -test "background opacity retains exact endpoints and percentage precision" { - try std.testing.expectEqual(@as(f32, 0), backgroundOpacity(0)); - try std.testing.expectEqual(@as(f32, 0.7), backgroundOpacity(70)); - try std.testing.expectEqual(@as(f32, 1), backgroundOpacity(100)); - for (0..100) |percent| { - try std.testing.expect(backgroundOpacity(@intCast(percent)) < backgroundOpacity(@intCast(percent + 1))); - } -} - -test "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.sync(); - const s = try core.render(core.scratch.allocator()); - defer dim = .{}; - dim.begin(60, s.regionList()); - try std.testing.expect(dim.focused != pardes.Region.none); - var cover: [80 * 24]Cover = undefined; - coverFrame(&cover, 80, 24, &.{}, &.{}, s.regionList()); - var seen: [2]bool = .{ false, false }; - for (s.regionList()) |region| if (region.kind == .body or region.kind == .tag) { - const unfocused = region.owner != dim.focused; - try std.testing.expectEqual(unfocused, cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); - seen[@intFromBool(unfocused)] = true; - } else if (region.kind == .grip) try std.testing.expect(!cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); - try std.testing.expect(seen[0] and seen[1]); - // Toward the ground, a pair already near its floor no further. - var instance: CellInstance = std.mem.zeroes(CellInstance); - instance.fr = 0.9; - instance.fg = 0.9; - instance.fb = 0.9; - dim.fade(&instance); - try std.testing.expect(instance.fr < 0.9 and instance.fr > 0); - try std.testing.expect(pardes.colors.contrast(Dim.byteRgb(.{ instance.fr, instance.fg, instance.fb }), .{ 0, 0, 0 }) >= 4.5 - 1e-3); - // Off, nothing fades. - dim.begin(0, s.regionList()); - try std.testing.expect(!dim.of(0) and !dim.of(1)); -} - -test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px black rules and 12px track" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); - for (0..40) |_| core.update(.tick); - core.sync(); - const s = try core.render(core.scratch.allocator()); - try std.testing.expectEqual(@as(u8, 2), s.chrome.rule_px); - // acme's 12px, at GripWidth's 150% default. - try std.testing.expectEqual(@as(u8, 18), s.chrome.rail_px); - var g = testGui(16, 20, 10, 12); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 480, true); - const px = struct { - fn w(item: CellInstance) f32 { - return (item.x1 - item.x0) / 2 * 1280; - } - }; - var spines: usize = 0; - var tracks: usize = 0; - for (g.decor.items) |item| { - const black = item.br == 0 and item.bg == 0 and item.bb == 0; - // No rule at the window's left edge; one 2px spine where columns meet. - if (black and @abs(px.w(item) - 2) < 0.01 and item.y1 < -0.9) { - try std.testing.expect(item.x0 > -1); - spines += 1; - } - const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - if (@abs(item.br - @as(f32, 0x99) / 255) < 1e-3 and @abs(item.bb - @as(f32, 0x4c) / 255) < 1e-3 and @abs(px.w(item) - (column[1] - column[0])) < 0.01) tracks += 1; - } - try std.testing.expectEqual(@as(usize, 1), spines); - try std.testing.expect(tracks >= 2); -} - -test "the scrollbar thumb moves by the pixel and follows a glide" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const thumb = struct { - // The thumb's top, in window pixels. - fn top(gui: *Gui, p: *pardes.Pardes) !f32 { - gui.decor.clearRetainingCapacity(); - p.sync(); - const s = try p.render(p.scratch.allocator()); - var groups: Groups = .{}; - try buildDecor(gui, std.testing.allocator, s, &groups, fixedCellLayout(gui), 800, 480, true); - const ink = s.chrome.scroll_thumb; - for (gui.decor.items) |item| if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and - @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and - @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) return (1 - item.y0) / 2 * 480; - return error.TestExpectedThumb; - } - }; - pane.file.?.scroll = 10; - const at10 = try thumb.top(&g, core); - pane.file.?.scroll = 11; - const at11 = try thumb.top(&g, core); - // A line of a thousand moves it a fraction of a row, not 0 or 20 px. - try std.testing.expect(at11 > at10 and at11 - at10 < 1); - g.glide.pane = core.view().active; - g.glide.follow.offset = -1; - try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); - // A wrapped line: the picture moved two rows for the one line, and the - // thumb lags the line, not two. - g.glide.lines_moved = 1; - g.glide.rows_moved = 2; - g.glide.follow.offset = -2; - try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); -} - -test "the scrollbar thumb lies in its scroll column, a pixel short of the column's right edge, so the track edges it" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const ink = s.chrome.scroll_thumb; - const thumb = for (g.decor.items) |item| { - if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and - @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and - @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) break item; - } else return error.TestExpectedThumb; - // The pane is the window's first: its scroll column is at cell 0. - const column = scrollColumn(&g, &s.chrome, 0, fixedCellLayout(&g)); - try std.testing.expectApproxEqAbs(column[0], (thumb.x0 + 1) / 2 * 800, 1e-3); - try std.testing.expectApproxEqAbs(column[1] - 1, (thumb.x1 + 1) / 2 * 800, 1e-3); -} - -test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - core.newScratchBelow(0); - core.sync(); - const s = try core.render(core.scratch.allocator()); - const lower = for (s.regionList()) |region| { - if (region.kind == .tag and region.rect.y > 2) break region; - } else return error.TestExpectedStackedTag; - for ([_]u32{ 12, 20 }) |tagline_h| { - var g = testGui(10, 20, 6, tagline_h); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const top = @as(f32, @floatFromInt(lower.rect.y)) * 20; - const slack: f32 = @floatFromInt(@max(1, pardes.Layer.taglineBandOffset(lower.rect.y, 480, 20, tagline_h))); - var found = false; - for (g.decor.items) |item| { - const y0 = (1 - item.y0) / 2 * 480; - const y1 = (1 - item.y1) / 2 * 480; - if (@abs(y0 - top) > 0.01 or @abs(item.br - @as(f32, @floatFromInt(s.chrome.border[0])) / 255) > 1e-3) continue; - found = true; - try std.testing.expect(y1 - y0 <= slack + 0.01); - } - try std.testing.expect(found); - } -} - -test "an empty column is ruled on both sides, as between two filled ones" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - // Newcol from the left pane: an empty column between the two filled ones. - pardes.layout.newColumn(core, 0); - core.sync(); - try std.testing.expectEqual(@as(usize, 3), core.view().ncol); - try std.testing.expectEqual(@as(usize, 0), core.view().cols[1].n); - const s = try core.render(core.scratch.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); - const border = [3]f32{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 }; - // Its left edge and its right edge (the next column's left): each a - // rule `rule_px` wide in the border colour, down to the window's foot. - for ([_]usize{ 1, 2 }) |column| { - const px: f32 = @floatFromInt(@as(u32, core.view().col_x[column]) * 10); - const rule = for (g.decor.items) |item| { - if (@abs(item.x0 - (px / 800 * 2 - 1)) < 1e-4 and @abs(item.x1 - ((px + @as(f32, @floatFromInt(s.chrome.rule_px))) / 800 * 2 - 1)) < 1e-4 and - std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &border)) break item; - } else return error.TestExpectedColumnRule; - try std.testing.expectEqual(@as(f32, -1), rule.y1); - } -} - -test "at a 2x display every logical pixel is two: rules, the tag rule, the grip's ring, the rail's edge" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); - for (0..40) |_| core.update(.tick); - core.sync(); - const s = try core.render(core.scratch.allocator()); - for ([_]f32{ 1, 2 }) |scale| { - display_scale = scale; - defer display_scale = 1; - var g = testGui(16, 32, 12, 24); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 768, true); - const w = struct { - fn of(item: CellInstance) f32 { - return (item.x1 - item.x0) / 2 * 1280; - } - fn h(item: CellInstance) f32 { - return (item.y0 - item.y1) / 2 * 768; - } - }; - var spine: ?f32 = null; - var tag_rule: ?f32 = null; - var ring: ?f32 = null; - for (g.decor.items) |item| { - const rgb: [3]u8 = .{ @intFromFloat(@round(item.br * 255)), @intFromFloat(@round(item.bg * 255)), @intFromFloat(@round(item.bb * 255)) }; - // The spine between the columns: black, tall. - if (std.mem.eql(u8, &rgb, &.{ 0, 0, 0 }) and w.h(item) > 300) spine = @round(w.of(item)); - // The tag rule: #8888cc, wide and thin. - if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.of(item) > 200) tag_rule = @round(w.h(item)); - // The ring's left side: #8888cc, a tag row tall. - if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.h(item) > 10 and w.of(item) < 8) ring = @round(w.of(item)); - } - try std.testing.expectEqual(@as(?f32, 2 * scale), spine); - try std.testing.expectEqual(@as(?f32, 1 * scale), tag_rule); - try std.testing.expectEqual(@as(?f32, 2 * scale), ring); - // The rail starts after the rule, a logical 2 in, and keeps a - // logical 3 clear of the text when the cell is narrow. - const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - try std.testing.expectEqual(40 * 16 + 2 * scale, column[0]); - g.cell_w = 12; - defer g.cell_w = 16; - const narrow = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - try std.testing.expectEqual(@as(f32, 40 * 12 + 2 * scale), narrow[0]); - try std.testing.expectEqual(@as(f32, 40 * 12) + 12 * @as(f32, @floatFromInt(config.GUTTER)) - 3 * scale, narrow[1]); - g.cell_w = 8; - // A bar cursor is an eighth of its cell, never under a logical pixel - // (an 8 px cell: one pixel, two at 2x). - const saved = s.cursor; - defer s.cursor = saved; - s.cursor = .{ .x = 60, .y = 10, .bar = true }; - var boxes: [max_cursors]CursorBox = undefined; - const n = cursorBoxes(&g, s, fixedCellLayout(&g), 768, &boxes); - const bar = for (boxes[0..n]) |box| { - if (box.bar and box.x0 == 60 * 8) break box; - } else return error.NoBarCursor; - try std.testing.expectEqual(scale, bar.x1 - bar.x0); - } -} - -test "decor is read from the regions" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - const ndc = struct { - fn x(px: f32) f32 { - return px / 800 * 2 - 1; - } - }; - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); - // A spine one pixel wide at each column's left edge, down from under the - // workspace tag; a rail two pixels wide at each pane's. - for (core.view().col_x[0..core.view().ncol]) |x| { - const left = ndc.x(@as(f32, @floatFromInt(x)) * 10); - // Two pixels (rule_px), and none at the window's own edge. - const spine = for (g.decor.items) |item| { - if (item.x0 == left and @abs(item.x1 - ndc.x(@as(f32, @floatFromInt(x)) * 10 + 2)) < 0.0001 and - @abs(item.y0 - (1 - 20.0 / 480.0 * 2)) < 0.0001 and std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &.{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 })) break item; - } else null; - try std.testing.expectEqual(x == 0, spine == null); - if (spine) |rule| { - try std.testing.expectApproxEqAbs(@as(f32, 1 - 20.0 / 480.0 * 2), rule.y0, 0.0001); - try std.testing.expectEqual(@as(f32, -1), rule.y1); - } - // The scrollbar fills the scroll column right of the rule. - const column = scrollColumn(&g, &s.chrome, x, layout); - const rail = for (g.decor.items) |item| { - if (@abs(item.x0 - ndc.x(column[0])) < 0.0001 and @abs(item.x1 - ndc.x(column[1])) < 0.0001 and - @abs(item.br - @as(f32, @floatFromInt(s.chrome.scroll_track[0])) / 255) < 0.0001) break item; - } else return error.TestExpectedRail; - _ = rail; - } - try std.testing.expectEqual(@as(u32, 0), groups.items[groups.notices].decor_count); -} - -test "a body tells its first line" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); - pane.scrollBy(8); - core.sync(); - const s = try core.render(core.scratch.allocator()); - const body = for (s.regionList()) |region| { - if (region.kind == .body) break region; - } else return error.NoBody; - try std.testing.expectEqual(@as(i32, 8), body.line); -} - -test "a caret eases a cell at a time, keeps up with typing, and glides a jump, landing exactly" { - const ms = std.time.ns_per_ms; - var caret: Caret = .{}; - caret.aim(.{ .x = 3, .y = 4, .w = 1, .h = 1 }, 0, false); - // The first mark lands at once. - try std.testing.expect(!caret.moving()); - // A step eases, a stream of them keeps up. - caret.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, 1000 * ms, false); - try std.testing.expect(caret.moving()); - caret.aim(.{ .x = 5, .y = 4, .w = 1, .h = 1 }, 1050 * ms, false); - try std.testing.expect(!caret.moving()); - // A jump glides, the leading corner ahead, and lands exactly. - caret.aim(.{ .x = 30, .y = 10, .w = 1, .h = 1 }, 2000 * ms, false); - try std.testing.expect(caret.moving()); - const mid = caret.sample(2040 * ms); - try std.testing.expect(mid[1][0] > mid[0][0] - 1 and mid[0][0] > 5 and mid[0][0] < 30); - var t: u64 = 2040 * ms; - while (caret.step(t)) t += 16 * ms; - try std.testing.expect(t < 2400 * ms); - try std.testing.expectEqual([2]f32{ 30, 10 }, caret.sample(t)[0]); - // A scroll lands it with its text. - caret.see(.{ .x = 30, .y = 8, .w = 1, .h = 1 }, 0, 10, 2, 1, t); - caret.see(.{ .x = 30, .y = 6, .w = 1, .h = 1 }, 0, 12, 2, 1, t + 16 * ms); - try std.testing.expect(!caret.moving()); -} - -test "a jump's trail is drawn behind the cursor in its body, and gone by 120 ms" { - var cells: [80 * 4]pardes.Cell = @splat(.{}); - var surface: pardes.Surface = .{ .cols = 80, .rows = 4, .cells = &cells }; - surface.regions[0] = .{ .kind = .body, .rect = .{ .x = 2, .y = 0, .w = 78, .h = 4 } }; - surface.nregions = 1; - var g = testGui(10, 20, 8, 16); - var vertices: [5 * 6]OverlayVertex = undefined; - var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 80 }; - const ms = std.time.ns_per_ms; - surface.cursor = .{ .x = 4, .y = 1 }; - appendJumpTrail(&g, true, &surface, 1000 * ms, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - surface.cursor = .{ .x = 14, .y = 1 }; - appendJumpTrail(&g, true, &surface, 1016 * ms, &builder); - try std.testing.expect(builder.len >= 3 * 6 and builder.len <= 5 * 6); - // On the cursor's row, behind it, never its own cell. - for (vertices[0..builder.len]) |v| { - const x = (v.x + 1) * 400; - const y = (1 - v.y) * 40; - try std.testing.expect(y >= 20 - 0.01 and y <= 40 + 0.01); - try std.testing.expect(x >= 50 - 0.01 and x <= 140 + 0.01); - } - try std.testing.expect(g.trail.active); - builder.len = 0; - appendJumpTrail(&g, true, &surface, 1150 * ms, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - try std.testing.expect(!g.trail.active); -} - -test "a pet stays past the workspace tag's text, and off it is gone" { - std.testing.refAllDecls(pet); - var cells: [80]pardes.Cell = @splat(.{}); - const surface: pardes.Surface = .{ .cols = 80, .rows = 1, .cells = &cells }; - for ("Workspace Commands", 0..) |ch, i| { - cells[i].text[0] = ch; - cells[i].len = 1; - cells[i].default = false; - } - var g = testGui(10, 20, 8, 16); - var vertices: [pet.max_vertices]OverlayVertex = undefined; - var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 480 }; - appendWorkspacePet(&g, .cat, &surface, &builder); - try std.testing.expect(builder.len > 0); - for (vertices[0..builder.len]) |v| { - const x = (v.x + 1) * 400; - const y = (1 - v.y) * 240; - try std.testing.expect(x >= 20 * 8 - 0.01); - try std.testing.expect(y >= 0 and y < 20); - } - builder.len = 0; - appendWorkspacePet(&g, .off, &surface, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - try std.testing.expectEqual(@as(?u64, null), g.pet_state.tick); -} - -test "compact body layer rendering fills recovered rows and clips the final glyph" { - var g = testGui(10, 20, 6, 12); - var cells: [24]pardes.Cell = @splat(.{}); - var layer: pardes.Layer = .{ - .viewport = .{ .x = 3, .y = 2, .w = 2, .h = 5 }, - .cols = 2, - .rows = 12, - .context_rows = 4, - .cells = &cells, - }; - layer.setContextLines(&.{ 0, 4, 5, 6 }); - var instances: [32]CellInstance = undefined; - var next: u32 = 0; - emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); - // Four compact header rows (48px), then three body rows: two complete - // and a third clipped to the remaining12px of the100px viewport. - try std.testing.expectEqual(@as(u32, 20), next); - try std.testing.expectApproxEqAbs(@as(f32, 0.49), instances[3].y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0.48), instances[3].y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 80.0 / 255.0), instances[3].br, 0.0001); - try std.testing.expectApproxEqAbs(instances[3].br, instances[13].br, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0.6), instances[0].y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0.12), instances[14].y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, -0.4), instances[19].y1, 0.0001); - try std.testing.expectApproxEqAbs(instances[19].v0 + @as(f32, 12) / atlas_h, instances[19].v1, 0.0001); - // A drag preview reserves the last physical column without changing cells. - layer.viewport.w = 1; - next = 0; - emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); - for (instances[0..next]) |instance| try std.testing.expect(instance.x1 <= -0.6 + 0.0001); -} - -test "compact tag layers fill available width and clip at their physical edge" { - var g = testGui(10, 20, 6, 12); - var cells: [6]pardes.Cell = @splat(.{}); - const layer: pardes.Layer = .{ .kind = .pane, .id = 0, .serial = 7, .viewport = .{ .x = 2, .y = 3, .w = 3, .h = 1 }, .cols = 6, .rows = 1, .cells = &cells, .bg = .{ 20, 30, 40 } }; - var instances: [8]CellInstance = undefined; - var next: u32 = 0; - emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); - // Five six-pixel cells fit in the three body-column viewport. - try std.testing.expectEqual(@as(u32, 6), next); - try std.testing.expectApproxEqAbs(@as(f32, -0.6), instances[1].x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0), instances[5].x1, 0.0001); - g.tagline_width = 8; - next = 0; - emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); - try std.testing.expectEqual(@as(u32, 5), next); - try std.testing.expectApproxEqAbs(@as(f32, 0), instances[4].x1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 6) / atlas_w, instances[4].u1 - instances[4].u0, 0.0001); -} - -test "trackpad rotation never types search keys into an insert-mode file or raw terminal" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); - defer core.deinit(); - _ = try core.setTestFile("unchanged\n"); - var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; - defer client.deinit(); - var in: Input = .{ .core = core, .client = &client }; - var g: Gui = undefined; - g.trackpad = .{}; - var ev: c.UITrackpadEvent = std.mem.zeroes(c.UITrackpadEvent); - ev.kind = c.UI_TRACKPAD_ROTATE; - ev.a = 20; - const pane = core.panes[core.view().active].?; - pane.body.mode = .insert; - dispatchTrackpad(&g, &in, &ev); - pane.body.mode = .tty; - dispatchTrackpad(&g, &in, &ev); - try std.testing.expectEqual(@as(usize, 0), client.pending.items.len); - ev.kind = c.UI_TRACKPAD_HISTORY; - ev.a = -1; - dispatchTrackpad(&g, &in, &ev); - ev.a = 1; - dispatchTrackpad(&g, &in, &ev); - try std.testing.expectEqual(@as(usize, 2), client.pending.items.len); - try std.testing.expectEqualStrings("Back", client.pending.items[0].command); - try std.testing.expectEqualStrings("Forward", client.pending.items[1].command); -} - -test "a detached GUI authority follows terminal directory changes with no window" { - const gpa = std.testing.allocator; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "child"); - var start_buf: [4096]u8 = undefined; - const start = start_buf[0..try tmp.dir.realPath(io, &start_buf)]; - var cwd_buf: [4096]u8 = undefined; - const expected = cwd_buf[0..try tmp.dir.realPathFile(io, "child", &cwd_buf)]; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.shell_spoke = true; - _ = core.settings.shell.effective.set("/bin/sh"); - var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - const rcs: host_io.Shell.PromptFiles = .{}; - var pipes: PipeTasks = .{}; - var watches: file_watch.Table = @splat(null); - var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches }; - defer shell.shutdownPtys(); - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); - const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000; - var actual: [4096]u8 = undefined; - while (std.Io.Clock.awake.now(io).toMilliseconds() < until) { - if (host_io.shellCwd(child.pid, &actual)) |cwd| if (std.mem.eql(u8, cwd, expected)) break; - try io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expectEqualStrings(expected, host_io.shellCwd(child.pid, &actual) orelse return error.MissingCwd); - pollFrame(&shell); - try std.testing.expectEqualStrings(expected, core.panes[0].?.cwd.owned); -} - -test "detached trackpad scrolling keeps fractions local and queues whole rows for replication" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); - defer core.deinit(); - _ = try core.setTestFile("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\nsixteen\nseventeen\neighteen\nnineteen\ntwenty\n"); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - _ = try core.render(arena.allocator()); - var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; - defer client.deinit(); - var in: Input = .{ .core = core, .client = &client }; - const id = core.view().active; - const r = core.view().rects[id]; - var g: Gui = undefined; - g.scroll_pane = id; - g.scroll_delta = 0.375; - g.scroll_lag = 0; - g.scroll_idle = 0; - g.scroll_notch = 0; - g.scroll_edge = &.{}; - g.scroll_edge_len = 0; - g.glide = .{}; - g.scroll_col = r.x + config.GUTTER + 2; - g.scroll_row = core.bodyTop(core.panes[id].?, r) + 2; - defer gpa.free(g.scroll_edge); - const before = core.panes[id].?.scroll(); - try std.testing.expect(scrollRows(&g, &in, gpa)); - try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); - // The next row is fetched early; its inverse raster offset keeps the - // exact fraction under the finger until that row is fully shown. - try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(client.pending.items.len)) + g.scroll_lag); - try std.testing.expectEqual(before, core.panes[id].?.scroll()); - core.update(client.pending.items[0]); - client.pending.clearRetainingCapacity(); - g.scroll_delta = 0.75; - try std.testing.expect(scrollRows(&g, &in, gpa)); - try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); - try std.testing.expectEqual(before + 1, core.panes[id].?.scroll()); - try std.testing.expect(client.pending.items[0].mouse.shift); - core.update(client.pending.items[0]); - try std.testing.expectEqual(@as(f32, 1.125), @as(f32, @floatFromInt(core.panes[id].?.scroll() - before)) + g.scroll_lag); -} - -/// Render addon scenes to textures on this device, before the page's pass. -/// The fallback cells remain visible if decoding or pipeline creation fails. -fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, surface: *const pardes.Surface) void { - for (surface.gpu_frames, 0..) |maybe, id| { - const scratch: GpuScene.abi.Image = @fromBackingInt(@intCast(pardes.MAX_PANES + id + 1)); - const frame = maybe orelse { - if (g.addon_gpu) |*gpu| { - gpu.forget(@fromBackingInt(@intCast(id + 1))); - gpu.forget(scratch); - } - g.addon_hash[id] = 0; - g.addon_serial[id] = 0; - g.addon_failed[id] = 0; - continue; - }; - const hash = std.hash.Wyhash.hash(frame.serial, frame.bytes); - if (g.addon_failed[id] == hash) continue; - if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.cells.device); - const gpu = &g.addon_gpu.?; - const target: GpuScene.abi.Image = @fromBackingInt(@intCast(id + 1)); - if (g.addon_hash[id] != hash or g.addon_serial[id] != frame.serial) { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var scene = GpuScene.decodeFrame(arena.allocator(), frame.bytes) catch |err| { - log.warn("addon GPU scene: {t}", .{err}); - g.addon_failed[id] = hash; - continue; - }; - scene.pass.image = if (scene.post != null) scratch else target; - gpu.record(cmd, scene.pass) catch |err| { - log.warn("addon GPU render: {t}", .{err}); - g.addon_failed[id] = hash; - continue; - }; - if (scene.post) |post| { - gpu.postProcess(cmd, scratch, target, post) catch |err| { - log.warn("addon GPU postprocess: {t}", .{err}); - g.addon_failed[id] = hash; - continue; - }; - } else gpu.forget(scratch); - g.addon_hash[id] = hash; - g.addon_serial[id] = frame.serial; - } - const out = gpu.output(target) orelse continue; - g.cells.makeAddonPipeline() catch continue; - g.prepared_images.append(gpa, .{ - .premultiplied = true, - .texture = out.texture, - .place = .{ .pane = @intCast(id), .raster = .{ .ptr = undefined, .w = out.width, .h = out.height, .stride = out.width * 4 }, .src = .{ .x = 0, .y = 0, .w = out.width, .h = out.height }, .dst = frame.dst, .key = hash }, - }) catch {}; - } - if (g.addon_gpu) |*gpu| gpu.endFrame(); -} - -test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes to the recorded stage and slots" { - // The glyph atlas the frames sample, byte for byte and on any machine: - // FreeType and HarfBuzz are the build's, the faces the repo's (the - // embedded Adwaita Mono, assets/MapleMono-NF for ligatures and Nerd - // icons). CJK has no face of the repo's and no fallback of pardes's - // list: the frame corpus draws its .notdef. Recorded before the GPU - // move (.scratch/sketch/briefs/gpu-s0.md); a change here is a change - // to every frame. - const want = [2][2]u64{ .{ 0xa03053f14e2c5472, 0x9029886b638b07d5 }, .{ 0xcbaa53a0103aaff5, 0x7563d69768f7d867 } }; - const maple = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(maple); - defer display_scale = 1; - var got: [2][2]u64 = undefined; - for ([_]f32{ 27, 54 }, [_]f32{ 1, 2 }, &got) |px, scale, *hashes| { - display_scale = scale; - var stage_hash = std.hash.Wyhash.init(0); - var slots_hash = std.hash.Wyhash.init(0); - // 0: Adwaita Mono, Maple its fallback; 1: Maple, whose ligatures shape. - for ([_][]const u8{ font_ttf, maple }) |primary| { - var g = try textTestGui(primary, px); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false)); - try std.testing.expect(fitTaglineFont(&g, 80)); - const decorations = [_]Atlas.Decoration{ - .{}, - .{ .bold = true }, - .{ .underline = .single }, - .{ .underline = .double }, - .{ .underline = .curly }, - .{ .underline = .dotted }, - .{ .underline = .dashed }, - .{ .strikethrough = true }, - }; - for (0x21..0x7f) |cp| { - const drawn = g.atlas.glyphForCodepoint(@intCast(cp)); - for (decorations) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body, .decoration = decoration }) orelse return error.AtlasFull; - for (decorations[0..2]) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = decoration }) orelse return error.AtlasFull; - } - const space = g.atlas.glyphForCodepoint(' '); - _ = cachedGlyph(&g, .{ .face = space.face, .glyph = space.glyph, .role = .body, .decoration = .{ .underline = .single } }) orelse return error.AtlasFull; - for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]Atlas.Role{ .body, .tagline }) |role| { - _ = cachedGlyph(&g, .{ .face = 0, .glyph = cp, .role = role, .rule = true }) orelse return error.AtlasFull; - }; - for ([_]u32{ '$', '^', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const drawn = g.atlas.glyphForCodepoint(cp); - _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }) orelse return error.AtlasFull; - }; - // Nerd icons (Yazi's folder, a file, powerline's arrow): Maple's, - // the primary's or the fallback's. - for ([_]u32{ 0xe5ff, 0xf07b, 0xe0b0 }) |cp| { - const drawn = g.atlas.glyphForCodepoint(cp); - try std.testing.expect(drawn.glyph != 0); - _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body }) orelse return error.AtlasFull; - } - // Ligature strips, shaped by the words' cache as a frame shapes them. - const line = textTestLine("a->b => != <= >= == === !== |> <| :: ++ -- www office"); - for (0..line.len) |i| _ = cellSlot(&g, &line, i, null, .body); - stage_hash.update(g.atlas.atlas_stage); - const Entry = struct { key: u64, u: u32, v: u32 }; - var entries: std.ArrayList(Entry) = .empty; - defer entries.deinit(std.testing.allocator); - var it = g.atlas.glyphs.iterator(); - while (it.next()) |e| try entries.append(std.testing.allocator, .{ .key = @bitCast(e.key_ptr.*), .u = e.value_ptr.u, .v = e.value_ptr.v }); - std.mem.sort(Entry, entries.items, {}, struct { - fn less(_: void, x: Entry, y: Entry) bool { - return x.key < y.key; - } - }.less); - for (entries.items) |e| slots_hash.update(std.mem.asBytes(&e)); - } - hashes.* = .{ stage_hash.final(), slots_hash.final() }; - } - if (!std.meta.eql(want, got)) std.debug.print("atlas hashes: .{{ .{{ 0x{x}, 0x{x} }}, .{{ 0x{x}, 0x{x} }} }}\n", .{ got[0][0], got[0][1], got[1][0], got[1][1] }); - try std.testing.expectEqual(want, got); -} diff --git a/src/gui/macos_trackpad.h b/src/gui/macos_trackpad.h deleted file mode 100644 index f5266084..00000000 --- a/src/gui/macos_trackpad.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef PARDES_MACOS_TRACKPAD_H -#define PARDES_MACOS_TRACKPAD_H -#include - -enum { UI_TRACKPAD_FINGERS = 1, UI_TRACKPAD_PRESSURE, UI_TRACKPAD_ROTATE, - UI_TRACKPAD_PINCH, UI_TRACKPAD_SCROLL, UI_TRACKPAD_HISTORY }; -/* Same prefix as SDL_UserEvent; the rest lives inside SDL_Event's storage. */ -typedef struct { - Uint32 type, reserved; - Uint64 timestamp; - SDL_WindowID windowID; - int kind; - float x, y, a, b; - Uint32 phase; - int fingers; -} UITrackpadEvent; - -Uint32 ui_macos_trackpad_event_type(void); -void ui_macos_trackpad_attach(SDL_Window *window); -void ui_macos_trackpad_haptic(void); -#endif diff --git a/src/gui/macos_trackpad.m b/src/gui/macos_trackpad.m deleted file mode 100644 index 64806b9e..00000000 --- a/src/gui/macos_trackpad.m +++ /dev/null @@ -1,176 +0,0 @@ -/* AppKit input missing from SDL's public event stream. The SDL view keeps its - * drawing, keyboard and mouse responder chain; only trackpad methods change. */ -#import -#import -#include "macos_trackpad.h" -#include -#include - -static char window_key; -static char swipe_key, axis_key, suppress_momentum_key; -static Uint32 gesture_type; -static Class trackpad_class; -_Static_assert(sizeof(UITrackpadEvent) <= sizeof(SDL_Event), "trackpad event fits SDL"); - -Uint32 ui_macos_trackpad_event_type(void) { return gesture_type; } - -void ui_macos_trackpad_haptic(void) -{ - [[NSHapticFeedbackManager defaultPerformer] - performFeedbackPattern:NSHapticFeedbackPatternAlignment - performanceTime:NSHapticFeedbackPerformanceTimeNow]; -} - -static void send_gesture(NSView *view, NSEvent *event, int kind, float a, float b, int fingers) -{ - SDL_Window *window = (SDL_Window *)[objc_getAssociatedObject(view, &window_key) pointerValue]; - if (!window) return; - NSPoint point = [view convertPoint:event.locationInWindow fromView:nil]; - SDL_Event packet = {0}; - UITrackpadEvent decoded = {0}; - UITrackpadEvent *out = &decoded; - out->type = gesture_type; - out->timestamp = SDL_GetTicksNS(); - out->windowID = SDL_GetWindowID(window); - out->kind = kind; - out->x = point.x; - out->y = view.isFlipped ? point.y : NSHeight(view.bounds) - point.y; - out->a = a; - out->b = b; - out->fingers = fingers; - /* Stable decoded phases, independent of NSEventPhase's bit values. */ - if (kind == UI_TRACKPAD_ROTATE || kind == UI_TRACKPAD_PINCH || kind == UI_TRACKPAD_SCROLL) - out->phase = event.phase == NSEventPhaseBegan ? 1 : - event.phase == NSEventPhaseEnded ? 2 : - event.phase == NSEventPhaseCancelled ? 3 : 0; - memcpy(&packet, &decoded, sizeof(decoded)); - SDL_PushEvent(&packet); -} - -static void touches(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_FINGERS, 0, 0, - (int)[event touchesMatchingPhase:NSTouchPhaseTouching inView:nil].count); - /* Do not also emit SDL's absolute finger coordinates: those describe the - * trackpad surface, not a position inside this window. Scroll comes from - * scrollWheel:, including the system's momentum events. */ -} - -static void pressure(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_PRESSURE, event.stage, 0, 0); -} - -static void rotate(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_ROTATE, event.rotation, 0, 0); -} - -static void magnify(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_PINCH, 1 + event.magnification, 0, 0); -} - -static void swipe(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - /* NSEvent swipe deltaX: negative is right/back, positive left/forward. */ - if (event.deltaX != 0) - send_gesture(view, event, UI_TRACKPAD_HISTORY, event.deltaX, 0, 0); -} - -static void scroll(NSView *view, SEL selector, NSEvent *event) -{ - if (event.hasPreciseScrollingDeltas) { - if (event.phase == NSEventPhaseBegan) { - objc_setAssociatedObject(view, &axis_key, @0, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - objc_setAssociatedObject(view, &suppress_momentum_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } - if ([objc_getAssociatedObject(view, &swipe_key) boolValue]) return; - if ([objc_getAssociatedObject(view, &suppress_momentum_key) boolValue]) return; - NSInteger axis = [objc_getAssociatedObject(view, &axis_key) integerValue]; - CGFloat x = fabs(event.scrollingDeltaX), y = fabs(event.scrollingDeltaY); - if (!axis && x + y >= 3) { - if (x > y * 1.5) axis = 1; - else if (y > x * 1.5) axis = 2; - objc_setAssociatedObject(view, &axis_key, @(axis), OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } - if (axis == 1 && (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseChanged) && - !(event.modifierFlags & (NSEventModifierFlagShift | NSEventModifierFlagOption)) && - [NSEvent isSwipeTrackingFromScrollEventsEnabled]) { - // AppKit supplies Safari-style completion/cancellation and honours - // the user's Swipe Between Pages preference. No guessed velocity. - objc_setAssociatedObject(view, &swipe_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - __weak NSView *weak_view = view; - __block BOOL cancelled = NO; - __block BOOL previewed = NO; - [event trackSwipeEventWithOptions:NSEventSwipeTrackingLockDirection | NSEventSwipeTrackingClampGestureAmount - dampenAmountThresholdMin:-1 max:1 - usingHandler:^(CGFloat amount, NSEventPhase phase, BOOL complete, BOOL *stop) { - NSView *target = weak_view; - if (!target) { *stop = YES; return; } - if (phase == NSEventPhaseCancelled) cancelled = YES; - // An early notch says the swipe is approaching the - // shorter commit distance, while the fingers still move. - if (!cancelled && !complete && !previewed && fabs(amount) >= 0.12) { - previewed = YES; - ui_macos_trackpad_haptic(); - } - const BOOL commit = !cancelled && phase != NSEventPhaseNone && fabs(amount) >= 0.25; - if (!commit && !cancelled && phase != NSEventPhaseEnded && !complete) return; - objc_setAssociatedObject(target, &swipe_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - objc_setAssociatedObject(target, &suppress_momentum_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - // Commit during the physical swipe. AppKit's later - // animation to +/-1 must not set our trigger distance. - *stop = YES; - if (commit) - send_gesture(target, event, UI_TRACKPAD_HISTORY, amount > 0 ? 1 : -1, 0, 0); - }]; - return; - } - send_gesture(view, event, UI_TRACKPAD_SCROLL, - event.scrollingDeltaX, event.scrollingDeltaY, 0); - } else { - /* An ordinary mouse wheel retains SDL's discrete-notch handling. */ - [[view nextResponder] scrollWheel:event]; - } - (void)selector; -} - -void ui_macos_trackpad_attach(SDL_Window *window) -{ - NSWindow *native = (__bridge NSWindow *)SDL_GetPointerProperty( - SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); - NSView *view = native.contentView; - if (!view) return; - if (!gesture_type) { - /* SDL_EVENT_USER is already the shell's queue wake. */ - Uint32 first = SDL_RegisterEvents(2); - if (!first) return; - gesture_type = first + 1; - } - if (!trackpad_class) { - trackpad_class = objc_allocateClassPair(object_getClass(view), "PardesSDLTrackpadView", 0); - if (!trackpad_class) return; - SEL touch_selectors[] = { @selector(touchesBeganWithEvent:), @selector(touchesMovedWithEvent:), - @selector(touchesEndedWithEvent:), @selector(touchesCancelledWithEvent:) }; - for (unsigned i = 0; i < 4; ++i) - class_addMethod(trackpad_class, touch_selectors[i], (IMP)touches, "v@:@"); - class_addMethod(trackpad_class, @selector(pressureChangeWithEvent:), (IMP)pressure, "v@:@"); - class_addMethod(trackpad_class, @selector(rotateWithEvent:), (IMP)rotate, "v@:@"); - class_addMethod(trackpad_class, @selector(magnifyWithEvent:), (IMP)magnify, "v@:@"); - class_addMethod(trackpad_class, @selector(swipeWithEvent:), (IMP)swipe, "v@:@"); - class_addMethod(trackpad_class, @selector(scrollWheel:), (IMP)scroll, "v@:@"); - objc_registerClassPair(trackpad_class); - } - objc_setAssociatedObject(view, &window_key, [NSValue valueWithPointer:window], OBJC_ASSOCIATION_RETAIN_NONATOMIC); - object_setClass(view, trackpad_class); - view.allowedTouchTypes = NSTouchTypeMaskIndirect; - view.wantsRestingTouches = YES; - view.pressureConfiguration = [[NSPressureConfiguration alloc] - initWithPressureBehavior:NSPressureBehaviorPrimaryDeepClick]; -} diff --git a/src/gui/pet.zig b/src/gui/pet.zig deleted file mode 100644 index 7a13ca91..00000000 --- a/src/gui/pet.zig +++ /dev/null @@ -1,215 +0,0 @@ -//! Original code-native pixel companions. Pure, bounded geometry and a 10 Hz -//! animation clock: no textures, allocation, input handling or editor state. -const std = @import("std"); - -pub const Kind = enum { off, cat, frog }; -pub const width = 12; -pub const height = 9; -pub const max_vertices = width * height * 6; -pub const Lane = struct { left: f32, right: f32, top: f32, scale: f32 }; -pub const Pose = struct { x: f32, y: f32, scale: f32, left: bool, walking: bool, frame: u8 }; -/// The frog's hop: sits two ticks, takes off, peaks for two, comes down, lands. -const hop_ticks = 8; - -/// Only the trailing blank part of the global tag is eligible. The caller -/// supplies its last occupied cell, including any wide-grapheme continuation. -pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32) ?Lane { - if (cell_w <= 0 or band_h < height + 2) return null; - const scale = @min(3, @floor((band_h - 2) / height)); - const left = @as(f32, @floatFromInt(occupied + 2)) * cell_w; - const right = screen_w - 2 * cell_w - width * scale; - if (right - left < 4 * scale) return null; - return .{ .left = left, .right = right, .top = top + band_h - height * scale - 1, .scale = scale }; -} - -pub const State = struct { - kind: Kind = .off, - tick: ?u64 = null, - x: f32 = 0, - target: f32 = 0, - left: bool = false, - idle: u8 = 12, - frame: u8 = 0, - rng: std.Random.DefaultPrng = undefined, - - /// No lane (the tag's text has filled it) hides the pet but keeps - /// where it was and what it was doing. - pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { - const region = area orelse return null; - if (kind == .off) { - s.* = .{}; - return null; - } - const tick = now_ms / 100; - if (s.kind != kind or s.tick == null) { - s.* = .{ .kind = kind, .tick = tick, .x = region.left, .target = region.left, .rng = .init(now_ms) }; - } - s.x = std.math.clamp(s.x, region.left, region.right); - s.target = std.math.clamp(s.target, region.left, region.right); - // Coming back from suspension never launches the pet across the tag. - const steps = @min(tick -| s.tick.?, 2); - s.tick = tick; - for (0..steps) |_| { - s.frame +%= 1; - if (s.idle > 0) { - s.idle -= 1; - if (s.idle == 0) { - // Wander to a random spot of the lane; one too close - // would be a shuffle in place, so take the far end. - s.target = region.left + s.rng.random().float(f32) * (region.right - region.left); - if (@abs(s.target - s.x) < 8 * region.scale) - s.target = if (s.x - region.left > region.right - s.x) region.left else region.right; - s.left = s.target < s.x; - s.frame = 255; // the walk starts at frame 0 - } - continue; - } - // The cat walks steadily; the frog travels only while airborne. - const phase = s.frame % hop_ticks; - if (kind == .cat or (phase >= 2 and phase < 6)) { - const step = (if (kind == .cat) @as(f32, 1.8) else 2.6) * region.scale; - s.x = if (s.left) @max(s.target, s.x - step) else @min(s.target, s.x + step); - } - if (s.x == s.target and (kind == .cat or phase == hop_ticks - 1)) - s.idle = s.rng.random().intRangeAtMost(u8, 20, 60); - } - return .{ .x = @floor(s.x), .y = region.top, .scale = region.scale, .left = s.left, .walking = s.idle == 0, .frame = s.frame }; - } -}; - -const cat = [_][]const u8{ - " # # ", - " #####", - " ##o##", - " # ######", - " # ######## ", - " ######### ", - " ######## ", - " ## ## ", - " # # ", -}; -const frog = [_][]const u8{ - " ", - " ", - " ", - " ## ", - " #o## ", - " #########", - " ######### ", - " ##### ## ", - "###### ### ", -}; -const frog_leap = [_][]const u8{ - " ## ", - " #o## ", - " #######", - " ######## ", - " ####### ", - " ### ## ", - "## # ", - "# ", - " ", -}; - -/// 0 transparent, 1 theme ink, 2 eye cutout. Walk legs and idle blinks are -/// generated in this fixed 12x9 tile; neither can spill into an adjacent row. -pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { - if (x_in >= width or y >= height or kind == .off) return 0; - const x = if (pose.left) width - 1 - x_in else x_in; - const alternate = (pose.frame / 2) % 2 == 1; - // An idle companion still looks alive during its first pause: a slow - // two-pixel tail-tip flick, or the frog's throat gently inflating. These - // remain inside the tile and mirror with the rest of the animal. - const breathing = (pose.frame / 4) % 2 == 1; - if (!pose.walking and breathing) { - if (kind == .cat and y == 3 and x <= 1) - return @intFromBool(x == 0); - if (kind == .frog and ((y == 6 and x == 11) or (y == 7 and x == 10))) return 1; - } - if (kind == .cat and pose.walking and alternate and y >= 7) - return @intFromBool((y == 7 and (x == 3 or x == 7)) or (y == 8 and (x == 2 or x == 8))); - // A hopping frog leaps two rows low at take-off and one on the way down. - const phase = pose.frame % hop_ticks; - const leaping = kind == .frog and pose.walking and phase >= 2 and phase < 6; - const sink: usize = if (!leaping) 0 else if (phase == 2) 2 else if (phase == 5) 1 else 0; - if (y < sink) return 0; - const ch = (if (kind == .cat) cat else if (leaping) frog_leap else frog)[y - sink][x]; - return switch (ch) { - '#' => 1, - 'o' => if (!pose.walking and pose.frame % 30 >= 27) 1 else 2, - else => 0, - }; -} - -test "pet stays in trailing workspace blanks, and a lost lane hides it without a reset" { - try std.testing.expect(lane(20, 8, 200, 0, 16) == null); - try std.testing.expect(lane(3, 8, 200, 0, 10) == null); - const region = lane(3, 8, 200, 2, 20).?; - try std.testing.expect(region.left >= 5 * 8); - var state: State = .{}; - var moved = false; - var reversed = false; - for (0..2000) |i| { - const pose = state.sample(.cat, i * 100, region).?; - try std.testing.expect(pose.x >= region.left and pose.x + width * pose.scale <= 200 - 16); - try std.testing.expect(pose.y >= 2 and pose.y + height * pose.scale < 22); - moved = moved or pose.walking; - reversed = reversed or pose.left; - } - try std.testing.expect(moved and reversed); - const kept = state; - try std.testing.expect(state.sample(.cat, 300000, null) == null); - try std.testing.expectEqual(kept.x, state.x); - try std.testing.expectEqual(kept.tick, state.tick); - try std.testing.expect(state.sample(.off, 300100, region) == null); -} - -test "pet clock is fixed rate and sprites bounded in both directions" { - const region = lane(1, 8, 400, 0, 16).?; - var state: State = .{}; - const start = state.sample(.frog, 1000, region).?; - try std.testing.expectEqualDeep(start, state.sample(.frog, 1099, region).?); - for ([_]Kind{ .cat, .frog }) |kind| for ([_]bool{ false, true }) |left| { - const pose: Pose = .{ .x = 0, .y = 0, .scale = 1, .left = left, .walking = true, .frame = 3 }; - var count: usize = 0; - for (0..height) |y| for (0..width) |x| { - count += @intFromBool(pixel(kind, pose, x, y) != 0); - }; - try std.testing.expect(count > 20 and count <= width * height); - try std.testing.expectEqual(@as(u2, 0), pixel(kind, pose, width, height)); - }; -} - -test "pet rests at random spots and the frog travels only in the air" { - const region = lane(1, 8, 800, 0, 16).?; - var state: State = .{}; - var last = state.sample(.frog, 0, region).?; - var rested_midway = false; - for (1..3000) |i| { - const pose = state.sample(.frog, i * 100, region).?; - const phase = pose.frame % hop_ticks; - if (pose.x != last.x) try std.testing.expect(pose.walking and phase >= 2 and phase < 6); - rested_midway = rested_midway or (last.walking and !pose.walking and pose.x > region.left and pose.x < @floor(region.right)); - last = pose; - } - try std.testing.expect(rested_midway); -} - -test "pet initial idle visibly animates without walking or leaving its tile" { - const region = lane(1, 8, 400, 0, 16).?; - for ([_]Kind{ .cat, .frog }) |kind| { - var state: State = .{}; - const initial = state.sample(kind, 0, region).?; - var later = initial; - for (1..5) |tick| later = state.sample(kind, tick * 100, region).?; - try std.testing.expect(!initial.walking and !later.walking); - try std.testing.expectEqual(initial.x, later.x); - try std.testing.expectEqual(initial.y, later.y); - var changes: usize = 0; - for (0..height) |y| for (0..width) |x| { - changes += @intFromBool(pixel(kind, initial, x, y) != pixel(kind, later, x, y)); - }; - try std.testing.expectEqual(@as(usize, 2), changes); - try std.testing.expectEqual(@as(u2, 0), pixel(kind, later, width, height)); - } -} diff --git a/src/host_io.zig b/src/host_io.zig deleted file mode 100644 index cadcc1d2..00000000 --- a/src/host_io.zig +++ /dev/null @@ -1,4007 +0,0 @@ -const builtin = @import("builtin"); -const std = @import("std"); -const posix = std.posix; -/// libc: ptys, fork and exec, signals; and the leaf file calls (/proc, PATH, the prompt rc files), which run with no io: in a forked child, a signal handler, or for callers holding none. -const libc = std.c; -const pardes = @import("pardes.zig"); -const selection_pipe = @import("selection_pipe.zig"); -const ninep_io = @import("runtime").ninep_io; -const filesystem = @import("fs.zig"); -const file_watch = @import("file_watch.zig"); -const replica = @import("replica.zig"); -const daemon = @import("runtime").daemon; -const panes = @import("panes.zig"); - -pub const Host = struct { - ctx: ?*anyopaque = null, - vtable: *const VTable = &.{}, - - pub const VTable = struct { - wait_input: ?*const fn (ctx: ?*anyopaque, timeout_ms: u32) void = null, - /// The shell's monotonic clock in ns: the only time the core sees. - /// Without one, core animation moves only by `.tick` events. - now: ?*const fn (ctx: ?*anyopaque) u64 = null, - present: ?*const fn (ctx: ?*anyopaque, surface: *const pardes.Surface) void = null, - post_present: ?*const fn (ctx: ?*anyopaque) void = null, - poll_frame: ?*const fn (ctx: ?*anyopaque) void = null, - /// Whether anyone sees a frame drawn now. A detached session with no - /// client attached draws none (a /screen read draws its own), and - /// the frame owed is drawn when one attaches. Absent: always. - watched: ?*const fn (ctx: ?*anyopaque) bool = null, - /// Detach: the terminal or window let go, the session left running - /// for the daemon to attach again (daemon.zig). - detach: ?*const fn (ctx: ?*anyopaque) void = null, - /// Adopt: the shells a dead session left, asked of the daemon. - adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, - /// Upgrade: this process exec'd as the pardes installed since, at - /// the step's end (upgrade.zig); `pane` hears why if it cannot be. - upgrade: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, - /// Whether a newer pardes is installed at the path this process - /// started from, to be said once (upgrade.zig): asked at a focus-in. - newer_build: ?*const fn (ctx: ?*anyopaque) bool = null, - spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null, - pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null, - pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null, - pty_signal: ?*const fn (ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void = null, - close_pty: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, - tty_taken: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, - /// The name of the program holding the tty, when it is not the - /// shell (host_io.foregroundName), in `buf`. - fg_name: ?*const fn (ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 = null, - /// Answered at once, not queued as an effect: Kill asks while the - /// job it saw running is still the one in the tty (host_io.killJob). - kill_job: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, - write_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void = null, - write_dump: ?*const fn (ctx: ?*anyopaque, bytes: []const u8) void = null, - watch_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void = null, - watch_theme: ?*const fn (ctx: ?*anyopaque, generation: u32, on: bool) void = null, - dump_themes: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, - set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null, - read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null, - open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null, - /// A plumbing rule's program (Effect.start): every host's is - /// startDetached. Null once it runs, else why not. - start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null, - lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, - pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, - /// Start the streaming search of this generation on a worker - /// (pardes.Stream.start); absent, it runs on the loop. - search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null, - /// Carry the dump of handover `seq` to another window on a worker - /// (Handover.start), which answers through the inbox's `handed`. - hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null, - /// Run job `token` of the pane in slot `pane` (whose serial is - /// `serial`) on a worker (`KindJob`), answering with the `job` event; - /// absent, it runs on the loop. - job: ?*const fn (ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void = null, - }; -}; - -/// A kind's job (Effect.job), taken off its pane: its input, its kind's -/// `job_run` and generation; run on a worker (or here), its answer the -/// core's `job` event. Its library is held until it lands (Addon.holdJob). -/// A draw (api.draw, `draw`) is one of this process's alone: never an -/// event, its answer kept for the pane's next paint (Kind.landDraw). -pub const KindJob = struct { - gpa: std.mem.Allocator, - pane: u8, - serial: u32, - token: u32, - gen: u32, - ops: *const pardes.Kind.Ops, - in: []u8, - /// What the job allocates (`pa_out`), freed with it; `out` the last. - arena: std.heap.ArenaAllocator, - out: []u8 = &.{}, - id: u32 = 0, - /// A draw's: the core it was asked in. - draw: ?*const pardes.Pardes = null, - - pub fn take(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) ?*KindJob { - const pn = p.panes[pane] orelse return null; - const slot = pn.addon orelse return null; - const ops = slot.ops orelse return null; - if (pn.serial != serial or ops.job_run == null) return null; - const at = for (&slot.jobs) |*j| { - if (j.*) |job| if (job.token == token) break j; - } else return null; - const j = slot.gpa.create(KindJob) catch return null; - j.* = .{ .gpa = slot.gpa, .pane = pane, .serial = serial, .token = token, .gen = slot.gen, .ops = ops, .in = at.*.?.in, .arena = .init(slot.gpa) }; - at.* = null; - pardes.Addon.holdJob(ops, true); - return j; - } - - pub fn run(j: *KindJob) void { - const Out = struct { - fn alloc(out: [*c]pardes.Kind.c.pa_out, n: usize) callconv(.c) ?*anyopaque { - const job: *KindJob = @ptrCast(@alignCast(out.*.ctx)); - job.out = job.arena.allocator().alignedAlloc(u8, .@"16", n) catch &.{}; - return if (job.out.len == n) job.out.ptr else null; - } - }; - var out: pardes.Kind.c.pa_out = .{ .alloc = Out.alloc, .ctx = j }; - const n = j.ops.job_run.?(j.in.ptr, @intCast(j.in.len), &out); - j.out = j.out[0..@min(n, j.out.len)]; - } - - /// Its answer to the core, and it gone. - pub fn land(j: *KindJob, p: *pardes.Pardes) void { - if (j.draw != null) return pardes.Kind.landDraw(p, j); - p.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); - j.drop(); - } - - pub fn drop(j: *KindJob) void { - pardes.Addon.holdJob(j.ops, false); - j.gpa.free(j.in); - j.arena.deinit(); - j.gpa.destroy(j); - } - - /// On a worker of `io`, posting itself to `sink` done: a host's `job`. - pub fn start(io: std.Io, p: *pardes.Pardes, tasks: *selection_pipe.Tasks, pane: u8, serial: u32, token: u32, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) void { - const j = take(p, pane, serial, token) orelse return; - if (!go(io, tasks, j, ctx, sink)) here(j, p); - } - - /// `j` on a worker of `io`, posting itself to `sink` done; false when - /// none could take it. - pub fn go(io: std.Io, tasks: *selection_pipe.Tasks, j: *KindJob, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) bool { - next_id +%= 1; - j.id = next_id | 0x8000_0000; - const work = struct { - fn work(job: *KindJob, c: ?*anyopaque, s: *const fn (?*anyopaque, *KindJob) void) void { - job.run(); - s(c, job); - } - }.work; - if (tasks.full()) return false; - const future = io.concurrent(work, .{ j, ctx, sink }) catch return false; - _ = tasks.add(.{ .id = j.id, .future = future }); - return true; - } - - var next_id: u32 = 0; - - fn here(j: *KindJob, p: *pardes.Pardes) void { - j.run(); - j.land(p); - } - - /// No workers (a test, the fallback): it runs on the loop, at once. - pub fn runHere(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) void { - here(take(p, pane, serial, token) orelse return, p); - } -}; - -/// PARDES_TEST_CLOCK makes a shell's `Host.now` answer a virtual clock -/// instead of `std.Io.Clock.awake`, moved only when a timed wait runs out -- -/// straight to the core's next wake -- so the snapshot harness sees the same -/// frames whatever the machine's load. -pub fn testClock() ?u64 { - return if (libc.getenv("PARDES_TEST_CLOCK")) |v| (if (std.mem.span(v).len != 0) 0 else null) else null; -} - -/// The kitty images and syntax subsystems a frontend's session draws with, -/// on `allocs` (pardes.memory.init), and what kinds keep past a call (their -/// heap, `pa_api.heap`: the pdf addon's documents and pages). `stopWorkers` -/// is its defer. -pub fn startWorkers(allocs: pardes.memory.Allocators) void { - pardes.Term.start(allocs.image); - pardes.Kind.heap = allocs.addon; - pardes.syntax.start(allocs.tree_sitter); -} - -pub fn stopWorkers() void { - pardes.Term.stop(); - pardes.syntax.stop(); -} - -/// A Restore's new core, from the dump at `path` (core.takeRestore), or -/// null once why it is not is said. ponytail: a Restore replaces the core -/// its clients replicate; they are let go, and attach again. The old -/// core's panes and theme are no longer watched; the frontend lets go of -/// its ptys and pipes and swaps the new core in. ponytail: a restored -/// session is one view, the live one's (the tty's terminal, the window's -/// window): the others are let go, as a detach of each. -pub fn restoreCore(gpa: std.mem.Allocator, core: *pardes.Pardes, path: []const u8, peers: *replica.Peers, inotify_fd: c_int, watches: *file_watch.Table) ?*pardes.Pardes { - peers.dropAll(core); - const bytes = pardes.dump.restoreBytes(core, gpa, path) catch |err| { - core.reportError(core.view().active, "Restore", err); - return null; - }; - defer gpa.free(bytes); - const nc = pardes.dump.restore(core, bytes, path) catch |err| { - core.reportError(core.view().active, "Restore", err); - return null; - }; - file_watch.unwatchAll(inotify_fd, watches); - _ = file_watch.applyThemeEffect(core, gpa, inotify_fd, watches, 0, false); - return nc; -} - -/// A shell of a dead session the daemon handed this one (Adopt), and the -/// terminal pane made for it once there is one. -pub const Adoption = struct { pid: libc.pid_t, fd: c_int, pane: ?u8 }; - -/// The shells of dead sessions handed this one (Adopt), each waiting for -/// the spawn of the terminal pane made for it (`take`). -pub const Adoptions = struct { - list: [pardes.MAX_PANES]Adoption = undefined, - len: usize = 0, - /// Taken in since the last Adopt. - taken: usize = 0, - - /// Adopt: the daemon is asked for the shells of sessions that died - /// holding them; each comes back to `adoptShell`. - pub fn ask(a: *Adoptions, core: *pardes.Pardes, pane: u8) void { - if (!daemon.kept()) return core.reportFailure(pane, "Adopt: no pardes daemon is keeping shells for this session"); - a.taken = 0; - daemon.adopt(); - } - - /// One shell of a dead session (`pid` 0: the last of them was told): - /// a terminal pane made for it, as the Term word makes one, whose spawn - /// takes this pty instead of forking a shell (`take`). - pub fn adoptShell(a: *Adoptions, core: *pardes.Pardes, pid: libc.pid_t, fd: c_int) void { - if (pid == 0) { - var buf: pardes.Kind.Buf(96) = .{}; - return core.setMessage(core.view().active, if (a.taken == 0) "Adopt: no shell of a session that died is waiting" else buf.print("Adopt: {d} shell{s} taken in; what they showed is gone", .{ a.taken, if (a.taken == 1) "" else "s" })); - } - if (a.len < a.list.len) { - a.list[a.len] = .{ .pid = pid, .fd = fd, .pane = null }; - a.len += 1; - if (core.adoptShell()) |id| { - a.list[a.len - 1].pane = id; - a.taken += 1; - return; - } - a.len -= 1; - } - // No room for it: its master goes, and the shell with this session. - _ = libc.close(fd); - var buf: pardes.Kind.Buf(96) = .{}; - core.setMessage(core.view().active, buf.print("Adopt: no room for shell {d}; it ends with this session", .{pid})); - } - - /// The adopted shell pane `pane`'s spawn takes, off the list. - pub fn take(a: *Adoptions, pane: u8) ?Adoption { - for (a.list[0..a.len], 0..) |it, i| if (it.pane == pane) { - std.mem.copyForwards(Adoption, a.list[i .. a.len - 1], a.list[i + 1 .. a.len]); - a.len -= 1; - return it; - }; - return null; - } -}; - -pub const Fallback = struct { - pub const dump_path = "pardes.dump"; - - gpa: std.mem.Allocator, - files: std.StringHashMapUnmanaged([]u8) = .empty, - clipboard: std.ArrayListUnmanaged(u8) = .empty, - link: std.ArrayListUnmanaged(u8) = .empty, - /// The programs plumbing rules started, as Effect.start packs them, - /// one a line. - started: std.ArrayListUnmanaged(u8) = .empty, - spawned: [pardes.MAX_PANES]bool = @splat(false), - watched: [pardes.MAX_PANES]bool = @splat(false), - - pub fn deinit(f: *Fallback) void { - var it = f.files.iterator(); - while (it.next()) |entry| { - f.gpa.free(entry.key_ptr.*); - f.gpa.free(entry.value_ptr.*); - } - f.files.deinit(f.gpa); - f.clipboard.deinit(f.gpa); - f.link.deinit(f.gpa); - f.started.deinit(f.gpa); - } - - pub fn writeFile(f: *Fallback, path: []const u8, bytes: []const u8) bool { - const copy = f.gpa.dupe(u8, bytes) catch return false; - if (f.files.getEntry(path)) |entry| { - f.gpa.free(entry.value_ptr.*); - entry.value_ptr.* = copy; - return true; - } - const key = f.gpa.dupe(u8, path) catch { - f.gpa.free(copy); - return false; - }; - f.files.put(f.gpa, key, copy) catch { - f.gpa.free(key); - f.gpa.free(copy); - return false; - }; - return true; - } - - pub fn get(f: *const Fallback, path: []const u8) ?[]const u8 { - if (f.files.get(path)) |written| return written; - return filesystem.sourceBytes(path); - } - - pub fn setClipboard(f: *Fallback, text: []const u8) void { - f.clipboard.clearRetainingCapacity(); - f.clipboard.appendSlice(f.gpa, text) catch {}; - } - - pub fn setLink(f: *Fallback, url: []const u8) void { - f.link.clearRetainingCapacity(); - f.link.appendSlice(f.gpa, url) catch {}; - } - - pub fn start(f: *Fallback, line: []const u8) ?[]const u8 { - f.started.appendSlice(f.gpa, line) catch return "out of memory"; - f.started.append(f.gpa, '\n') catch return "out of memory"; - return null; - } -}; - -/// What a pixel host's loop takes from its workers, in order: each pane's -/// pty output (a reader waits while `output_capacity` is full, so output is -/// never dropped or reordered), its end of file, the language client's -/// answers and status and the `|` jobs' answers (those kept apart, so a -/// full output queue never holds them up), and file-watch news. Output and -/// end of file of a reader that was canceled or replaced, and an answer to -/// a language query since superseded, are dropped here. -pub const Inbox = struct { - pub const Msg = union(enum) { - output: struct { pane: u8, gen: u32, bytes: []u8 }, - eof: struct { pane: u8, gen: u32, failure: ?anyerror = null }, - lsp: struct { id: u32, rows: ?[]u8 }, - lsp_status: []u8, - pipe: selection_pipe.Response, - /// A streaming search's rows (pardes.Stream), of whatever generation: - /// the core drops a stale one. - search: pardes.Stream.Batch, - /// How a handover went (Handover.zig): `words` is where it went, or - /// why it did not; gpa-owned. - handed: struct { seq: u32, ok: bool, words: []u8 }, - /// A kind's job done on a worker (KindJob), never dropped. - kind_job: *KindJob, - files_changed, - fs_ready, - /// The daemon asks for the window again (`pardes-gui --attach`). - window, - /// A shell a dead session left, its pty's master (Adopt); pid 0 is - /// the last of them told. - adopted: struct { pid: libc.pid_t, fd: c_int }, - - pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void { - switch (m) { - .output => |o| gpa.free(o.bytes), - .lsp => |l| if (l.rows) |rows| lsp_allocator.free(rows), - .lsp_status => |t| lsp_allocator.free(t), - .pipe => |response_value| { - var response = response_value; - response.deinit(gpa); - }, - .search => |b| b.deinit(gpa), - .handed => |h| gpa.free(h.words), - .kind_job => |j| j.drop(), - .adopted => |a| if (a.fd >= 0) { - _ = libc.close(a.fd); - }, - .eof, .files_changed, .fs_ready, .window => {}, - } - } - }; - - pub const capacity = 512; - pub const output_capacity = capacity - pardes.MAX_PANES; - - pub const Batch = struct { - items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined, - len: usize = 0, - - pub fn slice(batch: *Batch) []Msg { - return batch.items[0..batch.len]; - } - }; - - gpa: std.mem.Allocator, - lsp_allocator: std.mem.Allocator, - /// The query in flight; the UI thread's alone (spawnLsp, teardown). - lsp_task: ?Lsp.Task = null, - /// Wakes the host's loop after a push from another thread: an SDL - /// event, a macOS runtime callback. Null: nobody to wake (tests). - wake_fn: ?*const fn (?*anyopaque) void = null, - wake_ctx: ?*anyopaque = null, - /// The process's Io: its terminal readers wait for space on `space`. - io: std.Io, - mutex: std.Io.Mutex = .init, - space: std.Io.Condition = .init, - items: [capacity]Msg = undefined, - head: usize = 0, - len: usize = 0, - closed: bool = false, - files_changed: bool = false, - readers: [pardes.MAX_PANES]?u32 = @splat(null), - waiting: usize = 0, - lsp_id: ?u32 = null, - completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined, - completion_len: usize = 0, - - pub fn lock(q: *Inbox) void { - q.mutex.lockUncancelable(q.io); - } - - pub fn unlock(q: *Inbox) void { - q.mutex.unlock(q.io); - } - - pub fn wake(q: *Inbox) void { - if (q.wake_fn) |f| f(q.wake_ctx); - } - - pub fn acceptReader(q: *Inbox, pane: u8, gen: u32) void { - q.lock(); - defer q.unlock(); - std.debug.assert(q.readers[pane] == null); - q.readers[pane] = gen; - } - - pub fn cancelReader(q: *Inbox, pane: u8, gen: u32) void { - q.lock(); - defer q.unlock(); - if (q.readers[pane] != gen) return; - q.readers[pane] = null; - var i: usize = 0; - while (i < q.len) { - const msg = q.items[(q.head + i) % q.items.len]; - const matches = switch (msg) { - .output => |o| o.pane == pane and o.gen == gen, - .eof => |e| e.pane == pane and e.gen == gen, - else => false, - }; - if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; - } - q.space.broadcast(q.io); - } - - pub fn pushOutput(q: *Inbox, pane: u8, gen: u32, bytes: []u8) bool { - q.lock(); - while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) { - q.waiting += 1; - q.space.waitUncancelable(q.io, &q.mutex); - q.waiting -= 1; - } - if (q.closed or q.readers[pane] != gen) { - q.unlock(); - q.gpa.free(bytes); - return false; - } - q.items[(q.head + q.len) % q.items.len] = .{ .output = .{ .pane = pane, .gen = gen, .bytes = bytes } }; - q.len += 1; - q.unlock(); - q.wake(); - return true; - } - - fn removeAt(q: *Inbox, offset: usize) Msg { - const removed = q.items[(q.head + offset) % q.items.len]; - var i = offset; - while (i + 1 < q.len) : (i += 1) - q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len]; - q.len -= 1; - return removed; - } - - pub fn discardLsp(q: *Inbox) void { - for (q.completions[0..q.completion_len], 0..) |msg, i| if (msg == .lsp) { - msg.deinit(q.gpa, q.lsp_allocator); - q.completion_len -= 1; - std.mem.copyForwards(Msg, q.completions[i..q.completion_len], q.completions[i + 1 .. q.completion_len + 1]); - return; - }; - } - - pub fn push(q: *Inbox, m: Msg) void { - if (m == .output) { - _ = q.pushOutput(m.output.pane, m.output.gen, m.output.bytes); - return; - } - q.lock(); - if (q.closed) { - q.unlock(); - m.deinit(q.gpa, q.lsp_allocator); - return; - } - switch (m) { - .files_changed => q.files_changed = true, - .lsp, .pipe, .kind_job => { - if (m == .lsp) { - if (q.lsp_id != m.lsp.id) { - q.unlock(); - m.deinit(q.gpa, q.lsp_allocator); - return; - } - q.discardLsp(); - } - std.debug.assert(q.completion_len < q.completions.len); - q.completions[q.completion_len] = m; - q.completion_len += 1; - }, - else => { - if (m == .eof) { - if (q.readers[m.eof.pane] != m.eof.gen) { - q.unlock(); - return; - } - std.debug.assert(q.len < q.items.len); - } else if (q.len >= output_capacity) { - q.unlock(); - m.deinit(q.gpa, q.lsp_allocator); - return; - } - q.items[(q.head + q.len) % q.items.len] = m; - q.len += 1; - }, - } - q.unlock(); - q.wake(); - } - - pub fn take(q: *Inbox) Batch { - var batch: Batch = .{}; - q.takeInto(&batch); - return batch; - } - - /// `take` into a batch the caller keeps: an idle wakeup copies nothing - /// (the batch is some 20 KB, and was built and returned by value each - /// time). - pub fn takeInto(q: *Inbox, batch: *Batch) void { - batch.len = 0; - q.lock(); - defer q.unlock(); - if (q.len == 0 and !q.files_changed and q.completion_len == 0) return; - while (q.len > 0) { - batch.items[batch.len] = q.items[q.head]; - batch.len += 1; - q.head = (q.head + 1) % q.items.len; - q.len -= 1; - } - q.head = 0; - if (q.files_changed) { - batch.items[batch.len] = .files_changed; - batch.len += 1; - q.files_changed = false; - } - @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]); - batch.len += q.completion_len; - q.completion_len = 0; - q.space.broadcast(q.io); - } - - pub fn discardCompletions(q: *Inbox) void { - q.lock(); - defer q.unlock(); - q.lsp_id = null; - for (q.completions[0..q.completion_len]) |msg| msg.deinit(q.gpa, q.lsp_allocator); - q.completion_len = 0; - } - - pub fn close(q: *Inbox) void { - q.lock(); - q.closed = true; - q.files_changed = false; - q.readers = @splat(null); - q.space.broadcast(q.io); - q.unlock(); - q.discardCompletions(); - q.lock(); - defer q.unlock(); - while (q.len > 0) { - const m = q.items[q.head]; - m.deinit(q.gpa, q.lsp_allocator); - q.head = (q.head + 1) % q.items.len; - q.len -= 1; - } - q.head = 0; - } - - pub fn deinit(q: *Inbox) void { - q.close(); - std.debug.assert(q.waiting == 0); - } - - /// A pane's reader: its pty's output pushed as it comes, then its end - /// of file; canceled (closePty), it pushes nothing more. - pub fn startReader(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) !std.Io.Future(void) { - q.acceptReader(pane, gen); - errdefer q.cancelReader(pane, gen); - return q.io.concurrent(readPty, .{ q, pty, pane, gen }); - } - - fn readPty(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) void { - var buf: [0x10000]u8 = undefined; - var failure: ?anyerror = null; - while (true) { - const n = pty.readStreaming(q.io, &.{&buf}) catch |err| switch (err) { - // A pty whose child has gone answers EIO: its end of file. - error.EndOfStream, error.InputOutput => break, - error.Canceled => return, - else => { - failure = err; - break; - }, - }; - if (n == 0) continue; - const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| { - failure = err; - break; - }; - if (!q.pushOutput(pane, gen, bytes)) return; - } - q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } }); - } - - /// Starts `e`, its answer let in and every older one's turned away. - pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void { - q.lock(); - q.lsp_id = e.id; - q.discardLsp(); - q.unlock(); - // The old query's waits are cancelation points: its join is short, and - // what it still delivers carries an id the queue now rejects. - Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows); - } - - fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); - q.push(.{ .lsp = .{ .id = id, .rows = rows } }); - } - - /// The language client's status line (lsp.setStatusSink). - pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { - const q: *Inbox = @ptrCast(@alignCast(ctx orelse return)); - const copy = q.lsp_allocator.dupe(u8, text) catch return; - q.push(.{ .lsp_status = copy }); - } - - /// A `|` job's answer (selection_pipe.start's sink). - pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void { - const q: *Inbox = @ptrCast(@alignCast(ctx.?)); - q.push(.{ .kind_job = j }); - } - - pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { - const q: *Inbox = @ptrCast(@alignCast(ctx.?)); - q.push(.{ .pipe = response }); - } - - /// A handover's end (Handover.Job.post). - pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void { - const q: *Inbox = @ptrCast(@alignCast(ctx.?)); - const copy = q.gpa.dupe(u8, words) catch return; - q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } }); - } - - /// A streaming search's batch (pardes.Stream.start's sink). Never - /// dropped for want of room, as output is not: the worker waits for - /// room, a wait its cancel ends (false: it stops). - pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { - const q: *Inbox = @ptrCast(@alignCast(ctx.?)); - q.lock(); - while (!q.closed and q.len >= output_capacity) { - q.waiting += 1; - q.space.wait(q.io, &q.mutex) catch { - q.waiting -= 1; - q.unlock(); - batch.deinit(q.gpa); - return false; - }; - q.waiting -= 1; - } - if (q.closed) { - q.unlock(); - batch.deinit(q.gpa); - return false; - } - q.items[(q.head + q.len) % q.items.len] = .{ .search = batch }; - q.len += 1; - q.unlock(); - q.wake(); - return true; - } - - /// A watched child exited (setExitWake): wake the loop, which takes it. - pub fn wakeForExit(ctx: ?*anyopaque) void { - const q: *Inbox = @ptrCast(@alignCast(ctx.?)); - q.wake(); - } -}; - -pub const Lsp = struct { - pub const Request = struct { - id: u32, - kind: pardes.lsp.Kind, - pane: u8, - offset: u32, - arg: []const u8, - }; - - pub const Task = struct { - id: u32, - future: std.Io.Future(void), - }; - - /// One language query, owned by the worker that runs it. - pub const Job = struct { - callstack_depth: u8 = pardes.lsp.callstack_default_depth, - dirty: bool = false, - id: u32, - kind: pardes.lsp.Kind, - offset: u32, - path: []u8, - source: [:0]u8, - arg: []u8, - root: []u8, - /// The other open files, for a query that can reach them. - others: []pardes.lsp.Doc = &.{}, - - pub fn free(job: *Job, gpa: std.mem.Allocator) void { - gpa.free(job.path); - gpa.free(job.source); - gpa.free(job.arg); - gpa.free(job.root); - for (job.others) |doc| { - gpa.free(doc.path); - gpa.free(doc.source); - } - gpa.free(job.others); - gpa.destroy(job); - } - }; - - // Copy before starting a worker; the editor may replace any source slice afterward. - pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job { - if (req.pane >= core.panes.len) return error.NoPane; - const pane = core.panes[req.pane] orelse return error.NoPane; - const file = pane.file; - const job = try gpa.create(Job); - errdefer gpa.destroy(job); - const declared_path = if (file) |f| f.path else ""; - const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); - errdefer gpa.free(path); - const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0); - errdefer gpa.free(source); - const arg = try gpa.dupe(u8, req.arg); - errdefer gpa.free(arg); - const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice(); - const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); - errdefer gpa.free(root); - job.* = .{ - .callstack_depth = core.settings.callstack_depth, - .dirty = pardes.tagline.dirty(pane), - .id = req.id, - .kind = req.kind, - .offset = req.offset, - .path = path, - .source = source, - .arg = arg, - .root = root, - }; - // ponytail: a copy of every open file per such query; a server - // already told of one is sent nothing more (syncDoc). - // Lspwhy too: the query it explains may be one of those, and its - // trace shows each file synced first. - if (pardes.lsp.reachesOtherFiles(req.kind) or req.kind == .explain) { - var others: std.ArrayList(pardes.lsp.Doc) = .empty; - errdefer { - for (others.items) |doc| { - gpa.free(doc.path); - gpa.free(doc.source); - } - others.deinit(gpa); - } - var copied: usize = 0; - for (core.panes, 0..) |slot, i| { - const other = slot orelse continue; - if (i == req.pane) continue; - const f = other.file orelse continue; - if (f.output != null) continue; - if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; - copied += f.content.len; - const local = filesystem.localPath(f.path) orelse continue; - const other_path = try gpa.dupe(u8, local); - const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { - gpa.free(other_path); - return err; - }; - try others.append(gpa, .{ .path = other_path, .source = other_source }); - } - job.others = try others.toOwnedSlice(gpa); - } - return job; - } - - // Null is failure; the receiver frees non-null rows with the job's allocator. - pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; - - /// Start `req` on a worker that hands its rows to `deliver`, the query - /// in `task` canceled first. One that cannot start is answered (no rows) - /// and reported here. - pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?Task, req: Request, ctx: ?*anyopaque, deliver: Deliver) void { - if (task.*) |*old| { - old.future.cancel(io); - task.* = null; - } - const job = snapshot(gpa, core, req) catch |err| { - core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return core.reportError(req.pane, "lsp", err); - }; - const future = io.concurrent(work, .{ io, gpa, job, ctx, deliver }) catch |err| { - job.free(gpa); - core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - return core.reportError(req.pane, "lsp", err); - }; - task.* = .{ .id = req.id, .future = future }; - } - - pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { - defer job.free(gpa); - // The query's memory is the fixed region memory.zig reserved at - // startup: a hard bound, reused by each query in turn. - const region = pardes.memory.takeLspQuery() orelse { - deliver(ctx, job.id, null); - return; - }; - var arena: std.heap.FixedBufferAllocator = .init(region); - defer pardes.memory.giveLspQuery(arena.end_index); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - pardes.lsp.query(io, arena.allocator(), .{ - .kind = job.kind, - .path = job.path, - .source = job.source, - .offset = job.offset, - .arg = job.arg, - .root = job.root, - .others = job.others, - .callstack_depth = job.callstack_depth, - .dirty = job.dirty, - .budget = &arena, - }, &out.writer) catch { - deliver(ctx, job.id, null); - return; - }; - const rows = out.toOwnedSlice() catch { - deliver(ctx, job.id, null); - return; - }; - deliver(ctx, job.id, rows); - } - - test "a snapshot owns every byte the backend will read" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - - core.settings.callstack_depth = 16; - var needle: [6]u8 = "needle".*; - const job = try snapshot(gpa, core, .{ - .id = 7, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = &needle, - }); - defer job.free(gpa); - - core.settings.callstack_depth = 2; - try std.testing.expectEqual(@as(u8, 16), job.callstack_depth); - try std.testing.expectEqual(@as(u32, 7), job.id); - try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind); - try std.testing.expectEqualStrings("needle", job.arg); - try std.testing.expect(job.arg.ptr != &needle); - try std.testing.expectEqualStrings("", job.path); - try std.testing.expectEqual(@as(usize, 0), job.source.len); - try std.testing.expectEqual(@as(u8, 0), job.source[0]); - const pane = core.panes[core.view().active].?; - try std.testing.expectEqualStrings(pane.cwdSlice(), job.root); - if (job.root.len > 0) try std.testing.expect(job.root.ptr != pane.cwdSlice().ptr); - } - - test "LSP snapshot frees every partially copied field on allocation failure" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - _ = try core.setTestFile("const copied = true;\n"); - const Snapshot = struct { - fn check(gpa: std.mem.Allocator, p: *const pardes.Pardes) !void { - const job = try snapshot(gpa, p, .{ - .id = 7, - .kind = .hover, - .pane = @intCast(p.view().active), - .offset = 6, - .arg = "query", - }); - defer job.free(gpa); - try std.testing.expectEqualStrings("const copied = true;\n", job.source); - } - }; - try std.testing.checkAllAllocationFailures(std.testing.allocator, Snapshot.check, .{core}); - } - - test "LSP snapshots translate explicit OS paths once and retain virtual names" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("const value = true;\n"); - for ([_]struct { path: []const u8, native: []const u8 }{ - .{ .path = "/n/os/project/file.zig", .native = "/project/file.zig" }, - .{ .path = "/n/os/n/os/project/file.zig", .native = "/n/os/project/file.zig" }, - .{ .path = "/virtual/src/file.zig", .native = "/virtual/src/file.zig" }, - }) |case| { - const replacement = try gpa.dupe(u8, case.path); - gpa.free(pane.file.?.path); - pane.file.?.path = replacement; - const job = try snapshot(gpa, core, .{ .id = 1, .kind = .hover, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); - defer job.free(gpa); - try std.testing.expectEqualStrings(case.native, job.path); - try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(case.native).?, job.root); - try std.testing.expectEqualStrings(case.path, pane.file.?.path); - } - } - - test "a pane that is gone yields no job rather than a null deref" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - - // The effect is drained after the core has moved on, so the pane it names - // may already have been deleted. Every shell open-coded this check. - const empty = for (core.panes, 0..) |slot, id| { - if (slot == null) break @as(u8, @intCast(id)); - } else return error.NoEmptyPane; - try std.testing.expectError(error.NoPane, snapshot(gpa, core, .{ - .id = 1, - .kind = .definition, - .pane = empty, - .offset = 0, - .arg = "", - })); - } - - test "work consumes the job and hands its rows to the sink" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - - const Sink = struct { - var seen_id: u32 = 0; - var seen_rows: ?[]u8 = null; - fn take(_: ?*anyopaque, id: u32, rows: ?[]u8) void { - seen_id = id; - seen_rows = rows; - } - }; - Sink.seen_id = 0; - Sink.seen_rows = null; - - const job = try snapshot(gpa, core, .{ - .id = 42, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = "", - }); - work(std.testing.io, gpa, job, null, Sink.take); - - // `status` is the one kind that answers with no file and no cursor, which - // is what makes it assertable here without a language server on the box. - try std.testing.expectEqual(@as(u32, 42), Sink.seen_id); - const rows = Sink.seen_rows orelse return error.SinkNeverCalled; - defer gpa.free(rows); - } - - test "LSP edit query failure leaves text and undo untouched before a successful retry" { - if (!pardes.lsp.supports.contains(.format)) return; - const Sink = struct { - core: *pardes.Pardes, - gpa: std.mem.Allocator, - calls: usize = 0, - failed: bool = false, - - fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const self: *@This() = @ptrCast(@alignCast(ctx.?)); - defer if (rows) |text| self.gpa.free(text); - self.calls += 1; - self.failed = rows == null; - self.core.update(.{ .lsp_resp = .{ .id = id, .rows = rows } }); - } - }; - const gpa = std.testing.allocator; - for ([_]pardes.lsp.Kind{ .format, .rename }) |kind| { - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("const value=1;\n"); - const path = try gpa.dupe(u8, "/file.zig"); - gpa.free(pane.file.?.path); - pane.file.?.path = path; - pane.body.cur_col = 6; - const revision = pane.file.?.revision; - const undo_len = pane.file.?.history.journal.done; - var failing = std.testing.FailingAllocator.init(gpa, .{}); - var sink: Sink = .{ .core = core, .gpa = failing.allocator() }; - for ([_]bool{ true, false }) |fail| { - failing.fail_index = std.math.maxInt(usize); - core.lspRequest(core.view().active, kind, "renamed"); - const job = try snapshot(failing.allocator(), core, .{ - .id = core.lsp_ask.wait.?.id, - .kind = kind, - .pane = @intCast(core.view().active), - .offset = 6, - .arg = "renamed", - }); - if (fail) failing.fail_index = failing.alloc_index; - work(std.testing.io, failing.allocator(), job, &sink, Sink.take); - try std.testing.expectEqual(fail, sink.failed); - try std.testing.expect(core.lsp_ask.wait == null); - if (fail) { - try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content); - try std.testing.expectEqual(revision, pane.file.?.revision); - try std.testing.expectEqual(undo_len, pane.file.?.history.journal.done); - } else { - try std.testing.expectEqualStrings(if (kind == .format) "const value = 1;\n" else "const renamed=1;\n", pane.file.?.content); - try std.testing.expectEqual(undo_len + 1, pane.file.?.history.journal.done); - } - } - try std.testing.expectEqual(@as(usize, 2), sink.calls); - } - } - - test "LSP work delivers failure when transferring result ownership cannot allocate" { - if (!pardes.lsp.supports.contains(.status)) return; - const TransferAllocator = struct { - failed: bool = false, - fail_copy: bool = false, - fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - if (self.fail_copy) { - self.failed = true; - return null; - } - return std.testing.allocator.rawAlloc(len, alignment, ra); - } - fn resize(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { - return std.testing.allocator.rawResize(bytes, alignment, len, ra); - } - fn remap(ctx: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - if (len < bytes.len) { - self.fail_copy = true; - return null; - } - return std.testing.allocator.rawRemap(bytes, alignment, len, ra); - } - fn free(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, ra: usize) void { - std.testing.allocator.rawFree(bytes, alignment, ra); - } - }; - const Sink = struct { - calls: usize = 0, - id: u32 = 0, - rows: ?[]u8 = null, - fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { - const self: *@This() = @ptrCast(@alignCast(ctx.?)); - self.calls += 1; - self.id = id; - self.rows = rows; - } - }; - var allocator: TransferAllocator = .{}; - const gpa: std.mem.Allocator = .{ .ptr = &allocator, .vtable = &.{ - .alloc = TransferAllocator.alloc, - .resize = TransferAllocator.resize, - .remap = TransferAllocator.remap, - .free = TransferAllocator.free, - } }; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); - var sink: Sink = .{}; - work(std.testing.io, gpa, job, &sink, Sink.take); - if (sink.rows) |rows| gpa.free(rows); - try std.testing.expect(allocator.failed); - try std.testing.expectEqual(@as(usize, 1), sink.calls); - try std.testing.expectEqual(@as(u32, 37), sink.id); - try std.testing.expect(sink.rows == null); - } -}; - -pub const Shell = struct { - const X_OK: c_int = 1; - - extern "c" fn mkstemp(template: [*:0]u8) c_int; - extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; - - const path_capacity = 4096; - const max_path_files = 64; - - // Repair only the system-only PATH inherited from a macOS GUI launch. - fn adoptSystemPath() void { - if (comptime builtin.os.tag != .macos) return; - var buf: [path_capacity]u8 = undefined; - var len: usize = 0; - collectSystemPath("/etc/paths", "/etc/paths.d", &buf, &len); - if (len == 0) return; - const system = buf[0..len]; - - const current: []const u8 = if (libc.getenv("PATH")) |p| std.mem.span(p) else ""; - if (!allEntriesWithin(current, system)) return; - if (std.mem.eql(u8, current, system)) return; - - var out: [path_capacity:0]u8 = undefined; - if (len >= out.len) return; - @memcpy(out[0..len], system); - out[len] = 0; - _ = setenv("PATH", out[0..len :0].ptr, 1); - } - - // Run in the parent before forking; children borrow the completed prompt files. - pub fn prepare() PromptFiles { - adoptSystemPath(); - if (comptime builtin.os.tag.isDarwin()) - _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1); - sweepDeadRcs(); - const rcs = PromptFiles.init(); - // A private file goes at a fatal signal too, not only at Exit. - for ([_]?[:0]const u8{ if (rcs.bash_owned) rcs.bashPath() else null, if (rcs.fish_owned) rcs.fishPath() else null }, 0..) |owned, i| { - const path = owned orelse continue; - @memcpy(fatal_rcs[i][0..path.len], path); - fatal_rcs[i][path.len] = 0; - fatal_rc_len[i] = path.len; - } - ninep_io.fatal_cleanup = unlinkOwnedRcs; - return rcs; - } - - /// This process's private prompt files, where a fatal signal's handler - /// can reach them (unlinkOwnedRcs). - var fatal_rcs: [2][rc_path_capacity:0]u8 = undefined; - var fatal_rc_len: [2]usize = .{ 0, 0 }; - - /// Removes this process's private prompt files. Async-signal-safe (two - /// unlinks): SIGTERM and SIGHUP call it before the signal's death. - pub fn unlinkOwnedRcs() void { - for (&fatal_rc_len, 0..) |*len, i| { - const n = len.*; - if (n == 0) continue; - len.* = 0; - _ = libc.unlink(fatal_rcs[i][0..n :0].ptr); - } - } - - /// Removes /tmp's `pardes-osc133---XXXXXX` files whose pid - /// is gone (kill(pid, 0) answers ESRCH): what a killed or crashed - /// editor left. A live pid's, one of another user's, or a name of - /// another shape is left alone. - fn sweepDeadRcs() void { - const dir = std.c.opendir("/tmp") orelse return; - defer _ = std.c.closedir(dir); - var dead: [64][64]u8 = undefined; - var dead_len: [64]usize = undefined; - var n: usize = 0; - while (std.c.readdir(dir)) |ent| { - const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); - const pid = rcPid(name) orelse continue; - // This pid's are this process's, but in an upgraded one: those - // were its old image's (upgrade.zig), and its own come after. - if (pid == std.c.getpid() and @import("runtime").upgrade.resumed == null) continue; - if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; - if (name.len >= 64 or n == dead.len) continue; - @memcpy(dead[n][0..name.len], name); - dead_len[n] = name.len; - n += 1; - } - for (dead[0..n], dead_len[0..n]) |*entry, len| { - var path_buf: [80:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&path_buf, "/tmp/{s}", .{entry[0..len]}, 0) catch continue; - const facts = ninep_io.statNoFollow(path) orelse continue; - if (facts.mode & 0o170000 != 0o100000 or facts.uid != libc.getuid()) continue; - _ = libc.unlink(path.ptr); - } - } - - /// The pid in `pardes-osc133---XXXXXX`, or null. - fn rcPid(name: []const u8) ?std.c.pid_t { - const head = "pardes-osc133-"; - if (!std.mem.startsWith(u8, name, head)) return null; - var fields = std.mem.splitScalar(u8, name[head.len..], '-'); - _ = fields.next() orelse return null; // the shell - const digits = fields.next() orelse return null; - const rest = fields.next() orelse return null; - if (fields.next() != null or rest.len != 6 or digits.len == 0 or digits.len > 10) return null; - for (digits) |c| if (!std.ascii.isDigit(c)) return null; - const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null; - return if (pid > 0) pid else null; - } - - fn collectSystemPath(paths_file: [:0]const u8, paths_dir: []const u8, buf: []u8, len: *usize) void { - var file_buf: [path_capacity]u8 = undefined; - if (readSmall(paths_file, &file_buf)) |body| appendLines(buf, len, body); - - const io = std.Io.Threaded.global_single_threaded.io(); - var dir = std.Io.Dir.cwd().openDir(io, paths_dir, .{ .iterate = true }) catch return; - defer dir.close(io); - - var names: [max_path_files][256]u8 = undefined; - var name_lens: [max_path_files]usize = undefined; - var count: usize = 0; - var it = dir.iterate(); - while (count < names.len) { - const entry = (it.next(io) catch break) orelse break; - if (entry.kind == .directory) continue; - if (entry.name.len == 0 or entry.name.len > names[count].len) continue; - @memcpy(names[count][0..entry.name.len], entry.name); - name_lens[count] = entry.name.len; - count += 1; - } - var order: [max_path_files]usize = undefined; - for (0..count) |i| order[i] = i; - std.mem.sort(usize, order[0..count], Names{ .names = &names, .lens = &name_lens }, Names.lessThan); - - var path_buf: [512]u8 = undefined; - for (order[0..count]) |i| { - const name = names[i][0..name_lens[i]]; - const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ paths_dir, name }, 0) catch continue; - if (readSmall(path, &file_buf)) |body| appendLines(buf, len, body); - } - } - - const Names = struct { - names: *const [max_path_files][256]u8, - lens: *const [max_path_files]usize, - - fn lessThan(self: Names, a: usize, b: usize) bool { - return std.mem.order(u8, self.names[a][0..self.lens[a]], self.names[b][0..self.lens[b]]) == .lt; - } - }; - - fn appendLines(buf: []u8, len: *usize, body: []const u8) void { - var lines = std.mem.splitScalar(u8, body, '\n'); - while (lines.next()) |raw| appendEntry(buf, len, std.mem.trim(u8, raw, " \t\r")); - } - - fn appendEntry(buf: []u8, len: *usize, entry: []const u8) void { - if (entry.len == 0) return; - if (hasEntry(buf[0..len.*], entry)) return; - const separator: usize = if (len.* == 0) 0 else 1; - if (len.* + separator + entry.len > buf.len) return; - if (separator == 1) { - buf[len.*] = ':'; - len.* += 1; - } - @memcpy(buf[len.*..][0..entry.len], entry); - len.* += entry.len; - } - - fn hasEntry(list: []const u8, entry: []const u8) bool { - var it = std.mem.tokenizeScalar(u8, list, ':'); - while (it.next()) |have| if (std.mem.eql(u8, have, entry)) return true; - return false; - } - - fn allEntriesWithin(candidate: []const u8, list: []const u8) bool { - var it = std.mem.tokenizeScalar(u8, candidate, ':'); - while (it.next()) |entry| if (!hasEntry(list, entry)) return false; - return true; - } - - fn readSmall(path: [:0]const u8, buf: []u8) ?[]const u8 { - const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); - if (fd < 0) return null; - defer _ = libc.close(fd); - var off: usize = 0; - while (off < buf.len) { - const n = libc.read(fd, buf[off..].ptr, buf.len - off); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - return null; - } - if (n == 0) break; - off += @intCast(n); - } - return buf[0..off]; - } - - test "the launchd PATH is replaced and a configured one is left alone" { - var buf: [256]u8 = undefined; - var len: usize = 0; - appendEntry(&buf, &len, "/usr/bin"); - appendEntry(&buf, &len, "/bin"); - appendEntry(&buf, &len, "/usr/bin"); // already there: dedup keeps the first - appendEntry(&buf, &len, ""); - try std.testing.expectEqualStrings("/usr/bin:/bin", buf[0..len]); - - try std.testing.expect(allEntriesWithin("/usr/bin:/bin", "/usr/bin:/bin:/sbin")); - try std.testing.expect(allEntriesWithin("", "/usr/bin")); - try std.testing.expect(!allEntriesWithin("/Users/x/.cargo/bin:/usr/bin", "/usr/bin:/bin")); - try std.testing.expect(!allEntriesWithin("/opt/homebrew/bin", "/usr/bin:/bin")); - } - - test "system path files are sorted and duplicate directories keep their first position" { - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths", .data = " /usr/bin \n/bin\n\n/usr/bin\n" }); - try tmp.dir.createDirPath(std.testing.io, "paths.d"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/20-last", .data = "/opt/local/bin\n/usr/bin\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/10-first", .data = "/opt/homebrew/bin\n/bin\n" }); - var root_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)]; - var file_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - const paths_file = try std.fmt.bufPrintSentinel(&file_buf, "{s}/paths", .{root}, 0); - var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - const paths_dir = try std.fmt.bufPrint(&dir_buf, "{s}/paths.d", .{root}); - var buf: [path_capacity]u8 = undefined; - var len: usize = 0; - collectSystemPath(paths_file, paths_dir, &buf, &len); - try std.testing.expectEqualStrings("/usr/bin:/bin:/opt/homebrew/bin:/opt/local/bin", buf[0..len]); - } - - const Family = enum { bash, fish, none }; - - fn family(bin: []const u8) Family { - const slash = std.mem.lastIndexOfScalar(u8, bin, '/'); - const base = if (slash) |s| bin[s + 1 ..] else bin; - if (std.mem.startsWith(u8, base, "bash")) return .bash; - if (std.mem.startsWith(u8, base, "fish")) return .fish; - return .none; - } - - /// `family`, for a shell whose name does not say it (a renamed copy, a - /// link named otherwise): what it really is, by the name its links end - /// at, else by the program itself -- bash's carries BASH_VERSINFO, fish's - /// fish_prompt. ponytail: a string scan of at most 16 MiB, once a spawn - /// and only for a name that says nothing; a --version probe would fork. - fn familyOf(path: [*:0]const u8) Family { - const named = family(std.mem.span(path)); - if (named != .none) return named; - // A name a POSIX shell answers to is that shell, whatever the file: - // bash run as `sh` is sh, and reads no --rcfile. - const bin = std.mem.span(path); - const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; - for ([_][]const u8{ "sh", "dash", "zsh", "ksh", "mksh", "yash", "nu", "elvish", "xonsh", "tcsh", "csh" }) |known| - if (std.mem.eql(u8, base, known)) return .none; - var real: [std.Io.Dir.max_path_bytes]u8 = undefined; - if (libc.realpath(path, &real)) |r| { - const by_link = family(std.mem.span(@as([*:0]const u8, @ptrCast(r)))); - if (by_link != .none) return by_link; - } - const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); - if (fd < 0) return .none; - defer _ = libc.close(fd); - var chunk: [64 * 1024]u8 = undefined; - var carry: usize = 0; - var total: usize = 0; - while (total < 16 << 20) { - const n = libc.read(fd, chunk[carry..].ptr, chunk.len - carry); - if (n <= 0) break; - const have = carry + @as(usize, @intCast(n)); - total += @intCast(n); - // A script is no binary: its interpreter is what runs. - if (total == have and std.mem.startsWith(u8, chunk[0..have], "#!")) return .none; - if (std.mem.indexOf(u8, chunk[0..have], "BASH_VERSINFO") != null) return .bash; - if (std.mem.indexOf(u8, chunk[0..have], "fish_prompt") != null) return .fish; - // Keep the tail, so a marker cut by the chunk is still seen. - carry = @min(have, 16); - std.mem.copyForwards(u8, chunk[0..carry], chunk[have - carry .. have]); - } - return .none; - } - - test "a bash under another name is still told as bash" { - const bash: [:0]const u8 = "/usr/bin/bash"; - if (libc.access(bash, X_OK) != 0) return; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, bash, std.testing.allocator, .limited(16 << 20)); - defer std.testing.allocator.free(bytes); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mysh", .data = bytes, .flags = .{ .permissions = .executable_file } }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var path: [4200:0]u8 = undefined; - const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0); - try std.testing.expectEqual(Family.bash, familyOf(p.ptr)); - try std.testing.expectEqual(Family.none, familyOf("/bin/sh")); - } - - const bash_rc = - \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc" - \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]' - \\PS2='\[\e]133;A;k=c;aid=pardes\a\]'"$PS2"'\[\e]133;B;aid=pardes\a\]' - \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}" - \\if ((BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 404)); then - \\ PS0='\e]133;C;aid=pardes\a'"$PS0" - \\else - \\ trap 'printf "\e]133;C;aid=pardes\a"' DEBUG - \\fi - \\ - ; - - // fish -C runs after config.fish; bash --rcfile must source .bashrc itself. - const fish_rc = - \\functions -c fish_prompt __pardes_user_prompt - \\function fish_prompt - \\ printf '\e]133;A;cl=line;aid=pardes\a' - \\ __pardes_user_prompt - \\ printf '\e]133;B;aid=pardes\a' - \\end - \\function __pardes_preexec --on-event fish_preexec - \\ printf '\e]133;C;aid=pardes\a' - \\end - \\function __pardes_postexec --on-event fish_postexec - \\ printf '\e]133;D;%s;aid=pardes\a' $status - \\end - \\ - ; - - const rc_path_capacity = 256; - - /// The prompt files a shell sources at start. Under $XDG_RUNTIME_DIR - /// (private to the user) there is one file per content, named by its - /// hash and shared by every pardes, so none is left behind by a pardes - /// that was killed: 72K of them piled up in /tmp when each host wrote - /// its own. Without that directory each host writes private mkstemp - /// files in /tmp and removes them at teardown, as before. - pub const PromptFiles = struct { - bash_path: [rc_path_capacity:0]u8 = @splat(0), - bash_len: u16 = 0, - bash_owned: bool = false, - fish_path: [rc_path_capacity:0]u8 = @splat(0), - fish_len: u16 = 0, - fish_owned: bool = false, - fish_command: [rc_path_capacity + "source ''".len:0]u8 = @splat(0), - fish_command_len: u16 = 0, - - pub fn init() PromptFiles { - var rcs: PromptFiles = .{}; - const bash = place(&rcs.bash_path, "bash", bash_rc); - rcs.bash_len = bash.len; - rcs.bash_owned = bash.owned; - const fish = place(&rcs.fish_path, "fish", fish_rc); - rcs.fish_len = fish.len; - rcs.fish_owned = fish.owned; - if (rcs.fishPath()) |path| { - // Quoted for fish; a path a quote would break is not used. - const command = if (std.mem.indexOfAny(u8, path, "'\\") != null) - error.NoSpaceLeft - else - std.fmt.bufPrintSentinel(&rcs.fish_command, "source '{s}'", .{path}, 0); - const ok = command catch { - if (rcs.fish_owned) _ = libc.unlink(path.ptr); - rcs.fish_len = 0; - return rcs; - }; - rcs.fish_command_len = @intCast(ok.len); - } - return rcs; - } - - pub fn deinit(rcs: *PromptFiles) void { - // Removed here, not again by a signal's handler. - for (&fatal_rc_len, 0..) |*len, i| for ([_]?[:0]const u8{ rcs.bashPath(), rcs.fishPath() }) |mine| { - if (mine) |path| if (len.* == path.len and std.mem.eql(u8, fatal_rcs[i][0..len.*], path)) { - len.* = 0; - }; - }; - if (rcs.bashPath()) |path| if (rcs.bash_owned) { - _ = libc.unlink(path.ptr); - }; - if (rcs.fishPath()) |path| if (rcs.fish_owned) { - _ = libc.unlink(path.ptr); - }; - rcs.bash_len = 0; - rcs.fish_len = 0; - rcs.fish_command_len = 0; - } - - fn bashPath(rcs: *const PromptFiles) ?[:0]const u8 { - if (rcs.bash_len == 0) return null; - return rcs.bash_path[0..rcs.bash_len :0]; - } - - fn fishPath(rcs: *const PromptFiles) ?[:0]const u8 { - if (rcs.fish_len == 0) return null; - return rcs.fish_path[0..rcs.fish_len :0]; - } - - fn fishCommand(rcs: *const PromptFiles) ?[:0]const u8 { - if (rcs.fish_command_len == 0) return null; - return rcs.fish_command[0..rcs.fish_command_len :0]; - } - }; - - /// The shared file for `contents` under $XDG_RUNTIME_DIR, written - /// beside it and renamed into place when missing or different, so a - /// shell never reads half of one; failing that, a private /tmp file. - fn place(path_buf: *[rc_path_capacity:0]u8, name: []const u8, contents: []const u8) struct { len: u16, owned: bool } { - shared: { - const dir = std.mem.span(std.c.getenv("XDG_RUNTIME_DIR") orelse break :shared); - if (dir.len == 0 or dir[0] != '/') break :shared; - const final = std.fmt.bufPrintSentinel(path_buf, "{s}/pardes-osc133-{s}-{x:0>16}", .{ dir, name, std.hash.Wyhash.hash(0, contents) }, 0) catch break :shared; - var have: [2048]u8 = undefined; - if (readSmall(final, &have)) |got| if (std.mem.eql(u8, got, contents)) return .{ .len = @intCast(final.len), .owned = false }; - var tmp_buf: [rc_path_capacity:0]u8 = @splat(0); - var template_buf: [rc_path_capacity]u8 = undefined; - const tmp_template = std.fmt.bufPrint(&template_buf, "{s}.XXXXXX", .{final}) catch break :shared; - const n = stage(&tmp_buf, tmp_template, contents); - if (n == 0) break :shared; - if (libc.rename(tmp_buf[0..n :0].ptr, final.ptr) != 0) { - _ = libc.unlink(tmp_buf[0..n :0].ptr); - break :shared; - } - return .{ .len = @intCast(final.len), .owned = false }; - } - var tmp_template: [64]u8 = undefined; - // Its pid in the name: one a killed editor left is swept by the - // next (sweepDeadRcs). - const template = std.fmt.bufPrint(&tmp_template, "/tmp/pardes-osc133-{s}-{d}-XXXXXX", .{ name, @as(u32, @intCast(std.c.getpid())) }) catch return .{ .len = 0, .owned = false }; - return .{ .len = stage(path_buf, template, contents), .owned = true }; - } - - // Publish a path only after its private 0600 file is fully written and closed. - fn stage(path_buf: *[rc_path_capacity:0]u8, template: []const u8, contents: []const u8) u16 { - const path = std.fmt.bufPrintSentinel(path_buf, "{s}", .{template}, 0) catch return 0; - const fd = mkstemp(path.ptr); - if (fd < 0) return 0; - if (!writeFd(fd, contents)) { - _ = libc.close(fd); - _ = libc.unlink(path.ptr); - return 0; - } - if (libc.close(fd) != 0) { - _ = libc.unlink(path.ptr); - return 0; - } - return @intCast(path.len); - } - - test "shell family is the basename's prefix, and anything else runs unadorned" { - try std.testing.expectEqual(Family.fish, family("fish")); - try std.testing.expectEqual(Family.fish, family("/usr/bin/fish")); - try std.testing.expectEqual(Family.fish, family("/opt/homebrew/bin/fish")); - try std.testing.expectEqual(Family.bash, family("bash")); - try std.testing.expectEqual(Family.bash, family("/bin/bash")); - try std.testing.expectEqual(Family.bash, family("/usr/bin/bash-5.2")); - try std.testing.expectEqual(Family.fish, family("/usr/local/bin/fish-3.7")); - try std.testing.expectEqual(Family.none, family("/opt/fish/bin/nu")); - try std.testing.expectEqual(Family.none, family("/usr/bin/zsh")); - try std.testing.expectEqual(Family.none, family("/bin/sh")); - try std.testing.expectEqual(Family.none, family("nu")); - try std.testing.expectEqual(Family.none, family("")); - } - - const bin_dirs = [_][]const u8{ - "/usr/bin/", - "/bin/", - "/usr/local/bin/", - "/opt/homebrew/bin/", - "/opt/local/bin/", - "/usr/sbin/", - }; - - const fallbacks = [_][]const u8{ - if (builtin.os.tag == .linux) "/usr/bin/bash" else "/bin/bash", - "/bin/sh", - }; - - pub const Spawn = struct { - path: [*:0]const u8, - argv: [6:null]?[*:0]const u8, - }; - - // Resolve in the parent. The path buffer and prompt files must survive through exec. - pub fn resolve(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8, prompt_rcs: *const PromptFiles) Spawn { - const path = find(bin, buf) orelse fallback(buf); - const marks: [2]?[*:0]const u8 = switch (familyOf(path)) { - .bash => if (prompt_rcs.bashPath()) |rc| .{ "--rcfile", rc.ptr } else .{ null, null }, - .fish => if (prompt_rcs.fishCommand()) |command| .{ "-C", command.ptr } else .{ null, null }, - .none => .{ null, null }, - }; - return .{ .path = path, .argv = .{ path, marks[0], marks[1], null, null, null } }; - } - - /// A command pane's shell runs its one line with job control on, so a - /// job the line puts in the background has a process group of its own. - /// The shell leads the terminal's session, and when it exits the kernel - /// hangs up the terminal's foreground group: with job control off that - /// is the shell's own, the job's too, and the job died with the command - /// (nohup'd or not; only setsid got out, and not always in time). A - /// shell pardes does not know runs the line as it is. - pub fn commandArgv(path: [*:0]const u8, line: [*:0]const u8) [6:null]?[*:0]const u8 { - const bin = std.mem.span(path); - const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; - const posix_shells = [_][]const u8{ "bash", "sh", "dash", "zsh", "ksh", "mksh", "yash" }; - for (posix_shells) |name| if (std.mem.eql(u8, base, name)) - return .{ path, "-m", "-c", line, null, null }; - if (family(bin) == .fish) return .{ path, "-C", "status job-control full", "-c", line, null }; - return .{ path, "-c", line, null, null, null }; - } - - /// A shell by its path or its name in the usual directories, or null. - /// A path may be under a mount this editor serves: the turn goes out - /// with the lookups (pardes.Turn.yield). - pub fn find(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[*:0]const u8 { - if (bin.len == 0 or bin.len + 1 > buf.len) return null; - pardes.turn.yield(); - defer pardes.turn.back(); - if (std.mem.indexOfScalar(u8, bin, '/') != null) { - @memcpy(buf[0..bin.len], bin); - buf[bin.len] = 0; - const p: [*:0]const u8 = @ptrCast(buf); - return if (libc.access(p, X_OK) == 0 and !isDirectory(p)) p else null; - } - for (bin_dirs) |dir| { - if (dir.len + bin.len + 1 > buf.len) continue; - @memcpy(buf[0..dir.len], dir); - @memcpy(buf[dir.len..][0..bin.len], bin); - buf[dir.len + bin.len] = 0; - const p: [*:0]const u8 = @ptrCast(buf); - if (libc.access(p, X_OK) == 0) return p; - } - return null; - } - - /// A directory passes access(X_OK) (it can be searched): no shell. - pub fn isDirectory(path: [*:0]const u8) bool { - const d = libc.opendir(path) orelse return false; - _ = libc.closedir(d); - return true; - } - - /// 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.Io.Dir.max_path_bytes]u8 = undefined; - if (find(bin, &buf)) |found| { - // A script whose `#!` names a program that is not there: its - // exec fails ENOENT as a missing shell's does, so told apart. - var interp: [256]u8 = undefined; - const missing = missingInterpreter(found, &interp) orelse return null; - return std.fmt.bufPrint(said, "interpreter {s} not found", .{missing}) catch "interpreter not found"; - } - if (std.mem.indexOfScalar(u8, bin, '/') != null and bin.len < buf.len) { - @memcpy(buf[0..bin.len], bin); - buf[bin.len] = 0; - if (isDirectory(@ptrCast(&buf))) return std.fmt.bufPrint(said, "not a shell: {s} is a directory", .{bin}) catch "not a shell: a directory"; - // There, but no program: said so, not "not found". - if (libc.access(@ptrCast(&buf), 0) == 0) return std.fmt.bufPrint(said, "not a shell: {s} is not executable", .{bin}) catch "not a shell: not executable"; - } - // "not found": the words a mount reads as ENOENT. - return std.fmt.bufPrint(said, "shell \"{s}\" not found (a name on the usual paths, or a path to one)", .{bin}) catch "no such shell"; - } - - /// The program a script's `#!` line names, when it is not there to - /// run; null for a script whose interpreter is there, or no script. - pub fn missingInterpreter(path: [*:0]const u8, out: []u8) ?[]const u8 { - pardes.turn.yield(); - defer pardes.turn.back(); - const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); - if (fd < 0) return null; - defer _ = libc.close(fd); - var head: [256]u8 = undefined; - const n = libc.read(fd, &head, head.len); - if (n < 2) return null; - const got = head[0..@intCast(n)]; - if (!std.mem.startsWith(u8, got, "#!")) return null; - const line = got[2 .. std.mem.indexOfScalar(u8, got, '\n') orelse got.len]; - var words = std.mem.tokenizeAny(u8, line, " \t\r"); - const interp = words.next() orelse return null; - if (interp.len + 1 > out.len) return null; - @memcpy(out[0..interp.len], interp); - out[interp.len] = 0; - if (libc.access(@ptrCast(out.ptr), X_OK) == 0) return null; - return out[0..interp.len]; - } - - test "a script whose #! names a program not there is told apart from a missing shell" { - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp -x\n", .flags = .{ .permissions = .executable_file } }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "good", .data = "#!/bin/sh\n", .flags = .{ .permissions = .executable_file } }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var path: [4200]u8 = undefined; - var said: [320]u8 = undefined; - try std.testing.expectEqualStrings("interpreter /no/such/interp not found", refusal(try std.fmt.bufPrint(&path, "{s}/bad", .{dir}), &said).?); - try std.testing.expect(refusal(try std.fmt.bufPrint(&path, "{s}/good", .{dir}), &said) == null); - try std.testing.expect(std.mem.startsWith(u8, refusal(try std.fmt.bufPrint(&path, "{s}/none", .{dir}), &said).?, "shell \"")); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain", .data = "echo\n" }); - const plain = try std.fmt.bufPrint(&path, "{s}/plain", .{dir}); - try std.testing.expect(std.mem.endsWith(u8, refusal(plain, &said).?, "plain is not executable")); - } - - fn fallback(buf: *[std.Io.Dir.max_path_bytes]u8) [*:0]const u8 { - for (fallbacks) |f| { - @memcpy(buf[0..f.len], f); - buf[f.len] = 0; - const p: [*:0]const u8 = @ptrCast(buf); - if (libc.access(p, X_OK) == 0) return p; - } - return @ptrCast(buf); - } - - test "a command pane's line runs with job control on in the shells that have it" { - const want = struct { - fn check(path: [*:0]const u8, words: []const []const u8) !void { - const argv = commandArgv(path, "sleep 9 &"); - for (words, 0..) |w, i| try std.testing.expectEqualStrings(w, std.mem.span(argv[i].?)); - try std.testing.expect(argv[words.len] == null); - } - }; - try want.check("/usr/bin/bash", &.{ "/usr/bin/bash", "-m", "-c", "sleep 9 &" }); - try want.check("/bin/sh", &.{ "/bin/sh", "-m", "-c", "sleep 9 &" }); - try want.check("/usr/bin/fish", &.{ "/usr/bin/fish", "-C", "status job-control full", "-c", "sleep 9 &" }); - try want.check("/usr/bin/nu", &.{ "/usr/bin/nu", "-c", "sleep 9 &" }); - } - - test "a path is taken at its word, a name is looked up, and both pick their own marks" { - if (builtin.os.tag == .windows) return; - var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - var prompt_rcs = PromptFiles.init(); - defer prompt_rcs.deinit(); - - const sh = resolve("/bin/sh", &buf, &prompt_rcs); - try std.testing.expectEqualStrings("/bin/sh", std.mem.span(sh.path)); - try std.testing.expect(sh.argv[1] == null); - - const bash = resolve("bash", &buf, &prompt_rcs); - try std.testing.expect(family(std.mem.span(bash.path)) == .bash); - try std.testing.expectEqualStrings("--rcfile", std.mem.span(bash.argv[1].?)); - try std.testing.expectEqualStrings(prompt_rcs.bashPath().?, std.mem.span(bash.argv[2].?)); - - const missing = resolve("zznosuchshell", &buf, &prompt_rcs); - try std.testing.expect(!std.mem.eql(u8, "zznosuchshell", std.mem.span(missing.path))); - try std.testing.expect(libc.access(missing.path, X_OK) == 0); - - const gone = resolve("/zz/no/such/shell", &buf, &prompt_rcs); - try std.testing.expect(libc.access(gone.path, X_OK) == 0); - } - - test "a private prompt file names its pid, and a dead pid's is swept while a live one's stays" { - if (builtin.os.tag == .windows) return; - const dead = "/tmp/pardes-osc133-bash-2147483647-AbCdEf"; - var live_buf: [80:0]u8 = undefined; - const live = try std.fmt.bufPrintSentinel(&live_buf, "/tmp/pardes-osc133-bash-{d}-AbCdEf", .{@as(u32, @intCast(std.c.getppid()))}, 0); - defer for ([_][:0]const u8{ dead, live }) |path| { - _ = libc.unlink(path.ptr); - }; - for ([_][:0]const u8{ dead, live }) |path| { - const fd = libc.open(path, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600)); - if (fd < 0) return error.SkipZigTest; - _ = libc.close(fd); - } - sweepDeadRcs(); - try std.testing.expect(libc.access(dead, 0) < 0); - try std.testing.expect(libc.access(live, 0) == 0); - // The pid is read only from that shape: an older name has none. - try std.testing.expectEqual(@as(?std.c.pid_t, 42), rcPid("pardes-osc133-fish-42-Xy12Zq")); - try std.testing.expectEqual(@as(?std.c.pid_t, null), rcPid("pardes-osc133-bash-01z3XK")); - } - - test "prompt files are one per content under the runtime dir, or private and cleaned up without it" { - if (builtin.os.tag == .windows) return; - var saved_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); - const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; - defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); - - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var dir_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); - const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf); - _ = setenv("XDG_RUNTIME_DIR", dir_buf[0..dir_len :0].ptr, 1); - - // Shared: the same file for every owner, left in place, rewritten - // whole when what is there is not its content. - var a = PromptFiles.init(); - var b = PromptFiles.init(); - const a_bash = a.bashPath() orelse return error.TempCreateFailed; - try std.testing.expectEqualStrings(a_bash, b.bashPath().?); - try std.testing.expect(std.mem.startsWith(u8, a_bash, dir_buf[0..dir_len])); - const fish_command = a.fishCommand() orelse return error.MissingFishCommand; - var want: [rc_path_capacity + 16]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "source '{s}'", .{a.fishPath().?}), fish_command); - var buf: [2048]u8 = undefined; - try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed); - try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed); - const stat = try @import("fs.zig").statPath(std.testing.io, a_bash, .{}); - try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077); - var kept: [rc_path_capacity:0]u8 = @splat(0); - @memcpy(kept[0..a_bash.len], a_bash); - a.deinit(); - b.deinit(); - try std.testing.expect(libc.access(&kept, 0) == 0); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = std.Io.Dir.path.basename(kept[0..a_bash.len]), .data = "half" }); - var c = PromptFiles.init(); - defer c.deinit(); - try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); - - // No runtime dir: private files, one per owner, gone at teardown. - _ = testUnsetenv("XDG_RUNTIME_DIR"); - var d = PromptFiles.init(); - var e = PromptFiles.init(); - defer e.deinit(); - const d_bash = d.bashPath() orelse return error.TempCreateFailed; - try std.testing.expect(!std.mem.eql(u8, d_bash, e.bashPath().?)); - try std.testing.expect(std.mem.startsWith(u8, d_bash, "/tmp/pardes-osc133-bash-")); - try std.testing.expectEqual(@as(?std.c.pid_t, std.c.getpid()), rcPid(std.Io.Dir.path.basename(d_bash))); - @memcpy(kept[0..d_bash.len], d_bash); - kept[d_bash.len] = 0; - d.deinit(); - try std.testing.expect(libc.access(&kept, 0) < 0); - } -}; - -/// In a child between fork and exec: every signal back to its default and -/// none blocked, whatever this process ignores or blocks (the tty's SIGWINCH, -/// a SIGHUP nohup ignored). A handler resets at exec by itself; an ignored -/// signal and the mask do not. Async-signal-safe: sigaction and sigprocmask. -pub fn resetChildSignals() void { - const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; - var sig: u8 = 1; - while (sig < 65) : (sig += 1) { - if (sig == @backingInt(posix.SIG.KILL) or sig == @backingInt(posix.SIG.STOP)) continue; - _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); - } - const none = posix.sigemptyset(); - posix.sigprocmask(posix.SIG.SETMASK, &none, null); -} - -extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int; -extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn chdir(path: [*:0]const u8) c_int; -extern "c" fn _exit(status: c_int) noreturn; - -pub const Child = struct { - file: std.Io.File, - pid: posix.pid_t, -}; - -/// The environment a pty child is handed: everything this process carries, -/// with the terminal's own identity written over whatever the launcher left -/// behind. The child is talking to the bundled VT, never to the terminal -/// pardes itself was started from, and a macOS `.app` launch supplies no -/// `TERM` at all — which is exactly why `clear` fails there, why nothing -/// paints a colour, and why every cursor-addressing program falls back to a -/// dumb line-at-a-time mode. -pub const ChildEnv = struct { - /// Entries pardes owns. The name of each is read back out of its own - /// spelling, so there is one place to edit and no second list to drift. - const own = [_][*:0]const u8{ - "TERM=" ++ pardes.config.child_term, - "COLORTERM=" ++ pardes.config.child_colorterm, - "TERM_PROGRAM=" ++ pardes.config.child_term_program, - }; - - /// What this editor tells its children of itself (exportEnv, `$winid`), - /// kept here rather than set into this process's environment: std's Io read - /// that block at startup, and setenv/unsetenv rewrite it in place under it - /// (a spawn then scans a null inside it). `build` puts each exported one in - /// place of an inherited variable of its name; a cleared one hides it; one - /// never exported is inherited as it is. - pub const exported_names = [_][]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "winid" }; - var exported_state: [exported_names.len]enum { inherited, cleared, set } = @splat(.inherited); - var exported_line: [exported_names.len][pardes.memory.limits.host_path_cap + 64:0]u8 = undefined; - - /// Set (or, null, clear) what children are told for `var_name`. - pub fn exportVar(var_name: []const u8, value: ?[]const u8) void { - const i = exportedIndex(var_name).?; - const v = value orelse { - exported_state[i] = .cleared; - return; - }; - _ = std.fmt.bufPrintSentinel(&exported_line[i], "{s}={s}", .{ var_name, v }, 0) catch { - exported_state[i] = .cleared; - return; - }; - exported_state[i] = .set; - } - - /// What children are told for `var_name`, as `exportVar` left it; null - /// when cleared or never exported. - pub fn exported(var_name: []const u8) ?[]const u8 { - const i = exportedIndex(var_name) orelse return null; - if (exported_state[i] != .set) return null; - return std.mem.span(@as([*:0]const u8, &exported_line[i]))[var_name.len + 1 ..]; - } - - fn exportedIndex(var_name: []const u8) ?usize { - for (exported_names, 0..) |n, i| if (std.mem.eql(u8, n, var_name)) return i; - return null; - } - - /// Wide enough for any real environment; `build` answers null rather than - /// truncate, because a child missing half its variables is a worse bug - /// than one missing TERM, and the caller then execs with `environ` intact. - pub const Slots = [1024]?[*:0]const u8; - - fn name(entry: [*:0]const u8) []const u8 { - const line = std.mem.span(entry); - return line[0 .. std.mem.indexOfScalar(u8, line, '=') orelse line.len]; - } - - /// Which pager a child is given where the user's environment names none: - /// a command pane's one-shot shell `cat` (its output is a pane already), - /// a terminal's shell `pardes -` (a +Pager pane). - pub const Paging = enum { command, terminal }; - - pub fn build(slots: *Slots, paging: Paging) ?[*:null]const ?[*:0]const u8 { - var n: usize = 0; - var i: usize = 0; - while (libc.environ[i]) |entry| : (i += 1) { - const inherited = name(entry); - const shadowed = for (own) |mine| { - if (std.mem.eql(u8, inherited, name(mine))) break true; - } else false; - if (shadowed) continue; - if (exportedIndex(inherited)) |e| if (exported_state[e] != .inherited) continue; - if (n + own.len + exported_names.len + 1 > slots.len) return null; - slots[n] = entry; - n += 1; - } - // No pager to wait in (less holds a run at its first screen for - // ever): a command pane's output is read whole, through cat; a - // terminal's goes to a +Pager pane. Only where the inherited - // environment chose none. - const defaults: []const [*:0]const u8 = switch (paging) { - .command => &cat_pagers, - .terminal => pardesPagers(), - }; - for (defaults) |default| { - const set = for (libc.environ[0..i]) |entry| { - if (std.mem.eql(u8, name(entry.?), name(default))) break true; - } else false; - if (set) continue; - if (n + own.len + exported_names.len + 4 > slots.len) return null; - slots[n] = default; - n += 1; - } - for (&exported_line, exported_state) |*line, state| if (state == .set) { - slots[n] = line; - n += 1; - }; - for (own) |mine| { - slots[n] = mine; - n += 1; - } - slots[n] = null; - return @ptrCast(slots); - } - - const cat_pagers = [_][*:0]const u8{ "PAGER=cat", "GIT_PAGER=cat" }; - - /// `PAGER=' -'`, its own path so no PATH lookup can find - /// another; plain `pardes -` where the path cannot be read or quoted. - fn pardesPagers() []const [*:0]const u8 { - const S = struct { - var pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; - var git_pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; - var systemd_pager: [std.Io.Dir.max_path_bytes + 32:0]u8 = undefined; - var entries: [4][*:0]const u8 = undefined; - var ready = false; - }; - if (!S.ready) { - var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - var quoted_buf: [std.Io.Dir.max_path_bytes + 2]u8 = undefined; - const n = if (comptime builtin.os.tag == .linux) libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len) else -1; - const exe: []const u8 = if (n > 0 and @as(usize, @intCast(n)) < exe_buf.len) exe_buf[0..@intCast(n)] else "pardes"; - const command = pagerCommand(exe, "ed_buf); - S.entries[0] = if (std.fmt.bufPrintSentinel(&S.pager, "PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "PAGER=pardes -"; - S.entries[1] = if (std.fmt.bufPrintSentinel(&S.git_pager, "GIT_PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "GIT_PAGER=pardes -"; - // systemd's tools (journalctl, systemctl) read their own, and - // in their secure mode run only less: this pager has no shell - // to escape to, so secure mode buys nothing. - S.entries[2] = if (std.fmt.bufPrintSentinel(&S.systemd_pager, "SYSTEMD_PAGER={s} -", .{command}, 0)) |t| t.ptr else |_| "SYSTEMD_PAGER=pardes -"; - S.entries[3] = "SYSTEMD_PAGERSECURE=0"; - S.ready = true; - } - return &S.entries; - } - - /// The pager's path as a command line takes it: as it is when it needs - /// no quoting (systemd splits on blanks and execs, never through sh), - /// in single quotes when it holds a blank or a shell character, plain - /// `pardes` when even that cannot hold it. - fn pagerCommand(exe: []const u8, buf: []u8) []const u8 { - const plain = for (exe) |c| { - if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "/._+-,@%=:", c) != null)) break false; - } else true; - if (plain) return exe; - if (std.mem.indexOfScalar(u8, exe, '\'') != null) return "pardes"; - return std.fmt.bufPrint(buf, "'{s}'", .{exe}) catch "pardes"; - } -}; - -extern "c" fn unsetenv(name: [*:0]const u8) c_int; - -/// For tests: unset `name` without compacting the environment block std -/// captured at startup (std.testing.environ and Io's spawns read it later). A -/// new variable first moves glibc's `environ` to a heap copy, which unsetenv -/// then compacts instead. Runtime code never changes this process's -/// environment (ChildEnv.exportVar). -pub fn testUnsetenv(name: [*:0]const u8) c_int { - _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); - return unsetenv(name); -} - -/// The environment a pane's command is given (exportEnv, `$winid`, -/// ChildEnv), as `NAME=value` lines in `arena`, for a command that is not a -/// pane's: an Edit's filters, run from pane `serial`. -pub fn commandEnv(arena: std.mem.Allocator, serial: u32, adopts: bool) ![]const []const u8 { - ninep_io.exportEnv(serial, adopts); - exportWinid(serial); - var slots: ChildEnv.Slots = undefined; - const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; - var out: std.ArrayList([]const u8) = .empty; - var i: usize = 0; - while (envp[i]) |entry| : (i += 1) try out.append(arena, try arena.dupe(u8, std.mem.span(entry))); - return out.items; -} - -fn exportWinid(serial: u32) void { - var buf: [16]u8 = undefined; - ChildEnv.exportVar("winid", if (serial == 0) null else std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); // a u32 fits 16 -} - -/// The longest line a command pane runs (exec.zig refuses a longer one). -pub const exec_command_max = pardes.exec.command_max; - -/// A pane's pty size, in cells and in pixels: a program sizes its kitty -/// graphics by the pixels (yazi's previews; pardes nested in a pane). -pub fn ptyWinsize(core: ?*const pardes.Pardes, cols: u16, rows: u16) posix.winsize { - var ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; - if (core) |c| { - ws.xpixel = std.math.cast(u16, @as(u32, cols) * c.view().cell_pixels.w) orelse 0; - ws.ypixel = std.math.cast(u16, @as(u32, rows) * c.view().cell_pixels.h) orelse 0; - } - return ws; -} - -pub fn forkShell( - core: ?*pardes.Pardes, - pane: usize, - prompt_rcs: *const Shell.PromptFiles, - bin: []const u8, - cwd: []const u8, - rows: u16, - cols: u16, -) !Child { - const native_cwd = filesystem.localPath(cwd) orelse cwd; - if (std.mem.indexOfScalar(u8, native_cwd, 0) != null) return error.InvalidPath; - var cwd_buf: [4096]u8 = undefined; - const serial = if (core) |c| if (c.panes[pane]) |pn| pn.serial else 0 else 0; - const cwd_z: ?[:0]const u8 = if (native_cwd.len == 0) null else dir: { - const path = std.fmt.bufPrintSentinel(&cwd_buf, "{s}", .{native_cwd}, 0) catch return error.NameTooLong; - // A shell's directory may be inside a mount this editor serves. - pardes.turn.yield(); - defer pardes.turn.back(); - const stat = try @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), path, .{}); - if (stat.kind != .directory) return error.NotDir; - break :dir path; - }; - var master: c_int = -1; - var path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - // 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; - if (core) |c| if (c.panes[pane]) |pn| if (pn.shell) |name| { - const n = @min(name.len, own_buf.len); - @memcpy(own_buf[0..n], name[0..n]); - own = own_buf[0..n]; - }; - var spawn = Shell.resolve(own orelse bin, &path_buf, prompt_rcs); - // The turn was given up for the stat and the lookup: a 9P client may - // have closed the pane, and another taken its slot, whose command this - // is not. - if (core) |c| if ((if (c.panes[pane]) |pn| pn.serial else 0) != serial) return error.PaneGone; - // A command pane's child is the shell running its one line, which has - // no prompt to mark (exec.zig runCommand). - const one_line = if (core) |c| if (c.panes[pane]) |pn| pn.command else null else null; - var command_buf: [exec_command_max + 1]u8 = undefined; - if (one_line) |line| { - if (line.len > exec_command_max or std.mem.indexOfScalar(u8, line, 0) != null) return error.InvalidCommand; - @memcpy(command_buf[0..line.len], line); - command_buf[line.len] = 0; - spawn.argv = Shell.commandArgv(spawn.path, command_buf[0..line.len :0].ptr); - } - ninep_io.exportEnv( - if (core) |c| (if (c.panes[pane]) |pn| pn.serial else 0) else 0, - if (core) |c| !c.opts.nested else false, - ); - // acme's `$winid`: the pane a command was run from, so a script it runs - // can address that pane; unset for a shell and a header tag's command. - exportWinid(if (core) |c| (if (c.panes[pane]) |pn| (if (pn.command != null) pn.command_from else 0) else 0) else 0); - // Built here and not after the fork: between fork and exec the child may - // not call setenv, whose malloc can deadlock against a pty reader thread - // that held the heap when the fork took its snapshot. - var env_slots: ChildEnv.Slots = undefined; - const pages = if (core) |c| if (c.panes[pane]) |pn| pn.command_pages else false else false; - const paging: ChildEnv.Paging = if (one_line != null and !pages) - .command - else - .terminal; - const envp = ChildEnv.build(&env_slots, paging); - const ws = ptyWinsize(core, cols, rows); - // The child says here why it could not become the shell (its chdir or - // its exec failed, as for a script whose interpreter is not there): the - // pipe closes on exec, so the parent reads nothing when the shell runs, - // and a reason when it did not, before anyone is told it started. - var told: [2]c_int = .{ -1, -1 }; - // pipe and then CLOEXEC, not pipe2, which macOS has not. - if (libc.pipe(&told) != 0) return error.PipeFailed; - ninep_io.setCloexec(told[0]); - ninep_io.setCloexec(told[1]); - const pid = forkpty(&master, null, null, &ws); - if (pid < 0) { - _ = libc.close(told[0]); - _ = libc.close(told[1]); - return error.ForkFailed; - } - if (pid == 0) { - resetChildSignals(); - if (cwd_z) |path| if (chdir(path.ptr) != 0) { - const why = [_]u8{ 'c', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; - _ = libc.write(told[1], &why, why.len); - _exit(126); - }; - if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); - _ = execv(spawn.path, &spawn.argv); - const why = [_]u8{ 'x', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; - _ = libc.write(told[1], &why, why.len); - _exit(127); - } - _ = libc.close(told[1]); - const failed = failed: { - var why: [2]u8 = undefined; - pardes.turn.yield(); - defer pardes.turn.back(); - const n = libc.read(told[0], &why, why.len); - _ = libc.close(told[0]); - if (n != 2) break :failed null; - break :failed why; - }; - if (failed) |why| { - _ = libc.close(master); - _ = libc.waitpid(pid, null, 0); - const e: libc.E = @fromBackingInt(@intCast(why[1])); - if (why[0] == 'c') return if (e == .NOENT or e == .NOTDIR) error.FileNotFound else error.AccessDenied; - return switch (e) { - // Itself, or its script's interpreter: told apart by whether it - // is there. - .NOENT => if (libc.access(spawn.path, 0) == 0) error.InterpreterNotFound else error.ShellNotFound, - .ACCES, .PERM => error.ShellNotExecutable, - .NOEXEC => error.ShellNotExecutable, - else => error.ShellDidNotStart, - }; - } - ninep_io.setCloexec(master); - // The daemon keeps a dup: this session killed outright never hangs the - // shell up (daemon.zig). - @import("runtime").daemon.pty(pid, master); - if (core) |c| c.acknowledgeShell(pane, std.mem.span(spawn.path), one_line == null and spawn.argv[1] != null); - return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; -} - -pub fn writeFd(fd: c_int, data: []const u8) bool { - var off: usize = 0; - while (off < data.len) { - const n = libc.write(fd, data[off..].ptr, data.len - off); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - return false; - } - if (n == 0) return false; - off += @intCast(n); - } - return true; -} - -const vnode_info_path = extern struct { - vi: [152]u8 align(8), // struct vnode_info: vinfo_stat + type + pad + fsid - path: [1024]u8, // MAXPATHLEN -}; -const proc_vnodepathinfo = extern struct { - cdir: vnode_info_path, - rdir: vnode_info_path, -}; -const PROC_PIDVNODEPATHINFO: c_int = 9; -extern "c" fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *anyopaque, buffersize: c_int) c_int; - -/// Whether an adopted shell marks its prompts: one pardes started with its -/// prompt files (bash, zsh, fish), which a pane's runs wait on. -pub fn marksPrompts(pid: libc.pid_t) bool { - var buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - const exe = std.Io.Dir.path.basename(processExe(pid, &buf) orelse return false); - for ([_][]const u8{ "bash", "zsh", "fish" }) |shell| if (std.mem.eql(u8, exe, shell)) return true; - return false; -} - -/// The program `pid` runs, where the system says (an adopted shell's, for -/// 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 - return if (n > 1) buf[0 .. n - 1] else null; - } - if (comptime builtin.os.tag != .linux) return null; - var pbuf: [64]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/exe", .{pid}, 0) catch unreachable; // a pid fits 64 - const n = libc.readlink(path, buf.ptr, buf.len); - if (n <= 0 or n >= buf.len) return null; - return buf[0..@intCast(n)]; -} - -pub fn shellCwd(pid: libc.pid_t, buf: []u8) ?[]const u8 { - switch (builtin.os.tag) { - .linux => { - var pbuf: [64]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&pbuf, "/proc/{d}/cwd", .{pid}, 0) catch unreachable; // a pid fits 64 - const n = libc.readlink(path, buf.ptr, buf.len); - if (n <= 0 or n >= buf.len) return null; - const link = buf[0..@intCast(n)]; - // A directory removed under the shell reads ` (deleted)`: - // no directory to be named by, so the name it had stays, and a - // restart works there once it is back. - if (std.mem.endsWith(u8, link, " (deleted)")) { - _ = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), link, .{}) catch return null; - } - return link; - }, - .macos, .ios, .tvos, .watchos, .visionos => { - var info: proc_vnodepathinfo = undefined; - const n = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, @sizeOf(proc_vnodepathinfo)); - if (n < @as(c_int, @sizeOf(proc_vnodepathinfo))) return null; - const path = std.mem.sliceTo(&info.cdir.path, 0); - if (path.len == 0 or path.len == info.cdir.path.len or path.len > buf.len) return null; - @memcpy(buf[0..path.len], path); - return buf[0..path.len]; - }, - .freebsd => { - // A struct kinfo_file (sys/user.h), its last 1024 bytes the path. - var kf: [1392]u8 align(8) = undefined; - const n = kernProc(pid, 42, &kf) orelse return null; // KERN_PROC_CWD - if (n <= 368) return null; - const path = std.mem.sliceTo(kf[368..n], 0); - if (path.len == 0 or path.len >= buf.len) return null; - @memcpy(buf[0..path.len], path); - return buf[0..path.len]; - }, - else => return null, - } -} - -/// FreeBSD's kern.proc.. into `buf`: the bytes it wrote. -fn kernProc(pid: libc.pid_t, what: c_int, buf: []u8) ?usize { - const mib = [_]c_int{ 1, 14, what, pid }; // CTL_KERN, KERN_PROC - var len: usize = buf.len; - if (libc.sysctl(&mib, mib.len, buf.ptr, &len, null, 0) != 0) return null; - return len; -} - -/// Where a terminal is. The process forked for it, while it still runs the -/// shell pardes started (`shell_exe`), as ever: a job it runs, in another -/// directory (`(cd sub && make)`, a nested pardes), never names the pane. -/// One that exec'd into something else is a wrapper whose own directory -/// never moves (fish's `exec 9ns --mntgen -- fish`): the shell is the -/// foreground group when that is the same shell, and while a job holds the -/// foreground there is no answer, the last one standing. -pub fn ttyCwd(shell_pid: libc.pid_t, master_fd: c_int, shell_exe: []const u8, buf: []u8) ?[]const u8 { - var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - var shell_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - const shell = realShell(shell_exe, &shell_buf) orelse return shellCwd(shell_pid, buf); - const exe = processExe(shell_pid, &exe_buf) orelse return shellCwd(shell_pid, buf); - if (std.mem.eql(u8, exe, shell)) return shellCwd(shell_pid, buf); - const fg = tcgetpgrp(master_fd); - if (fg <= 0 or fg == shell_pid) return null; - const fg_exe = processExe(fg, &exe_buf) orelse return null; - return if (std.mem.eql(u8, fg_exe, shell)) shellCwd(fg, buf) else null; -} - -/// `shell_exe` as /proc//exe would read it: its links followed. -fn realShell(shell_exe: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[]const u8 { - var z: [std.Io.Dir.max_path_bytes:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&z, "{s}", .{shell_exe}, 0) catch return null; - const r = libc.realpath(path, buf) orelse return null; - return std.mem.span(@as([*:0]const u8, @ptrCast(r))); -} - -extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; - -const occ_max_depth: u8 = 8; -const occ_max_visited: usize = 32; - -/// Where `ttyTaken` answers from evidence rather than from `false`. The two -/// implementations are different walks over the same question, so they share -/// one suite rather than each asserting half of it. -const tty_probe_platform = switch (builtin.os.tag) { - .linux, .macos => true, - else => false, -}; - -const TtyProbe = struct { - self_exe: [std.Io.Dir.max_path_bytes]u8 = undefined, - exe: [std.Io.Dir.max_path_bytes]u8 = undefined, - blob: [4096]u8 = undefined, - pending: [occ_max_visited]Node = undefined, - - const Node = struct { pid: libc.pid_t, depth: u8 }; -}; - -pub fn ttyTaken(shell_pid: libc.pid_t, master_fd: c_int) bool { - switch (builtin.os.tag) { - .linux => { - var probe: TtyProbe = undefined; - const fg = tcgetpgrp(master_fd); - if (fg < 0) return false; - const self_exe = processExe(shell_pid, &probe.self_exe) orelse return false; - - var saw_fg = fg == shell_pid; - var pending: usize = 0; - var visited: usize = 0; - switch (pushChildren(&probe, &pending, shell_pid, 1)) { - .pushed => {}, - .unreadable => return false, - .full => return true, - } - - while (pending > 0) { - pending -= 1; - const node = probe.pending[pending]; - visited += 1; - if (visited > occ_max_visited) return true; - - const pgrp = procPgrp(node.pid, &probe.blob); - if (pgrp) |g| { - if (g == fg) saw_fg = true; - } - - const exe = processExe(node.pid, &probe.exe) orelse { - if (offTty(node.pid, &probe.blob)) continue; - // Exiting (its exe gone, not a zombie yet), or not ours - // to read: outside the foreground group it holds - // nothing, as a killed background job does for a moment. - if (pgrp) |g| if (g != fg) continue; - return true; - }; - if (!std.mem.eql(u8, exe, self_exe)) { - if (pgrp) |g| if (g == fg) return true; - continue; - } - if (node.depth >= occ_max_depth) return true; - switch (pushChildren(&probe, &pending, node.pid, node.depth + 1)) { - .pushed => {}, - .unreadable => {}, - .full => return true, - } - } - return !saw_fg; - }, - .macos => { - const fg = tcgetpgrp(master_fd); - if (fg <= 0) return false; - if (fg == shell_pid) return false; - return darwin.taken(shell_pid, fg); - }, - // ponytail: any foreground job but the shell's own group, so a - // nested interactive shell counts as taken; walk the group - // (KERN_PROC_PGRP) as darwin does if that matters. - .freebsd => { - const fg = tcgetpgrp(master_fd); - return fg > 0 and fg != shell_pid; - }, - else => return false, - } -} - -/// The same question the Linux walk asks, answered the way macOS can answer -/// it. There is no /proc to descend and no children list, but the tty's -/// foreground process group can be enumerated in one call — and "is anything -/// but the shell itself holding this terminal?" is exactly a statement about -/// the executables in that group. The test is the shell's own executable and -/// never its pid, which is what keeps a nested interactive shell a prompt, -/// and what still catches `bash -c 'sleep 30'`: the group holds `sleep` too. -/// -/// Until this existed, `ttyTaken` answered `false` on darwin for every pane, -/// so `exec.takesCommandLine` was permanently true and every bare Escape in -/// a raw terminal ran the `Last` builtin instead of reaching the child. -const darwin = struct { - const proc_pgrp_only: u32 = 2; - const proc_pidt_shortbsdinfo: c_int = 13; - const zombie_status: u32 = 5; // SZOMB - /// PROC_PIDPATHINFO_MAXSIZE. - const path_max = 4 * 1024; - /// A foreground group is a pipeline; anything larger is not a prompt. - const group_max = 64; - - const ShortBsdInfo = extern struct { - pid: u32, - ppid: u32, - pgid: u32, - status: u32, - comm: [16]u8, - flags: u32, - uid: u32, - gid: u32, - ruid: u32, - rgid: u32, - svuid: u32, - svgid: u32, - rfu: u32, - }; - - extern "c" fn proc_listpids(kind: u32, typeinfo: u32, buffer: ?*anyopaque, buffersize: c_int) c_int; - extern "c" fn proc_pidpath(pid: c_int, buffer: [*]u8, buffersize: u32) c_int; - - fn exe(pid: libc.pid_t, buf: *[path_max]u8) ?[]const u8 { - const got = proc_pidpath(pid, buf, buf.len); - if (got <= 0) return null; - return buf[0..@intCast(got)]; - } - - /// A pid with no readable path is either gone or not ours. Only a zombie - /// is provably harmless — it holds no tty — so everything else is taken. - fn zombie(pid: libc.pid_t) bool { - var info: ShortBsdInfo = undefined; - const got = proc_pidinfo(pid, proc_pidt_shortbsdinfo, 0, &info, @sizeOf(ShortBsdInfo)); - if (got != @sizeOf(ShortBsdInfo)) return false; - return info.status == zombie_status; - } - - fn taken(shell_pid: libc.pid_t, fg: libc.pid_t) bool { - var shell_buf: [path_max]u8 = undefined; - const shell_exe = exe(shell_pid, &shell_buf) orelse return false; - var group: [group_max]libc.pid_t = undefined; - const bytes = proc_listpids(proc_pgrp_only, @intCast(fg), &group, @sizeOf(@TypeOf(group))); - // An empty group is a group whose last member just exited: the shell - // is about to have its terminal back, and calling that taken would - // blink the prompt heuristic off for a frame every time a job ends. - if (bytes <= 0) return false; - const n = @as(usize, @intCast(bytes)) / @sizeOf(libc.pid_t); - if (n >= group.len) return true; - var exe_buf: [path_max]u8 = undefined; - for (group[0..n]) |pid| { - if (pid <= 0 or pid == shell_pid) continue; - const path = exe(pid, &exe_buf) orelse { - if (zombie(pid)) continue; - return true; - }; - if (!std.mem.eql(u8, path, shell_exe)) return true; - } - return false; - } -}; - -/// A program a plumbing rule starts (Effect.start), as Plan 9's plumber -/// starts one (match.c's startup): out of the editor's way, a session of -/// its own reaped by init, stdin, stdout and stderr /dev/null and no other -/// fd of the editor's, its argv exec'd (no shell: a rule that wants one -/// says `sh -c`) in its directory. `line` is its directory, then its argv, -/// each ended by a NUL. Null once it runs, else why not, as errno says it, -/// in `why` (as the tape replays a host's words): a pipe closed at the -/// exec carries the child's errno back. -pub fn startDetached(_: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 { - const words = startWords(line) orelse return null; - const n = @min(words.len, why.len); - @memcpy(why[0..n], words[0..n]); - return why[0..n]; -} - -fn startWords(line: []const u8) ?[]const u8 { - var buf: [pardes.effect_path_cap]u8 = undefined; - if (line.len == 0 or line.len > buf.len or line[line.len - 1] != 0) return "malformed"; - @memcpy(buf[0..line.len], line); - var argv: [64:null]?[*:0]const u8 = @splat(null); - var n: usize = 0; - var at: usize = 0; - var dir: [*:0]const u8 = undefined; - while (at < line.len) { - const end = std.mem.indexOfScalarPos(u8, line, at, 0).?; - const word: [*:0]const u8 = @ptrCast(&buf[at]); - if (at == 0) dir = word else if (n < argv.len) { - argv[n] = word; - n += 1; - } else return "more than 64 words"; - at = end + 1; - } - if (n == 0) return "no program"; - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return "no pipe"; - for (fds) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); - const first = libc.fork(); - if (first < 0) { - _ = libc.close(fds[0]); - _ = libc.close(fds[1]); - return "no fork"; - } - if (first == 0) { - // Only async-signal-safe calls between fork and exec. - _ = libc.setsid(); - if (libc.fork() != 0) libc._exit(0); - resetChildSignals(); - // What failed, then errno: 'd' the directory, 'x' the exec. - const Fail = struct { - fn say(fd: c_int, what: u8) noreturn { - var said: [5]u8 = undefined; - said[0] = what; - std.mem.writeInt(u32, said[1..5], @intFromEnum(libc.errno(-1)), .little); - _ = libc.write(fd, &said, said.len); - libc._exit(127); - } - }; - const err_fd = libc.fcntl(fds[1], libc.F.DUPFD_CLOEXEC, @as(c_int, 3)); - if (err_fd < 0) libc._exit(127); - if (dir[0] != 0 and libc.chdir(dir) != 0) Fail.say(err_fd, 'd'); - const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); - if (null_fd >= 0) for (0..3) |i| { - _ = libc.dup2(null_fd, @intCast(i)); - }; - // Every fd of the editor's but the errno pipe's gone: a pty's - // master held open would keep its terminal alive. - if (libc.dup2(err_fd, 3) < 0) libc._exit(127); - _ = libc.fcntl(3, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); - const shut = if (comptime builtin.os.tag == .linux) - std.os.linux.close_range(4, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0 - else - false; - if (!shut) { - var fd: c_int = 4; - while (fd < 1024) : (fd += 1) _ = libc.close(fd); - } - _ = execvp(argv[0].?, &argv); - Fail.say(3, 'x'); - } - _ = libc.close(fds[1]); - while (libc.waitpid(first, null, 0) < 0 and libc.errno(-1) == .INTR) {} - var said: [5]u8 = undefined; - var got: usize = 0; - while (got < said.len) { - const r = libc.read(fds[0], said[got..].ptr, said.len - got); - if (r < 0 and libc.errno(r) == .INTR) continue; - if (r <= 0) break; - got += @intCast(r); - } - _ = libc.close(fds[0]); - if (got < said.len) return null; - const code = std.mem.readInt(u32, said[1..5], .little); - const E = libc.E; - if (code == @intFromEnum(E.NOENT)) return if (said[0] == 'd') "its directory: no such directory" else "not found"; - if (code == @intFromEnum(E.ACCES)) return "permission denied"; - if (code == @intFromEnum(E.NOTDIR)) return "not a directory"; - if (code == @intFromEnum(E.NOEXEC)) return "not an executable"; - return if (said[0] == 'd') "its directory: cannot go there" else "cannot start it"; -} - -extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; - -/// A terminal pane's shell is done with (its pane gone, its pty closed or at -/// end of file): say hangup, for a shell that ignores the tty's, and see it -/// reaped, killed if it is still there 100 ms on. A thread does the waiting -/// so that no host loop needs a timer for it (macOS's has none); a thread -/// that cannot start kills and reaps it here. -/// ponytail: only the window waits for them at exit (waitRetired); the tui -/// and macOS leave a shell still inside its 100 ms to init, a waitRetired at -/// their exit if that matters. -pub fn retireShell(pid: libc.pid_t) void { - if (pid <= 0) return; - _ = libc.kill(pid, libc.SIG.HUP); - if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; - _ = retiring.fetchAdd(1, .monotonic); - const thread = std.Thread.spawn(.{}, reapRetiring, .{pid}) catch { - _ = retiring.fetchSub(1, .monotonic); - return reapShell(pid, 0); - }; - thread.detach(); -} - -/// retireShell's threads still waiting on a shell. -var retiring: std.atomic.Value(u32) = .init(0); - -fn reapRetiring(pid: libc.pid_t) void { - defer _ = retiring.fetchSub(1, .release); - reapShell(pid, 100); -} - -/// An exit's sweep: every shell retireShell still waits on is seen out, gone -/// on its hangup or killed at the end of its 100 ms, and reaped, rather than -/// left to init. -pub fn waitRetired() void { - while (retiring.load(.acquire) != 0) { - const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); - } -} - -// ---- a command pane's child, watched to its exit ---- -// -// A command pane's command is done when its process exits, not when its pty -// reaches end of file: a job it put in the background can hold the pty open -// after it has gone, and a command can close its terminal and run on. A -// thread per command waits for the exit without reaping (WNOWAIT), so the -// pid is still the child's -- no Kill can reach another process that took -// it -- until the host, told through `takeExited`, reaps it in its own loop -// with `exitStatus` and tells the core. - -const freebsd = builtin.os.tag == .freebsd; -const waitid_p_pid: c_int = if (freebsd) 0 else 1; -const waitid_wexited: c_int = if (freebsd) 16 else 4; -const waitid_wnowait: c_int = switch (builtin.os.tag) { - .linux => 0x01000000, - .freebsd => 8, - else => 0x20, -}; -// FreeBSD's id_t is 64 bits. -extern "c" fn waitid(idtype: c_int, id: if (freebsd) i64 else c_uint, infop: *anyopaque, options: c_int) c_int; - -var exited: [pardes.MAX_PANES * 2]std.atomic.Value(libc.pid_t) = @splat(.init(0)); -var exit_lock: libc.pthread_mutex_t = .{}; -var exit_wake: ?struct { ctx: ?*anyopaque, f: *const fn (?*anyopaque) void } = null; - -/// Who wakes the host's loop when a watched child exits; null at shutdown, -/// after which a watcher still waiting tells nobody. -pub fn setExitWake(ctx: ?*anyopaque, f: ?*const fn (?*anyopaque) void) void { - _ = libc.pthread_mutex_lock(&exit_lock); - defer _ = libc.pthread_mutex_unlock(&exit_lock); - exit_wake = if (f) |wake| .{ .ctx = ctx, .f = wake } else null; -} - -/// Watches a command pane's child; false when no thread could be started, -/// and the host then reads its exit at end of file instead. -pub fn watchExit(pid: libc.pid_t) bool { - const thread = std.Thread.spawn(.{}, watchChild, .{pid}) catch return false; - thread.detach(); - return true; -} - -fn watchChild(pid: libc.pid_t) void { - var info: [128]u8 align(16) = undefined; - while (waitid(waitid_p_pid, @intCast(pid), &info, waitid_wexited | waitid_wnowait) < 0 and libc.errno(-1) == .INTR) {} - // A cell for it, waiting for one if the host is slow to take them. - place: while (true) { - for (&exited) |*cell| if (cell.cmpxchgStrong(0, pid, .acq_rel, .acquire) == null) break :place; - const ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); - } - wakeForExit(); -} - -fn wakeForExit() void { - _ = libc.pthread_mutex_lock(&exit_lock); - defer _ = libc.pthread_mutex_unlock(&exit_lock); - if (exit_wake) |wake| wake.f(wake.ctx); -} - -/// Where a host's command pane is between its child's exit and the end of -/// its output. The exit is told once the output before it is in: at the -/// pty's end of file; or, when something else still holds the pty (a job -/// the command left in the background), once nothing is waiting to be read -/// -- checked when the exit is seen and again after each chunk of output, -/// with no timer to miss. acme's waitthread tells an exit when it is -/// reaped (acme.c:587-700); a terminal also has output in flight. -pub const CommandWatch = struct { - watched: bool = false, - /// The master, to ask whether output is still waiting. - fd: c_int = -1, - eof: bool = false, - exited: bool = false, - told: bool = false, - status: ?u8 = null, - - /// Whether the exit is to be told now. - pub fn due(w: *const CommandWatch) bool { - if (!w.exited or w.told) return false; - if (w.eof) return true; - var pfd = [1]libc.pollfd{.{ .fd = w.fd, .events = libc.POLL.IN, .revents = 0 }}; - if (libc.poll(&pfd, 1, 0) < 0) return true; - // Every holder of its terminal gone: the end of file comes, after - // the rest of the output. - if (pfd[0].revents & libc.POLL.HUP != 0) return false; - return pfd[0].revents & libc.POLL.IN == 0; - } -}; - -/// A host's pty slot, whichever way it keeps it: an optional, or one whose -/// `fd` is -1 when empty. -fn SlotPty(comptime S: type) type { - return switch (@typeInfo(S)) { - .optional => |o| *o.child, - else => *S, - }; -} - -fn slotPty(slot: anytype) ?SlotPty(@TypeOf(slot.*)) { - return switch (@typeInfo(@TypeOf(slot.*))) { - .optional => if (slot.*) |*pt| pt else null, - else => if (slot.fd < 0) null else slot, - }; -} - -/// Each watched child that exited: reaped, and the core told once its -/// output is in, its pty closed (`close(ctx, id)`) if its end of file came -/// first. Every host runs this after an exit's wake and after each chunk -/// of a command's output; `ptys` is its slot array, each slot with a `pid` -/// and a `cmd`. -pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime close: anytype) void { - while (takeExited()) |pid| for (ptys) |*slot| { - const pt = slotPty(slot) orelse continue; - if (!pt.cmd.watched or pt.pid != pid or pt.cmd.exited) continue; - pt.cmd.status = (reapExited(pid) orelse break).status; - pt.cmd.exited = true; - pt.pid = 0; // reaped: no signal or retire may reach whoever gets it next - break; - }; - for (ptys, 0..) |*slot, id| { - const pt = slotPty(slot) orelse continue; - if (!pt.cmd.watched or !pt.cmd.due()) continue; - pt.cmd.told = true; - const eof = pt.cmd.eof; - core.update(.{ .exited = .{ .pane = @intCast(id), .status = pt.cmd.status } }); - if (eof) close(ctx, id); - } -} - -/// A watched command's pty reached end of file: the core hears its output -/// is over; the pty is closed now if its exit was told, else when it is. -pub fn commandEof(core: *pardes.Pardes, ptys: anytype, id: usize, ctx: anytype, comptime close: anytype) void { - const pt = slotPty(&ptys[id]) orelse return; - pt.cmd.eof = true; - core.update(.{ .eof = .{ .pane = @intCast(id) } }); - if (pt.cmd.told) return close(ctx, id); - takeExits(core, ptys, ctx, close); -} - -/// Reaps `pid` if it has exited: its status (null: unknown, or not ours -/// to read), or null when it is still running -- a pid a watcher reported -/// may since have been reaped by another and taken by a new child. -pub fn reapExited(pid: libc.pid_t) ?struct { status: ?u8 } { - if (pid <= 0) return .{ .status = null }; - var status: c_int = 0; - const got = libc.waitpid(pid, &status, libc.W.NOHANG); - if (got == 0) return null; - if (got != pid) return .{ .status = null }; - return .{ .status = statusOf(status) }; -} - -/// A wait status as a shell says it: the exit code, or 128 and the signal -/// that ended it; null for neither. -fn statusOf(status: c_int) ?u8 { - const s: u32 = @bitCast(status); - if (libc.W.IFEXITED(s)) return @truncate(libc.W.EXITSTATUS(s)); - if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))); - return null; -} - -/// A watched child that has exited, not yet reaped, or null. -pub fn takeExited() ?libc.pid_t { - for (&exited) |*cell| { - const pid = cell.swap(0, .acq_rel); - if (pid != 0) return pid; - } - return null; -} - -/// A pane's child at its pty's end of file: reaped, and how it exited -/// (its code, or 128 and the signal that ended it), if it is gone within -/// `wait_ms`; null if it is still running (a job it left holds nothing -/// open, but the child itself may be a moment behind its pty), which the -/// caller then retires as it would any shell. -pub fn exitStatus(pid: libc.pid_t, wait_ms: u32) ?u8 { - if (pid <= 0) return null; - var waited: u32 = 0; - while (true) : (waited += 2) { - var status: c_int = 0; - const got = libc.waitpid(pid, &status, libc.W.NOHANG); - if (got == pid) return statusOf(status); - if (got < 0 or waited >= wait_ms) return null; - const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); - } -} - -fn reapShell(pid: libc.pid_t, grace_ms: u32) void { - var waited: u32 = 0; - while (waited < grace_ms) : (waited += 5) { - // Not 0 is reaped, or someone else reaped it: either way not ours. - if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; - const ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); - } - if (libc.waitpid(pid, null, libc.W.NOHANG) != 0) return; - _ = libc.kill(pid, libc.SIG.KILL); - while (libc.waitpid(pid, null, 0) < 0 and libc.errno(-1) == .INTR) {} -} - -/// The tty's foreground job is signalled. A command pane's shell (`command`) -/// is its command too: its line runs with job control on, so the job -/// running is in a group of its own, and the shell's group goes as well, or -/// the rest of the line would run on after the job it was on. A stop (TERM -/// or KILL) of a command reaches its `&` jobs too, each in a group of its -/// own in the shell's session: Kill leaves nothing the line started. -/// The shell goes first: a job that died before it would let it run the -/// line's next command in the gap, and the gap is a scan of all of /proc -/// (signalSession), long once pids have wrapped below the old processes'. -pub fn signalTty(shell_pid: libc.pid_t, master_fd: c_int, which: pardes.PtySignal, command: bool) void { - const sig = switch (which) { - .int => libc.SIG.INT, - .term => libc.SIG.TERM, - .hup => libc.SIG.HUP, - .quit => libc.SIG.QUIT, - .kill => libc.SIG.KILL, - }; - const fg = tcgetpgrp(master_fd); - if (command and shell_pid > 0 and fg != shell_pid) _ = libc.kill(-shell_pid, sig); - if (command and shell_pid > 0 and (which == .term or which == .kill)) signalSession(shell_pid, sig); - if (fg > 0) _ = libc.kill(-fg, sig); - if (fg <= 0 and !command and shell_pid > 0) _ = libc.kill(shell_pid, sig); -} - -/// Every process group in the session `sid` leads, but its own (which the -/// caller signals last). forkpty made the shell the session's leader, and -/// job control moves a job to a new group, never out of the session. -// ponytail: Linux only (a /proc scan); elsewhere a `&` job outlives Kill, -// add sysctl KERN_PROC_SESSION on macOS if that matters. -fn signalSession(sid: libc.pid_t, sig: libc.SIG) void { - if (comptime builtin.os.tag != .linux) return; - const d = libc.opendir("/proc") orelse return; - defer _ = libc.closedir(d); - var buf: [4096]u8 = undefined; - while (libc.readdir(d)) |ent| { - const name = std.mem.sliceTo(&ent.name, 0); - const pid = std.fmt.parseInt(libc.pid_t, name, 10) catch continue; - var path_buf: [64:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/stat", .{pid}, 0) catch unreachable; // a pid fits 64 - const ids = parseGroupSession(readProc(path, &buf) orelse continue) orelse continue; - if (ids.session == sid and ids.pgrp != sid) _ = libc.kill(-ids.pgrp, sig); - } -} - -fn parseGroupSession(stat: []const u8) ?struct { pgrp: libc.pid_t, session: libc.pid_t } { - const close = std.mem.lastIndexOfScalar(u8, stat, ')') orelse return null; - var fields = std.mem.tokenizeAny(u8, stat[close + 1 ..], " \t\n"); - _ = fields.next() orelse return null; // 3: state - _ = fields.next() orelse return null; // 4: ppid - const pgrp = std.fmt.parseInt(libc.pid_t, fields.next() orelse return null, 10) catch return null; - const session = std.fmt.parseInt(libc.pid_t, fields.next() orelse return null, 10) catch return null; - return .{ .pgrp = pgrp, .session = session }; -} - -/// Kill: SIGTERM to the job in the tty's foreground, never to the shell. -/// The shell leads its own group, and a job it runs has another; with job -/// control off (`set +m`, a shell run as `sh -c`) the job shares the shell's -/// group, and there is no job to signal apart from it: false. -pub fn killJob(shell_pid: libc.pid_t, master_fd: c_int) bool { - const fg = tcgetpgrp(master_fd); - if (fg <= 0 or fg == shell_pid) return false; - return libc.kill(-fg, libc.SIG.TERM) == 0; -} - -/// The command name of the tty's foreground job, when that is not the -/// shell: what `pty/run` says is running. /proc//comm on Linux, the -/// program's name on FreeBSD. -pub fn foregroundName(shell_pid: libc.pid_t, master_fd: c_int, buf: []u8) ?[]const u8 { - if (comptime builtin.os.tag != .linux and builtin.os.tag != .freebsd) return null; - const fg = tcgetpgrp(master_fd); - if (fg <= 0 or fg == shell_pid) return null; - if (comptime builtin.os.tag == .freebsd) return std.Io.Dir.path.basename(processExe(fg, buf) orelse return null); - var name: [64:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/comm", .{@as(u32, @intCast(fg))}, 0) catch unreachable; // a u32 fits 64 - const comm = std.mem.trimEnd(u8, readProc(path, buf) orelse return null, "\n"); - return if (comm.len > 0) comm else null; -} - -fn readProc(path: [*:0]const u8, buf: []u8) ?[]const u8 { - const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); - if (fd < 0) return null; - defer _ = libc.close(fd); - const got = libc.read(fd, buf.ptr, buf.len); - if (got <= 0) return null; - return buf[0..@intCast(got)]; -} - -fn procPgrp(pid: libc.pid_t, buf: *[4096]u8) ?libc.pid_t { - var name: [64:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/stat", .{@as(u32, @intCast(pid))}, 0) catch unreachable; // a u32 fits 64 - return (parseGroupSession(readProc(path, buf) orelse return null) orelse return null).pgrp; -} - -fn offTty(pid: libc.pid_t, buf: *[4096]u8) bool { - var name: [64:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/status", .{@as(u32, @intCast(pid))}, 0) catch unreachable; // a u32 fits 64 - const status = readProc(path, buf) orelse return true; - return parseZombie(status); -} - -fn parseZombie(status: []const u8) bool { - var lines = std.mem.splitScalar(u8, status, '\n'); - while (lines.next()) |line| { - if (!std.mem.startsWith(u8, line, "State:")) continue; - const state = std.mem.trim(u8, line["State:".len..], " \t\r"); - return state.len > 0 and state[0] == 'Z'; - } - return false; -} - -const Pushed = enum { pushed, unreadable, full }; - -fn pushChildren(probe: *TtyProbe, pending: *usize, pid: libc.pid_t, depth: u8) Pushed { - var name: [96:0]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&name, "/proc/{d}/task/{d}/children", .{ - @as(u32, @intCast(pid)), @as(u32, @intCast(pid)), - }, 0) catch unreachable; // two u32s fit 96 - const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); - if (fd < 0) return .unreadable; - defer _ = libc.close(fd); - const got = libc.read(fd, &probe.blob, probe.blob.len); - if (got < 0) return .unreadable; - - var kids: [occ_max_visited]libc.pid_t = undefined; - const total = parseChildren(probe.blob[0..@intCast(got)], &kids); - if (total > kids.len or pending.* + total > probe.pending.len) return .full; - for (kids[0..total]) |kid| { - probe.pending[pending.*] = .{ .pid = kid, .depth = depth }; - pending.* += 1; - } - return .pushed; -} - -fn parseChildren(text: []const u8, out: []libc.pid_t) usize { - var total: usize = 0; - var it = std.mem.tokenizeAny(u8, text, " \t\n\r"); - while (it.next()) |tok| { - if (std.mem.indexOfNone(u8, tok, "0123456789") != null) continue; - const kid = std.fmt.parseInt(libc.pid_t, tok, 10) catch continue; - if (total < out.len) out[total] = kid; - total += 1; - } - return total; -} - -const test_shell = "/bin/bash"; -const test_prompt = "PZX> "; - -const TestShell = struct { - master: c_int, - pid: libc.pid_t, - tail: [8192]u8 = undefined, - tail_len: usize = 0, - - fn start() ?TestShell { - if (!haveFile(test_shell)) return null; - var master: c_int = undefined; - const ws = std.posix.winsize{ .row = 24, .col = 80, .xpixel = 0, .ypixel = 0 }; - const pid = forkpty(&master, null, null, &ws); - if (pid < 0) return null; - if (pid == 0) { - const argv: [3:null]?[*:0]const u8 = .{ test_shell, "--norc", "-i" }; - _ = execv(test_shell, &argv); - _exit(127); - } - var sh: TestShell = .{ .master = master, .pid = pid }; - sh.send("export PS1='PZ''X> '\n"); - if (!sh.waitText(test_prompt, 10_000)) { - sh.stop(); - return null; - } - sh.forget(); - return sh; - } - - fn send(sh: *TestShell, bytes: []const u8) void { - _ = libc.write(sh.master, bytes.ptr, bytes.len); - } - - fn forget(sh: *TestShell) void { - sh.tail_len = 0; - } - - fn drain(sh: *TestShell) void { - while (true) { - var fds = [1]libc.pollfd{.{ .fd = sh.master, .events = libc.POLL.IN, .revents = 0 }}; - if (libc.poll(&fds, 1, 0) <= 0) return; - if (fds[0].revents & libc.POLL.IN == 0) return; - var chunk: [4096]u8 = undefined; - const n = libc.read(sh.master, &chunk, chunk.len); - if (n <= 0) return; - sh.append(chunk[0..@intCast(n)]); - } - } - - fn append(sh: *TestShell, bytes: []const u8) void { - if (bytes.len >= sh.tail.len) { - @memcpy(&sh.tail, bytes[bytes.len - sh.tail.len ..]); - sh.tail_len = sh.tail.len; - return; - } - const room = sh.tail.len - sh.tail_len; - if (bytes.len > room) { - const drop = bytes.len - room; - std.mem.copyForwards(u8, sh.tail[0 .. sh.tail_len - drop], sh.tail[drop..sh.tail_len]); - sh.tail_len -= drop; - } - @memcpy(sh.tail[sh.tail_len..][0..bytes.len], bytes); - sh.tail_len += bytes.len; - } - - fn waitText(sh: *TestShell, needle: []const u8, ms: i64) bool { - const deadline = nowMs() + ms; - while (true) { - sh.drain(); - if (std.mem.indexOf(u8, sh.tail[0..sh.tail_len], needle) != null) return true; - if (nowMs() >= deadline) return false; - sleepMs(5); - } - } - - fn taken(sh: *TestShell) bool { - sh.drain(); - return ttyTaken(sh.pid, sh.master); - } - - fn waitTaken(sh: *TestShell, want: bool, ms: i64) bool { - const deadline = nowMs() + ms; - while (true) { - if (sh.taken() == want) return true; - if (nowMs() >= deadline) return false; - sleepMs(5); - } - } - - fn holdsTaken(sh: *TestShell, want: bool, ms: i64) bool { - const deadline = nowMs() + ms; - while (nowMs() < deadline) { - if (sh.taken() != want) return false; - sleepMs(5); - } - return true; - } - - fn stop(sh: *TestShell) void { - if (comptime builtin.os.tag == .linux) { - var probe: TtyProbe = undefined; - var pending: usize = 0; - var doomed: [occ_max_visited]libc.pid_t = undefined; - var n: usize = 0; - _ = pushChildren(&probe, &pending, sh.pid, 1); - while (pending > 0) { - pending -= 1; - const node = probe.pending[pending]; - if (n == doomed.len) break; - doomed[n] = node.pid; - n += 1; - if (node.depth < occ_max_depth) _ = pushChildren(&probe, &pending, node.pid, node.depth + 1); - } - _ = libc.kill(sh.pid, libc.SIG.KILL); - for (doomed[0..n]) |kid| { - _ = libc.kill(kid, libc.SIG.KILL); - _ = libc.kill(-kid, libc.SIG.KILL); - } - } else { - // No children list to descend. forkpty made the shell a session - // leader, so its own group plus whichever group currently holds - // the tty covers the job the test left running. - const fg = tcgetpgrp(sh.master); - if (fg > 0 and fg != sh.pid) _ = libc.kill(-fg, libc.SIG.KILL); - _ = libc.kill(-sh.pid, libc.SIG.KILL); - _ = libc.kill(sh.pid, libc.SIG.KILL); - } - _ = libc.waitpid(sh.pid, null, 0); - _ = libc.close(sh.master); - } -}; - -fn haveFile(path: [*:0]const u8) bool { - const fd = libc.open(path, .{ .ACCMODE = .RDONLY }); - if (fd < 0) return false; - _ = libc.close(fd); - return true; -} - -fn nowMs() i64 { - return std.Io.Clock.awake.now(std.testing.io).toMilliseconds(); -} - -fn sleepMs(ms: i64) void { - std.testing.io.sleep(.fromMilliseconds(ms), .awake) catch {}; -} - -// ---- what every host's vtable does alike ---- - -/// A Save's write: the file written through the core's filesystem, the -/// pane's watch told the new text is the editor's own (so it is no outside -/// change), and "saved" said on the pane. -pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { - filesystem.write(core, path, bytes) catch |err| - return core.saveFailed(pane, path, err); - if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { - if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { - .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, - .kind => {}, - }; - }; - var mbuf: [256]u8 = undefined; - core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); - // The init file, saved here (Config): its settings take effect now. - pardes.exec.reapplyInitFile(core, path, bytes); - // The plumbing file (Plumb): its rules in force now. - pardes.Plumb.saved(core, pane, path, bytes); -} - -/// A Dump's write: into the state file under a label of its own -/// (Db.putDump), or as a file of its own where `Dump export` names one or -/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its -/// goldens). -pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { - const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; - if (to) |path| { - filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); - return core.setLastDump(path); - } - var stamp: [64]u8 = undefined; - var buf: [128]u8 = undefined; - const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { - var path: [4200]u8 = undefined; - // In the words a host reports failures in (tape.Failure). - const said: pardes.tape.Failure = switch (err) { - error.NoStateFile => error.NoDumpDirectory, - error.OutOfMemory => error.OutOfMemory, - error.NoSpaceLeft => error.NoSpaceLeft, - error.AccessDenied => error.AccessDenied, - else => error.InputOutput, - }; - return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); - }; - core.setLastDump(label); -} - -/// DumpThemes: the built-in themes written below the config directory. -pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { - const config_dir = core.opts.config_dir orelse return; - const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { - core.reportError(pane, "dump themes", err); - return; - }; - defer gpa.free(out_dir); - var mbuf: [256]u8 = undefined; - core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); -} - -pub const PtyTests = struct { - pub fn waitBlocked(queue: *Inbox) !void { - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - queue.lock(); - const waiting = queue.waiting; - queue.unlock(); - if (waiting != 0) return; - try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - return error.ReaderDidNotBlock; - } - - fn tail(queue: *Inbox, bytes: []u8) void { - if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - } -}; - -test { - _ = Lsp; -} - -test "a child starts with every signal at its default and none blocked" { - var blocked = posix.sigemptyset(); - posix.sigaddset(&blocked, posix.SIG.WINCH); - posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); - defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); - const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; - var was: posix.Sigaction = undefined; - posix.sigaction(posix.SIG.HUP, &ignore, &was); - defer posix.sigaction(posix.SIG.HUP, &was, null); - const pid = libc.fork(); - if (pid == 0) { - resetChildSignals(); - var now: posix.Sigaction = undefined; - posix.sigaction(posix.SIG.HUP, null, &now); - var mask = posix.sigemptyset(); - posix.sigprocmask(posix.SIG.BLOCK, null, &mask); - const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); - libc._exit(if (ok) 0 else 1); - } - var status: c_int = 0; - _ = libc.waitpid(pid, &status, 0); - try std.testing.expectEqual(@as(c_int, 0), status); -} - -test "the pager's path is quoted only when it needs it" { - var buf: [64]u8 = undefined; - try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); - try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); - try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); -} - -test "the child environment replaces the launcher's terminal identity exactly once" { - const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; - var saved_buf: [256]u8 = undefined; - const restore: ?[:0]const u8 = if (saved) |t| blk: { - if (t.len >= saved_buf.len) break :blk null; - @memcpy(saved_buf[0..t.len], t); - saved_buf[t.len] = 0; - break :blk saved_buf[0..t.len :0]; - } else null; - defer if (restore) |t| { - _ = Shell.setenv("TERM", t.ptr, 1); - } else { - _ = testUnsetenv("TERM"); - }; - - // A launcher TERM must be shadowed rather than duplicated, and the rest of - // the environment must arrive untouched. - try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); - try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); - defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); - - var slots: ChildEnv.Slots = undefined; - // Where the user named no pager: a terminal's shell pages into a - // +Pager pane (`pardes -`); a command pane's through cat. A pager the - // user named is kept. - var shell_slots: ChildEnv.Slots = undefined; - const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; - var said: usize = 0; - var systemd: usize = 0; - var j: usize = 0; - while (shell_envp[j]) |entry| : (j += 1) { - const line = std.mem.span(entry); - if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; - if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; - if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { - try std.testing.expect(std.mem.endsWith(u8, line, " -")); - said += 1; - } - } - if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); - // systemd's pager and its secure mode off, with ours only. - if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) - try std.testing.expectEqual(@as(usize, 2), systemd); - const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; - var terms: usize = 0; - var colorterms: usize = 0; - var probes: usize = 0; - var dumb = false; - var pagers: usize = 0; - var git_pagers: usize = 0; - var pager_cat = false; - var git_pager_cat = false; - var i: usize = 0; - while (envp[i]) |entry| : (i += 1) { - const line = std.mem.span(entry); - if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; - if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; - if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; - if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; - if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; - if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; - if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; - if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; - } - // A pager only where the user named none: cat, so nothing waits in less. - try std.testing.expectEqual(@as(usize, 1), pagers); - try std.testing.expectEqual(@as(usize, 1), git_pagers); - if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); - if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); - try std.testing.expectEqual(@as(usize, 1), terms); - try std.testing.expectEqual(@as(usize, 1), colorterms); - try std.testing.expectEqual(@as(usize, 1), probes); - try std.testing.expect(!dumb); - // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it - // is a separate entry and never a second TERM. - try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); -} - -test "shell spawn rejects invalid directories before creating a child" { - const rcs: Shell.PromptFiles = .{}; - try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); - const too_long = @as([4096]u8, @splat('x')); - try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); - - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; - var path_buf: [4096]u8 = undefined; - const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); - const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); - const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); - try std.testing.expect(missing.len > 256); - try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); -} - -test "a forked shell is told which terminal it is talking to" { - if (!haveFile("/bin/sh")) return error.SkipZigTest; - // Whatever launched the test is the wrong answer, so make it a loud one. - const saved = libc.getenv("TERM"); - var saved_buf: [256]u8 = undefined; - const restore: ?[:0]const u8 = if (saved) |t| blk: { - const span = std.mem.span(t); - if (span.len >= saved_buf.len) break :blk null; - @memcpy(saved_buf[0..span.len], span); - saved_buf[span.len] = 0; - break :blk saved_buf[0..span.len :0]; - } else null; - defer if (restore) |t| { - _ = Shell.setenv("TERM", t.ptr, 1); - } else { - _ = testUnsetenv("TERM"); - }; - _ = Shell.setenv("TERM", "dumb", 1); - - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - // The echoed command carries the unexpanded `$TERM`, so only the shell's - // own expansion can match this. - try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); - try std.testing.expect(sh.waitText( - "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, - 5_000, - )); -} - -test "shell spawn uses an explicit OS directory longer than 256 bytes" { - if (!haveFile("/bin/sh")) return error.SkipZigTest; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); - try tmp.dir.createDirPath(std.testing.io, sub_path); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; - try std.testing.expect(directory.len > 256); - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); - var expected_buf: [4096]u8 = undefined; - const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); - try std.testing.expect(sh.waitText(expected, 5_000)); -} - -test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "start/a/b"); - var path_buf: [4096]u8 = undefined; - const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; - var inner_buf: [4096]u8 = undefined; - const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; - const rcs: Shell.PromptFiles = .{}; - var result: [4096]u8 = undefined; - // A wrapper exec'd over the shell (timeout standing in for 9ns) runs - // another, two directories down, in the foreground. - { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); - try std.testing.expect(sh.waitText("pardes-in-", 5_000)); - // printf runs before the inner shell takes the foreground. - var tries: usize = 0; - while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) - try std.testing.io.sleep(.fromMilliseconds(20), .awake); - try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); - try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); - } - // A job of the shell's own, gone into a/b, leaves the pane where the - // shell is. - { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); - try std.testing.expect(sh.waitText("pardes-job", 5_000)); - try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); - } -} - -test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); - try tmp.dir.createDirPath(io, nested); - var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; - try std.testing.expect(directory.len > 1024); - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); - try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); - var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); - try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); - try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); -} - -test "a shell whose directory was removed is not named `... (deleted)`" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "gone"); - var path_buf: [4096]u8 = undefined; - const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); - try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); - var result: [4096]u8 = undefined; - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); - try tmp.dir.deleteDir(io, "gone"); - try std.testing.expect(shellCwd(child.pid, &result) == null); -} - -test "the children blob parses to pids, and a garbage token never becomes one" { - var out: [8]libc.pid_t = undefined; - try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); - try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); - try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); - try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); - try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); - try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); - try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); - try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); - var two: [2]libc.pid_t = undefined; - try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); -} - -test "the process group comes off the last ')', not a comm-shifted stat field" { - const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ - "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; - try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); - try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); - try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); - try std.testing.expect(parseGroupSession("") == null); - try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); - try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); - try std.testing.expect(parseGroupSession("no parens here at all") == null); -} - -test "the zombie state comes off its own status line" { - try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); - try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); - try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); - try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); - try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); - try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); - try std.testing.expect(!parseZombie("Name:\tsh\nSta")); - try std.testing.expect(!parseZombie("State:\t")); -} - -test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - try std.testing.expect(sh.holdsTaken(false, 200)); - - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - - sh.forget(); - sh.send("\x03"); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); -} - -test "Kill stops the foreground job, never the shell, and finds none with job control off" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - // At the prompt the shell is the foreground: there is nothing to stop. - try std.testing.expect(!killJob(sh.pid, sh.master)); - sleepMs(100); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); - - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - sh.forget(); - try std.testing.expect(killJob(sh.pid, sh.master)); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); - - // Job control off: the job runs in the shell's own group. - sh.forget(); - sh.send("set +m; sleep 30\n"); - sleepMs(300); - try std.testing.expect(!killJob(sh.pid, sh.master)); - sh.forget(); - sh.send("\x03"); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); -} - -test "a command pane's child is its shell running the one line, and its exit status is read at the end" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane - if (comptime !tty_probe_platform) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); - defer _ = libc.close(child.file.handle); - var got: [256]u8 = undefined; - var n: usize = 0; - while (n < got.len) { - const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); - if (r <= 0) break; // EIO once the child is gone: the pty's end - n += @intCast(r); - } - try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); - try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); -} - -test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane - if (comptime !tty_probe_platform) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - const Case = struct { line: []const u8, status: u8 }; - // A job left in the background holds the pty open past the command's - // exit; a command that lets go of its terminal runs on past its end of - // file. Either way the exit is the process's. - for ([_]Case{ - .{ .line = "sleep 3 & exit 4", .status = 4 }, - .{ .line = "exec /dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, - }) |c| { - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, "", c.line); - while (core.nextEffect()) |_| {} - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); - defer _ = libc.close(child.file.handle); - try std.testing.expect(watchExit(child.pid)); - var got: ?libc.pid_t = null; - var waited: i64 = 0; - while (got == null and waited < 5000) : (waited += 10) { - got = takeExited(); - if (got == null) sleepMs(10); - } - try std.testing.expectEqual(@as(?libc.pid_t, child.pid), got); - // Told before it is reaped: the pid is still the child's. - try std.testing.expectEqual(@as(?u8, c.status), reapExited(child.pid).?.status); - try core.removePane(id, null); - } -} - -test "a command's background job outlives it and its pty, and Kill stops its whole line, its & jobs too" { - if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane - if (comptime !tty_probe_platform) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - const Case = struct { line: []const u8, kill: bool, made: bool }; - for ([_]Case{ - // The shell leads the pty's session; its exit hangs up only the - // foreground group, which the job, in a group of its own, is not. - .{ .line = "(sleep 0.4; touch left) & exit 0", .kill = false, .made = true }, - // The job running is in its own group; the shell goes too. - .{ .line = "sleep 0.4; touch killed", .kill = true, .made = false }, - // Kill stops the whole command, its `&` jobs as well. - .{ .line = "(sleep 0.4; touch killed) & sleep 5", .kill = true, .made = false }, - }) |c| { - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, dir, c.line); - while (core.nextEffect()) |_| {} - const child = try forkShell(core, id, &rcs, "/bin/sh", dir, 24, 80); - if (c.kill) { - sleepMs(150); - signalTty(child.pid, child.file.handle, .term, true); - } - _ = exitStatus(child.pid, 2000); - _ = libc.close(child.file.handle); // the pane closes: the pty hangs up - sleepMs(800); - const name = if (c.kill) "killed" else "left"; - const made = if (tmp.dir.statFile(std.testing.io, name, .{})) |_| true else |_| false; - try std.testing.expectEqual(c.made, made); - try core.removePane(id, null); - } -} - -test "a retired shell that ignores the hangup is killed and reaped, not left a zombie" { - const pid = libc.fork(); - if (pid == 0) { - const argv = [_:null]?[*:0]const u8{ "/bin/sh", "-c", "trap '' HUP; exec sleep 30" }; - const envp = [_:null]?[*:0]const u8{}; - _ = libc.execve("/bin/sh", &argv, &envp); - libc._exit(127); - } - try std.testing.expect(pid > 0); - sleepMs(100); // past the trap - retireShell(pid); - // A zombie still answers kill(pid, 0); only a reaped pid is gone. - var waited: i64 = 0; - while (libc.kill(pid, @fromBackingInt(@intCast(0))) == 0 and waited < 2000) : (waited += 10) sleepMs(10); - try std.testing.expect(libc.kill(pid, @fromBackingInt(@intCast(0))) != 0); - try std.testing.expect(waited >= 90); // it did ignore the hangup -} - -test "a background job is not the tty's owner" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - sh.send("sleep 30 &\n"); - try std.testing.expect(sh.waitText("[1]", 10_000)); - try std.testing.expect(sh.holdsTaken(false, 300)); - - sh.send("kill %1\n"); - try std.testing.expect(sh.holdsTaken(false, 300)); -} - -test "a nested interactive shell is still a prompt" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - sh.forget(); - sh.send("bash --norc -i\n"); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expect(sh.holdsTaken(false, 300)); - - sh.forget(); - sh.send("bash --norc -i\n"); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expect(sh.holdsTaken(false, 300)); - - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - sh.send("\x03"); - try std.testing.expect(sh.waitTaken(false, 10_000)); -} - -test "the walk reaches the leaf: bash -c 'sleep 30' takes the tty" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - sh.send("bash --norc -c 'sleep 30'\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - sh.send("\x03"); - try std.testing.expect(sh.waitTaken(false, 10_000)); - - sh.send("bash --norc -c 'sleep 30; :'\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - - // Why the shallow answer is the wrong one, in each walk's own evidence: - // the wrapper between the shell and `sleep` wears the shell's executable, - // so a probe that stopped at it would report a prompt. - if (comptime builtin.os.tag == .linux) { - var probe: TtyProbe = undefined; - var pending: usize = 0; - try std.testing.expectEqual(Pushed.pushed, pushChildren(&probe, &pending, sh.pid, 1)); - try std.testing.expectEqual(@as(usize, 1), pending); - var wrapper_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - var shell_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; - try std.testing.expectEqualStrings( - processExe(sh.pid, &shell_buf).?, - processExe(probe.pending[0].pid, &wrapper_buf).?, - ); - } else { - const fg = tcgetpgrp(sh.master); - try std.testing.expect(fg > 0 and fg != sh.pid); - var leader_buf: [darwin.path_max]u8 = undefined; - var shell_buf: [darwin.path_max]u8 = undefined; - // The group's leader IS that wrapper, and it is the shell's binary. - try std.testing.expectEqualStrings( - darwin.exe(sh.pid, &shell_buf).?, - darwin.exe(fg, &leader_buf).?, - ); - // Taken all the same, because the rest of the group is not. - try std.testing.expect(darwin.taken(sh.pid, fg)); - } - - sh.send("\x03"); - try std.testing.expect(sh.waitTaken(false, 10_000)); -} - -test "a full-screen program takes the tty until it quits" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - const cases = [_]struct { bin: [*:0]const u8, run: []const u8, quit: []const u8 }{ - .{ .bin = "/usr/bin/vim", .run = "vim -u NONE -i NONE\n", .quit = "\x1b:q!\r" }, - .{ .bin = "/usr/bin/less", .run = "env LESS= less /etc/hosts\n", .quit = "q" }, - }; - var ran: usize = 0; - for (cases) |c| { - if (!haveFile(c.bin)) continue; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - sh.send(c.run); - try std.testing.expect(sh.waitTaken(true, 10_000)); - sh.forget(); - sh.send(c.quit); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - ran += 1; - } - if (ran == 0) return error.SkipZigTest; -} - -test "completion survives a full output queue" { - const gpa = std.testing.allocator; - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 7 }; - defer queue.deinit(); - queue.acceptReader(0, 1); - for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "output"), - } }); - for (0..selection_pipe.Tasks.capacity) |id| queue.push(.{ .pipe = .{ - .id = @intCast(id), - .success = false, - .outputs = &.{}, - .failure = .{ .stderr = try gpa.dupe(u8, "pipe failure") }, - } }); - queue.push(.{ .lsp = .{ .id = 7, .rows = try gpa.dupe(u8, "completion") } }); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(Inbox.output_capacity + selection_pipe.Tasks.capacity + 1, batch.len); - for (batch.items[0..Inbox.output_capacity]) |msg| { - try std.testing.expect(msg == .output); - try std.testing.expectEqualStrings("output", msg.output.bytes); - } - for (batch.items[Inbox.output_capacity..][0..selection_pipe.Tasks.capacity], 0..) |msg, id| { - try std.testing.expect(msg == .pipe); - try std.testing.expectEqual(@as(u32, @intCast(id)), msg.pipe.id); - } - var found = false; - for (batch.slice()) |msg| if (msg == .lsp) { - try std.testing.expectEqual(@as(u32, 7), msg.lsp.id); - try std.testing.expectEqualStrings("completion", msg.lsp.rows.?); - found = true; - }; - try std.testing.expect(found); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); -} - -test "PTY backpressure retains byte order and tail before EOF" { - const gpa = std.testing.allocator; - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - queue.acceptReader(0, 1); - for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); - const tail = try gpa.dupe(u8, "tail"); - var thread: ?std.Thread = std.Thread.spawn(.{}, PtyTests.tail, .{ &queue, tail }) catch |err| { - gpa.free(tail); - return err; - }; - defer { - queue.cancelReader(0, 1); - if (thread) |owned| owned.join(); - } - try PtyTests.waitBlocked(&queue); - queue.push(.files_changed); - queue.push(.files_changed); - var first = queue.take(); - defer for (first.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(Inbox.output_capacity + 1, first.len); - for (first.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); - try std.testing.expect(first.items[Inbox.output_capacity] == .files_changed); - thread.?.join(); - thread = null; - var last = queue.take(); - defer for (last.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 2), last.len); - try std.testing.expectEqualStrings("tail", last.items[0].output.bytes); - try std.testing.expect(last.items[1] == .eof); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); -} - -test "PTY backpressure cancellation and close release owned producers" { - const gpa = std.testing.allocator; - for ([_]bool{ false, true }) |close| { - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - queue.acceptReader(0, 1); - for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); - const tail = try gpa.dupe(u8, "cancelled"); - const thread = std.Thread.spawn(.{}, PtyTests.tail, .{ &queue, tail }) catch |err| { - gpa.free(tail); - return err; - }; - defer { - queue.cancelReader(0, 1); - thread.join(); - } - try PtyTests.waitBlocked(&queue); - if (close) queue.close() else queue.cancelReader(0, 1); - if (!close) { - queue.acceptReader(0, 2); - queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - try std.testing.expect(queue.pushOutput(0, 2, try gpa.dupe(u8, "replacement"))); - queue.push(.{ .eof = .{ .pane = 0, .gen = 2 } }); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 2), batch.len); - try std.testing.expectEqualStrings("replacement", batch.items[0].output.bytes); - try std.testing.expectEqual(@as(u32, 2), batch.items[1].eof.gen); - } else try std.testing.expectEqual(@as(usize, 0), queue.take().len); - } -} - -test "PTY EOF reserve cannot evict terminal output" { - const gpa = std.testing.allocator; - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - for (0..pardes.MAX_PANES) |pane| queue.acceptReader(@intCast(pane), 1); - for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); - for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = @intCast(pane), .gen = 1 } }); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(Inbox.capacity, batch.len); - for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); - for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane); -} - -test "completions retain their arrival order across LSP and pipes" { - const gpa = std.testing.allocator; - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 }; - defer queue.deinit(); - queue.push(.{ .pipe = .{ .id = 1, .success = true, .outputs = &.{} } }); - queue.push(.{ .lsp = .{ .id = 2, .rows = try gpa.dupe(u8, "second") } }); - queue.push(.{ .pipe = .{ .id = 3, .success = false, .outputs = &.{} } }); - queue.push(.{ .lsp = .{ .id = 1, .rows = try gpa.dupe(u8, "late") } }); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 3), batch.len); - try std.testing.expectEqual(@as(u32, 1), batch.items[0].pipe.id); - try std.testing.expectEqual(@as(u32, 2), batch.items[1].lsp.id); - try std.testing.expectEqual(@as(u32, 3), batch.items[2].pipe.id); -} - -test "completion reset frees queued payloads and rejects late LSP workers" { - const gpa = std.testing.allocator; - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 9 }; - defer queue.deinit(); - queue.acceptReader(0, 1); - queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "retained") } }); - queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "current") } }); - queue.push(.{ .lsp = .{ .id = 8, .rows = try gpa.dupe(u8, "late old request") } }); - try std.testing.expectEqualStrings("current", queue.completions[0].lsp.rows.?); - for (0..selection_pipe.Tasks.capacity) |id| { - const outputs = try gpa.alloc([]u8, 1); - outputs[0] = try gpa.dupe(u8, "cancelled result"); - queue.push(.{ .pipe = .{ .id = @intCast(id), .success = true, .outputs = outputs } }); - } - queue.discardCompletions(); - queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "late before Restore") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqualStrings("retained", batch.items[0].output.bytes); - - queue.lsp_id = 10; - queue.push(.{ .lsp = .{ .id = 10, .rows = null } }); - queue.push(.{ .lsp = .{ .id = 9, .rows = try gpa.dupe(u8, "late after Restore") } }); - var next = queue.take(); - defer for (next.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), next.len); - try std.testing.expectEqual(@as(u32, 10), next.items[0].lsp.id); - try std.testing.expect(next.items[0].lsp.rows == null); - - queue.push(.{ .lsp = .{ .id = 10, .rows = try gpa.dupe(u8, "closing result") } }); - queue.push(.{ .pipe = .{ - .id = 17, - .success = false, - .outputs = &.{}, - .failure = .{ .stderr = try gpa.dupe(u8, "closing failure") }, - } }); - queue.close(); - queue.push(.{ .lsp = .{ .id = 10, .rows = try gpa.dupe(u8, "late closed result") } }); - queue.push(.{ .pipe = .{ - .id = 18, - .success = false, - .outputs = &.{}, - .failure = .{ .stderr = try gpa.dupe(u8, "late closed failure") }, - } }); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); -} - -test "LSP query answers, and a newer one cancels it" { - const gpa = std.testing.allocator; - const io = std.testing.io; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - _ = try core.setTestFile("abc"); - var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - for (0..2) |_| { - core.lspRequest(core.view().active, .status, ""); - queue.startLsp(core, .{ .id = core.lsp_ask.wait.?.id, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" }); - } - const last = core.lsp_ask.wait.?.id; - queue.lsp_task.?.future.await(io); - queue.lsp_task = null; - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqual(last, batch.items[0].lsp.id); - try std.testing.expect(batch.items[0].lsp.rows != null); - core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); - try std.testing.expect(core.lsp_ask.wait == null); -} - -test "a plumbing rule's program starts detached, or says why not: a program not found, a directory not there" { - if (comptime builtin.os.tag != .linux) return; - var why: [64]u8 = undefined; - try std.testing.expect(startDetached(null, "/\x00true\x00", &why) == null); - try std.testing.expectEqualStrings("not found", startDetached(null, "/\x00no-such-program-x\x00", &why).?); - try std.testing.expectEqualStrings("its directory: no such directory", startDetached(null, "/no/such/dir\x00true\x00", &why).?); - try std.testing.expectEqualStrings("malformed", startDetached(null, "/\x00true", &why).?); -} diff --git a/src/jump_trail.zig b/src/jump_trail.zig deleted file mode 100644 index 25eba636..00000000 --- a/src/jump_trail.zig +++ /dev/null @@ -1,87 +0,0 @@ -//! JumpTrail: a jump of the cursor, three cells or more between two frames, -//! leaves a trail of three to five cells behind it along its path, most -//! beside the cursor, all fading out over 120 ms. A frontend's own: it sees -//! the cursor of the Surface it shows, frame after frame, and times the fade -//! on its own clock; the tty tints those cells' ground toward the text, the -//! window draws over them. Nothing of it reaches the core, which keeps the -//! setting alone (config.Runtime.jump_trail). -const std = @import("std"); - -pub const life_ns: u64 = 120 * std.time.ns_per_ms; - -/// A cell of the trail, and how far toward the text it is drawn (0 to 1). -pub const Cell = struct { x: i32, y: i32, strength: f32 }; - -last: ?[2]u16 = null, -from: [2]u16 = .{ 0, 0 }, -to: [2]u16 = .{ 0, 0 }, -start_ns: u64 = 0, -/// Fading: a frontend draws frames until it is not. -active: bool = false, - -const JumpTrail = @This(); - -/// A frame shows the cursor at `cursor` (null: none) at `now_ns`: the -/// trail's cells in it, the one beside the cursor first, or none. -pub fn see(trail: *JumpTrail, cursor: ?[2]u16, on: bool, now_ns: u64, out: *[5]Cell) []const Cell { - const here = cursor orelse { - trail.* = .{}; - return out[0..0]; - }; - 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.* = .{ .from = was, .to = here, .start_ns = now_ns, .active = true }; - } - trail.last = here; - const age = now_ns -| trail.start_ns; - if (!on or !trail.active or age >= life_ns or !std.meta.eql(trail.to, here)) { - trail.active = false; - return out[0..0]; - } - const t = @as(f32, @floatFromInt(age)) / @as(f32, @floatFromInt(life_ns)); - const fade = (1 - t) * (1 - t); - const dx: f32 = @floatFromInt(@as(i32, trail.from[0]) - trail.to[0]); - const dy: 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 len: usize = 0; - 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; - const strength = 0.55 * fade * (1 - @as(f32, @floatFromInt(k - 1)) / @as(f32, @floatFromInt(n))); - if (strength < 0.02) continue; - out[len] = .{ .x = x, .y = y, .strength = strength }; - len += 1; - } - return out[0..len]; -} - -test "a jump leaves a few cells behind the cursor, fading in 120 ms; a step, or off, leaves none" { - const ms = std.time.ns_per_ms; - var trail: JumpTrail = .{}; - var out: [5]Cell = undefined; - try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 2, 1 }, true, 1000 * ms, &out).len); - // Ten cells right: a trail back toward where it was, on its row, behind - // it, never its own cell, strongest beside it. - const lit = trail.see(.{ 12, 1 }, true, 1016 * ms, &out); - try std.testing.expect(trail.active and lit.len >= 3 and lit.len <= 5); - for (lit, 0..) |cell, i| { - try std.testing.expectEqual(@as(i32, 1), cell.y); - try std.testing.expect(cell.x > 2 and cell.x < 12); - if (i > 0) try std.testing.expect(cell.strength < lit[i - 1].strength and cell.x < lit[i - 1].x); - } - // Gone by 120 ms. - try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 12, 1 }, true, 1150 * ms, &out).len); - try std.testing.expect(!trail.active); - // A step of a cell leaves none; nor does a jump with it off. - try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 13, 1 }, true, 1200 * ms, &out).len); - try std.testing.expectEqual(@as(usize, 0), trail.see(.{ 2, 1 }, false, 1216 * ms, &out).len); - try std.testing.expect(!trail.active); -} diff --git a/src/look.zig b/src/look.zig index 2ca4afc3..c6e2ea8b 100644 --- a/src/look.zig +++ b/src/look.zig @@ -45,7 +45,7 @@ pub fn openLink(url: []const u8) void { if (pid < 0) return; if (pid == 0) { if (libc.fork() == 0) { - @import("host_io.zig").resetChildSignals(); + @import("dev").host_io.resetChildSignals(); const argv: [3:null]?[*:0]const u8 = .{ opener, url_z.ptr, null }; _ = execv(opener, &argv); } diff --git a/src/lsp/Scip.zig b/src/lsp/Scip.zig deleted file mode 100644 index 540ba5cd..00000000 --- a/src/lsp/Scip.zig +++ /dev/null @@ -1,357 +0,0 @@ -//! A repository's code intelligence, read from its `index.scip` (SCIP, -//! scip-code.org; the schema is scip.proto in sourcegraph/scip): the -//! language words ask it first and the language server when it has -//! nothing to say (lsp_client.zig). An indexer writes it at the project's -//! root (the Index word runs one); the nearest above a file's directory -//! answers for the file. It is read on the first question that wants it, -//! on the query's worker, off the typing path, and again once it changes. -//! -//! Kept: each document's path, position encoding and occurrences (range, -//! symbol, roles, the enclosing node's range), the symbols interned with -//! their occurrences listed by symbol, and the bytes of each symbol's -//! information, read again when a word wants its documentation, signature, -//! kind or relationships. Skipped: the metadata (paths resolve against -//! the index's own directory), external symbols, syntax kinds, an -//! occurrence's diagnostics and a document's text. -const std = @import("std"); -const statPath = @import("../fs.zig").statPath; - -/// Agave's workspace index is 104 MiB; leave room for it and its lookup tables. -/// A bigger index is refused, in words. -pub const max_bytes = 512 << 20; -const tables_bytes = 512 << 20; -/// Indexes kept loaded at once, the one asked least recently replaced. -const kept = 2; - -pub const Range = struct { sl: u32 = 0, sc: u32 = 0, el: u32 = 0, ec: u32 = 0 }; -/// What a document's characters count (its `position_encoding`). -pub const Enc = enum { utf8, utf16, utf32 }; -/// An occurrence's role bit (scip.proto SymbolRole) for a definition. -pub const role_definition = 1; - -pub const Occurrence = struct { - range: Range, - /// The node a definition names, a function's signature and body, when - /// the indexer gave it; empty otherwise. - enclosing: Range, - symbol: u32, - doc: u32, - roles: u32, -}; - -pub const Document = struct { path: []const u8, enc: Enc, first: u32, len: u32 }; - -pub const Index = struct { - path_buf: [4096]u8 = undefined, - path_len: usize = 0, - mtime: i96 = 0, - size: u64 = 0, - used: u64 = 0, - /// A document newer than the index has been said once. - stale_said: bool = false, - documents: []Document = &.{}, - occurrences: []Occurrence = &.{}, - /// By symbol id: its string, its information's bytes (empty for one - /// defined in no document here), and its occurrences, - /// `order[starts[id]..starts[id + 1]]`. - symbols: std.ArrayList([]const u8) = .empty, - infos: std.ArrayList([]const u8) = .empty, - starts: []u32 = &.{}, - order: []u32 = &.{}, - ids: std.StringHashMapUnmanaged(u32) = .empty, - - pub fn path(ix: *const Index) []const u8 { - return ix.path_buf[0..ix.path_len]; - } - - pub fn root(ix: *const Index) []const u8 { - return std.Io.Dir.path.dirname(ix.path()) orelse "/"; - } - - /// The document of the file at `abs`, or null. - pub fn document(ix: *const Index, abs: []const u8) ?u32 { - const r = ix.root(); - if (abs.len <= r.len + 1 or !std.mem.startsWith(u8, abs, r) or abs[r.len] != '/') return null; - for (ix.documents, 0..) |d, i| if (std.mem.eql(u8, d.path, abs[r.len + 1 ..])) return @intCast(i); - return null; - } - - /// The innermost occurrence of `doc` at (line, ch), counted in the - /// document's units; one ending at the cursor counts. - pub fn at(ix: *const Index, doc: u32, line: u32, ch: u32) ?u32 { - const d = ix.documents[doc]; - var best: ?u32 = null; - for (d.first..d.first + d.len) |i| { - const r = ix.occurrences[i].range; - if (!holds(r, .{ .sl = line, .sc = ch, .el = line, .ec = ch })) continue; - if (best == null or holds(ix.occurrences[best.?].range, r)) best = @intCast(i); - } - return best; - } - - /// Whether the file at `abs` changed after the index was written. - pub fn stale(ix: *const Index, io: std.Io, abs: []const u8) bool { - const st = statPath(io, abs, .{}) catch return false; - return st.mtime.nanoseconds > ix.mtime; - } - - pub fn of(ix: *const Index, symbol: u32) []const u32 { - return ix.order[ix.starts[symbol]..ix.starts[symbol + 1]]; - } - - /// The definition whose node holds occurrence `o`, the innermost, of a - /// function-like symbol: where the call `o` is made from. - pub fn enclosingDefinition(ix: *const Index, o: u32) ?u32 { - const d = ix.documents[ix.occurrences[o].doc]; - var best: ?u32 = null; - for (d.first..d.first + d.len) |i| { - const def = ix.occurrences[i]; - if (i == o or def.roles & role_definition == 0 or !holds(def.enclosing, ix.occurrences[o].range)) continue; - if (!callable(ix.infos.items[def.symbol])) continue; - if (best == null or holds(ix.occurrences[best.?].enclosing, def.enclosing)) best = @intCast(i); - } - return best; - } -}; - -/// Whether `outer` holds `inner`, its ends included. -pub fn holds(outer: Range, inner: Range) bool { - const starts_before = outer.sl < inner.sl or (outer.sl == inner.sl and outer.sc <= inner.sc); - const ends_after = outer.el > inner.el or (outer.el == inner.el and outer.ec >= inner.ec); - return starts_before and ends_after and (outer.sl != outer.el or outer.sc != outer.ec); -} - -/// A symbol information's kind (5) is a function's or a method's. -pub fn callable(info: []const u8) bool { - const kind = (field(info, 5) orelse return false).int; - return switch (kind) { - 9, 17, 18, 25, 26, 45, 47, 66...72, 74, 76, 80 => true, - else => false, - }; -} - -// ------------------------------------------------------------------ the wire - -/// One field of a Protobuf message: its number, and its varint or its -/// length-delimited bytes (fixed 32- and 64-bit ones are skipped whole). -pub const Field = struct { num: u64, int: u64 = 0, bytes: []const u8 = "" }; - -pub const Reader = struct { - bytes: []const u8, - at: usize = 0, - - pub fn varint(r: *Reader) error{Malformed}!u64 { - var n: u64 = 0; - var shift: u7 = 0; - while (r.at < r.bytes.len and shift < 64) : (shift += 7) { - const b = r.bytes[r.at]; - r.at += 1; - n |= @as(u64, b & 0x7f) << @intCast(shift); - if (b < 0x80) return n; - } - return error.Malformed; - } - - pub fn next(r: *Reader) error{Malformed}!?Field { - if (r.at == r.bytes.len) return null; - const key = try r.varint(); - var f: Field = .{ .num = key >> 3 }; - switch (key & 7) { - 0 => f.int = try r.varint(), - 1 => r.at += 8, - 5 => r.at += 4, - 2 => { - const len = try r.varint(); - if (len > r.bytes.len - r.at) return error.Malformed; - f.bytes = r.bytes[r.at..][0..@intCast(len)]; - r.at += @intCast(len); - }, - else => return error.Malformed, - } - if (r.at > r.bytes.len) return error.Malformed; - return f; - } -}; - -/// The first field `num` of a message. -pub fn field(msg: []const u8, num: u64) ?Field { - var r: Reader = .{ .bytes = msg }; - while (r.next() catch return null) |f| if (f.num == num) return f; - return null; -} - -/// A range written as packed varints, `[line, start, end]` or `[line, -/// start, end line, end]`, or as a SingleLineRange or MultiLineRange -/// message (`typed`), its zeros left out. -fn rangeOf(bytes: []const u8, typed: enum { packed_ints, single, multi }) error{Malformed}!Range { - var v: [4]u32 = @splat(0); - var n: usize = 0; - var r: Reader = .{ .bytes = bytes }; - if (typed == .packed_ints) { - while (r.at < bytes.len and n < 4) : (n += 1) v[n] = @truncate(try r.varint()); - if (n == 3) return .{ .sl = v[0], .sc = v[1], .el = v[0], .ec = v[2] }; - if (n != 4) return error.Malformed; - } else while (try r.next()) |f| if (f.num >= 1 and f.num <= 4) { - v[f.num - 1] = @truncate(f.int); - }; - if (typed == .single) return .{ .sl = v[0], .sc = v[1], .el = v[0], .ec = v[2] }; - return .{ .sl = v[0], .sc = v[1], .el = v[2], .ec = v[3] }; -} - -// ------------------------------------------------------------------ loading - -// Keep the large bounded regions out of the executable's static address range. -var regions: [kept]?[]u8 = @splat(null); -var slots: [kept]Index = @splat(.{}); -var clock: u64 = 0; - -pub const Error = error{ TooBig, Malformed, Unreadable, OutOfMemory }; - -/// The index for a file in `dir`: the nearest `index.scip` there or up to -/// seven directories above, read again when it changed since; null with -/// none. -pub fn find(io: std.Io, dir: []const u8) Error!?*Index { - var buf: [4096]u8 = undefined; - var d = dir; - for (0..8) |_| { - const p = std.fmt.bufPrint(&buf, "{s}/index.scip", .{if (std.mem.eql(u8, d, "/")) "" else d}) catch return null; - if (statPath(io, p, .{})) |st| return try use(io, p, st) else |_| {} - d = std.Io.Dir.path.dirname(d) orelse return null; - } - return null; -} - -fn use(io: std.Io, p: []const u8, st: std.Io.File.Stat) Error!*Index { - clock += 1; - var pick: usize = 0; - for (&slots, 0..) |*ix, i| { - if (std.mem.eql(u8, ix.path(), p) and ix.mtime == st.mtime.nanoseconds and ix.size == st.size) { - ix.used = clock; - return ix; - } - if (ix.used < slots[pick].used) pick = i; - } - if (st.size > max_bytes) return error.TooBig; - const ix = &slots[pick]; - ix.* = .{ .mtime = st.mtime.nanoseconds, .size = st.size, .used = clock, .path_len = p.len }; - @memcpy(ix.path_buf[0..p.len], p); - errdefer ix.* = .{}; - const region = regions[pick] orelse blk: { - const memory = try std.heap.page_allocator.alloc(u8, max_bytes + tables_bytes); - regions[pick] = memory; - break :blk memory; - }; - const file = std.Io.Dir.cwd().openFile(io, p, .{}) catch return error.Unreadable; - defer file.close(io); - const got = file.readPositionalAll(io, region[0..@intCast(st.size)], 0) catch return error.Unreadable; - var fba: std.heap.FixedBufferAllocator = .init(region[max_bytes..]); - parse(ix, region[0..got], fba.allocator()) catch |e| return if (e == error.OutOfMemory) error.TooBig else error.Malformed; - return ix; -} - -/// Two walks over the documents: one counts them and their occurrences, -/// the other fills the tables sized from the counts. -fn parse(ix: *Index, bytes: []const u8, a: std.mem.Allocator) !void { - var docs: usize = 0; - var occs: usize = 0; - var r: Reader = .{ .bytes = bytes }; - while (try r.next()) |f| if (f.num == 2) { - docs += 1; - var d: Reader = .{ .bytes = f.bytes }; - while (try d.next()) |g| occs += @intFromBool(g.num == 2); - }; - ix.documents = try a.alloc(Document, docs); - ix.occurrences = try a.alloc(Occurrence, occs); - occs = 0; - docs = 0; - r = .{ .bytes = bytes }; - while (try r.next()) |f| if (f.num == 2) { - const doc = &ix.documents[docs]; - doc.* = .{ .path = "", .enc = .utf8, .first = @intCast(occs), .len = 0 }; - var d: Reader = .{ .bytes = f.bytes }; - while (try d.next()) |g| switch (g.num) { - 1 => doc.path = g.bytes, - 2 => { - const o = &ix.occurrences[occs]; - o.* = .{ .range = .{}, .enclosing = .{}, .symbol = 0, .doc = @intCast(docs), .roles = 0 }; - var name: []const u8 = ""; - var e: Reader = .{ .bytes = g.bytes }; - while (try e.next()) |h| switch (h.num) { - 1 => o.range = try rangeOf(h.bytes, .packed_ints), - 2 => name = h.bytes, - 3 => o.roles = @truncate(h.int), - 7 => o.enclosing = try rangeOf(h.bytes, .packed_ints), - 8, 10 => (if (h.num == 8) &o.range else &o.enclosing).* = try rangeOf(h.bytes, .single), - 9, 11 => (if (h.num == 9) &o.range else &o.enclosing).* = try rangeOf(h.bytes, .multi), - else => {}, - }; - o.symbol = try intern(ix, a, name, docs); - occs += 1; - }, - 3 => if (field(g.bytes, 1)) |s| { - const id = try intern(ix, a, s.bytes, docs); - ix.infos.items[id] = g.bytes; - }, - 6 => doc.enc = switch (g.int) { - 2 => .utf16, - 3 => .utf32, - else => .utf8, - }, - else => {}, - }; - doc.len = @intCast(occs - doc.first); - docs += 1; - }; - // The occurrences listed by symbol: counted, the counts summed, filled. - ix.starts = try a.alloc(u32, ix.symbols.items.len + 1); - @memset(ix.starts, 0); - for (ix.occurrences) |o| ix.starts[o.symbol + 1] += 1; - for (1..ix.starts.len) |i| ix.starts[i] += ix.starts[i - 1]; - ix.order = try a.alloc(u32, ix.occurrences.len); - const filled = try a.alloc(u32, ix.symbols.items.len); - @memset(filled, 0); - for (ix.occurrences, 0..) |o, i| { - ix.order[ix.starts[o.symbol] + filled[o.symbol]] = @intCast(i); - filled[o.symbol] += 1; - } -} - -/// A symbol's id, a `local N` one's in its document alone (its key is the -/// document's number and the name), the first time it is met a new one. -fn intern(ix: *Index, a: std.mem.Allocator, name: []const u8, doc: usize) !u32 { - var buf: [64]u8 = undefined; - const local = std.mem.startsWith(u8, name, "local "); - const key = if (local) std.fmt.bufPrint(&buf, "{d} {s}", .{ doc, name }) catch return error.Malformed else name; - const got = try ix.ids.getOrPut(a, key); - if (!got.found_existing) { - if (local) got.key_ptr.* = try a.dupe(u8, key); - got.value_ptr.* = @intCast(ix.symbols.items.len); - try ix.symbols.append(a, name); - try ix.infos.append(a, ""); - } - return got.value_ptr.*; -} - -test "a varint and every wire type a reader skips" { - var r: Reader = .{ .bytes = &.{ 0xac, 0x02 } }; - try std.testing.expectEqual(@as(u64, 300), try r.varint()); - // field 1 varint 7, field 2 fixed64, field 3 bytes "hi", field 4 fixed32, field 5 varint 1 - const msg = [_]u8{ 0x08, 0x07, 0x11 } ++ @as([8]u8, @splat(9)) ++ [_]u8{ 0x1a, 0x02, 'h', 'i', 0x25 } ++ @as([4]u8, @splat(9)) ++ [_]u8{ 0x28, 0x01 }; - try std.testing.expectEqual(@as(u64, 7), field(&msg, 1).?.int); - try std.testing.expectEqualStrings("hi", field(&msg, 3).?.bytes); - try std.testing.expectEqual(@as(u64, 1), field(&msg, 5).?.int); - try std.testing.expect(field(&msg, 6) == null); - // cut short, an unknown wire type, a length past the end - for ([_][]const u8{ &.{0x80}, &.{ 0x0b, 0x00 }, &.{ 0x1a, 0x05, 'h' } }) |bad| { - var b: Reader = .{ .bytes = bad }; - try std.testing.expectError(error.Malformed, b.next()); - } -} - -test "ranges in the packed form and the typed ones, zeros left out" { - try std.testing.expectEqual(Range{ .sl = 3, .sc = 4, .el = 3, .ec = 7 }, try rangeOf(&.{ 3, 4, 7 }, .packed_ints)); - try std.testing.expectEqual(Range{ .sl = 1, .sc = 0, .el = 2, .ec = 5 }, try rangeOf(&.{ 1, 0, 2, 5 }, .packed_ints)); - try std.testing.expectEqual(Range{ .sl = 0, .sc = 0, .el = 0, .ec = 3 }, try rangeOf(&.{ 0x18, 3 }, .single)); - try std.testing.expectEqual(Range{ .sl = 2, .sc = 0, .el = 4, .ec = 1 }, try rangeOf(&.{ 0x08, 2, 0x18, 4, 0x20, 1 }, .multi)); - try std.testing.expectError(error.Malformed, rangeOf(&.{ 1, 2 }, .packed_ints)); -} diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 3f8fcde3..7a636f72 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -82,7 +82,7 @@ pub fn explaining(req: Req) Req { /// Every language, Zig's (zls) included, through the protocol client, which /// runs its server as a child process. -const client = @import("lsp_client.zig"); +const client = @import("dev").lsp_client; pub const supports: std.EnumSet(Kind) = client.supports; diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig deleted file mode 100644 index 097bddf2..00000000 --- a/src/lsp/lsp_client.zig +++ /dev/null @@ -1,3183 +0,0 @@ -//! A real Language Server Protocol client: child processes spoken to over -//! JSON-RPC 2.0 with `Content-Length` framing. Nothing here knows any single -//! language — `specs` is a table of (binary, languageId, extensions, root -//! markers), and zls, rust-analyzer, clangd and gopls are rows in it: every -//! language pardes answers questions about. -//! -//! THE PROCESS LIFECYCLE IS THE DESIGN. `lsp.query` is a synchronous call on a -//! worker thread, and a language server costs tens of milliseconds to start -//! and MINUTES to index a large workspace. So a server is spawned lazily on -//! the first query that needs it, kept for the life of the editor, and each -//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` -//! because a canceled query can still be inside `run` when the next arrives. -//! Every wait is an `Io` cancelation point: a shell cancels the worker of a -//! query it no longer wants, and the worker stops there. -//! -//! ONE READER THREAD PER SERVER, and it is not optional. The first design -//! pumped the socket only while a query waited, which works for a server that -//! only ever answers. A real server TALKS: rust-analyzer streams `$/progress` -//! for the whole minutes-long index of a big workspace, publishes diagnostics -//! it was never asked for, and asks its own `workspace/configuration` -//! questions mid-flight. The reader owns the read side of the socket, routes -//! responses to the one waiting query (a mailbox under the conn's mutex), -//! answers server-to-client requests so the server never blocks on us, feeds -//! the diagnostics store, and narrates state changes through `status sink` — -//! the shell posts them to `Pardes.setMessage`, so "rust-analyzer indexing 45%" -//! lands on the same transient message row a save narrates into. The reader is -//! also the ONLY closer of its socket fd: teardown calls `shutdown(2)` and the -//! reader closes on the EOF it then reads, so the fd number cannot be recycled -//! under a thread still polling it. -//! -//! Nothing here may wedge the editor: -//! - every write is bounded by a deadline, and every mailbox wait by a -//! deadline or, while the server narrates progress, by cancelation, -//! - a query the server does not answer in time returns no rows and sends -//! `$/cancelRequest`; the server is NOT killed for being busy (an indexing -//! server is busy for minutes and the status row says so) — but three -//! consecutive timeouts mean wedged, and wedged is killed and respawned, -//! - the transport is an AF_UNIX socketpair, so a dead server answers EPIPE -//! from `send(MSG_NOSIGNAL)` instead of killing pardes with SIGPIPE -//! (ignoring SIGPIPE process-wide would be inherited by every pty shell we -//! fork and would change what `yes | head` does in a pane), -//! - a binary missing from PATH costs one cached probe, disables the spec -//! for the session, and says so ONCE on the message row. -//! -//! Position encoding is negotiated to utf-8 and the SERVER'S ANSWER is -//! believed, not our request; the utf-16 conversion is implemented in both -//! directions for servers that refuse (`Req.offset` is a byte offset, and a -//! misconverted column is wrong on every line with non-ASCII in it). -const std = @import("std"); -const builtin = @import("builtin"); -const libc = std.c; -const lsp = @import("lsp.zig"); -const Scip = @import("Scip.zig"); - -extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn usleep(usec: c_uint) c_int; -extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; -// test-only libc (the seam's own tests build a real directory tree) -extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; -extern "c" fn system(cmd: [*:0]const u8) c_int; - -/// darwin has no MSG_NOSIGNAL and gets SO_NOSIGPIPE on the socket instead, -/// set right after socketpair. -const msg_nosignal = if (builtin.os.tag.isDarwin()) 0 else libc.MSG.NOSIGNAL; - -/// One language server this client knows how to run. Adding a language is -/// adding a row; nothing below the table branches on a language. -const Spec = struct { - /// what the message row and `SPC l i` call it - name: []const u8, - /// argv[0], searched on PATH unless it contains a slash - bin: []const u8, - args: []const []const u8 = &.{}, - /// the protocol's `languageId` for didOpen - lang: []const u8, - /// extensions that route a file here (the seam asks `speaks`) - exts: []const []const u8, - /// project markers, walked UP from the file: the TOP-MOST directory - /// holding one is the root (helix's find_root rule), `.git` the fallback - markers: []const []const u8, - /// environment override: a binary path/name to use instead of `bin`, or - /// empty ("") to disable the spec entirely. How the snapshot harness pins - /// a deterministic mock server, and how a user points at a custom build. - env: [:0]const u8, - /// The command that writes the language's `index.scip` at the project - /// root (Scip.zig), which the Index word runs there; `PARDES_SCIP_*` - /// (the env's language) names another. - indexer: []const u8, -}; - -/// Each spec's indexer override, `PARDES_SCIP_RS` beside `PARDES_LSP_RS`. -const indexer_envs = blk: { - var names: [specs.len][:0]const u8 = undefined; - for (specs, &names) |spec, *name| name.* = "PARDES_SCIP_" ++ spec.env["PARDES_LSP_".len..]; - break :blk names; -}; - -pub const specs = [_]Spec{ - .{ - .name = "zls", - .bin = "zls", - .lang = "zig", - .exts = &.{".zig"}, - .markers = &.{ "build.zig", "build.zig.zon" }, - .env = "PARDES_LSP_ZIG", - .indexer = "scip-zig", - }, - .{ - .name = "rust-analyzer", - .bin = "rust-analyzer", - .lang = "rust", - .exts = &.{".rs"}, - .markers = &.{ "Cargo.toml", "rust-project.json" }, - .env = "PARDES_LSP_RS", - .indexer = "rust-analyzer scip .", - }, - .{ - .name = "clangd", - .bin = "clangd", - .lang = "c", - .exts = &.{ ".c", ".h", ".cc", ".cpp", ".hpp", ".cxx", ".hxx" }, - .markers = &.{ "compile_commands.json", "compile_flags.txt", ".clangd" }, - .env = "PARDES_LSP_C", - .indexer = "scip-clang", - }, - .{ - .name = "gopls", - .bin = "gopls", - .lang = "go", - .exts = &.{".go"}, - .markers = &.{ "go.mod", "go.work" }, - .env = "PARDES_LSP_GO", - .indexer = "scip-go", - }, - .{ - .name = "typescript-language-server", - .bin = "typescript-language-server", - .args = &.{"--stdio"}, - .lang = "typescript", - .exts = &.{ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs" }, - .markers = &.{ "tsconfig.json", "jsconfig.json", "package.json" }, - .env = "PARDES_LSP_TS", - .indexer = "scip-typescript index", - }, - .{ - .name = "pyright", - .bin = "pyright-langserver", - .args = &.{"--stdio"}, - .lang = "python", - .exts = &.{".py"}, - .markers = &.{ "pyproject.toml", "setup.py", "requirements.txt" }, - .env = "PARDES_LSP_PY", - .indexer = "scip-python index .", - }, -}; - -/// Everything. Whether one SERVER can answer is a capability question -/// answered per connection; a kind its server never advertised simply returns -/// no rows, which the harness reports as CLAIMED-EMPTY per language — honest, -/// since the claim here is about the protocol, not about every server. -pub const supports: std.EnumSet(lsp.Kind) = .full; - -/// Routing: an extension in the table whose spec is not disabled by its env -/// var. Deliberately does NOT probe for the binary — this runs on the Tab -/// keystroke. A missing binary is discovered at spawn, disables the spec, and -/// says so once on the message row; until then Tab in a `.rs` file diverts, -/// gets "no rows" instantly (the disabled flag short-circuits), and indents -/// late exactly like any other unanswerable completion. -pub fn speaks(path: []const u8) bool { - return specFor(path) != null; -} - -fn specFor(path: []const u8) ?usize { - for (&specs, 0..) |*s, i| { - for (s.exts) |e| { - if (!std.mem.endsWith(u8, path, e)) continue; - if (libc.getenv(s.env)) |v| if (v[0] == 0) return null; // "" disables - return i; - } - } - return null; -} - -// Deadlines. A shell cancels-and-joins the previous worker on a new query, -// and its waits are cancelation points: so a request needs no deadline to -// keep the editor responsive, and waits for its answer. Past req_ms the -// message row says the server is still at it; only a server silent and idle -// (no $/progress) for wedge_ms has failed to answer. Timeouts do NOT kill the -// server — an indexing rust-analyzer legitimately sits on a `gd` for minutes. -// The handshake runs protected from cancelation, so it keeps its deadline. -const init_ms = 8_000; // spawn + initialize handshake -const req_ms = 4_000; // a request past this is said to be still working -const wedge_ms = 300_000; // silent and idle this long: not answering (rust-analyzer takes ~1 min on `default`'s callers in agave) -const diag_ms = 1_200; // wait for a publishDiagnostics push after didChange -const reply_ms = 2_000; // our answers to server-to-client requests -const reply_queue_bytes = 64 << 10; // replies waiting for the socket (Conn.replies) -const parse_kept = 1 << 20; // what the reader's parse arena keeps between messages -const max_diag_files = 256; // files a server's pushed diagnostics are kept for -const max_diag_bytes = 32 << 20; // and their bytes -const wedged_strikes = 3; // consecutive timeouts before a restart - -/// Rows one answer may hold, and its writer's bytes: carved from the query's -/// fixed region (memory.limits.arena.lsp_query) with the rest of its memory. -const max_rows = 100_000; -/// What a Callstack walk leaves of its query's region for rendering the -/// tree it found: past this it stops and says so. -const callstack_reserve = 32 << 20; -/// What rendering leaves of the answer's writer for its closing line. -const row_room = 4096; -const max_doc_bytes = 8 << 20; - -const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed, Canceled }; - -/// Long-lived state outlives every query arena and cannot borrow the caller's -/// gpa (a different one shows up in the harness than in the shell), so -/// connections own their memory from the page allocator. -const sa = std.heap.page_allocator; - -/// Which units `character` counts in — see the header note on believing the -/// server. -const Enc = Scip.Enc; - -const Doc = struct { - uri: []u8, - version: u32, - /// content hash: a query whose buffer has not moved since the last one - /// sends no didChange at all, which is most of what makes warm queries fast - hash: u64, - /// a didChange the server has not answered with diagnostics yet - stale: bool = true, -}; - -/// The last publishDiagnostics per file, kept as raw params and re-parsed -/// against a query's arena. The accumulation IS workspace diagnostics for a -/// server with no pull support. -const DiagSet = struct { uri: []u8, body: []u8 }; - -/// The slice of server capabilities this client changes behaviour on. Silent -/// kinds (a server with no renameProvider) need no flag — the request errors -/// and errors render as no rows. These four either pick between two code -/// paths or gate a second round trip. -const Caps = struct { - enc: Enc = .utf16, - /// textDocument/diagnostic (LSP 3.17 pull) — preferred over the push store - pull: bool = false, - /// workspace/diagnostic - pull_workspace: bool = false, - call_hier: bool = false, - type_hier: bool = false, - /// workspace/didChangeWorkspaceFolders is worth sending - folders: bool = false, -}; - -const State = enum(u8) { - /// never spawned — the row every spec starts on - off, - /// spawned, initialize in flight - starting, - ready, - /// transport broke or the server was declared wedged; next query respawns - dead, - /// binary missing or two failed handshakes; stays down for the session - disabled, -}; - -const Conn = struct { - mu: std.Io.Mutex = .init, - cond: std.Io.Condition = .init, - /// Frames go out whole: a query's requests and the reader's replies - /// share the socket, and interleaved halves are a parse error that ends - /// the server. - write_mu: std.Io.Mutex = .init, - /// Replies the reader made while a query's write held the socket, sent - /// by that writer once its own message is out (releaseWrite): the reader - /// never waits to write, since a server blocked on its output reads - /// nothing more of ours. - /// Two halves: the reader appends to `replies[filling]`, and the writer - /// flips them and sends the other, with no copy and no wait. - replies: [2][reply_queue_bytes]u8 = undefined, - replies_len: [2]usize = .{ 0, 0 }, - filling: u1 = 0, - replies_mu: std.Io.Mutex = .init, - state: State = .off, - /// bumped per spawn. A reader thread that sees a different gen than its - /// own is reading a corpse and exits; a waiter that sees one stops waiting. - gen: u32 = 0, - handshake_fails: u8 = 0, - /// monotonic ms before which a dead/failed server is not respawned — - /// exponential backoff against forking a doomed child per keystroke - retry_after_ms: i64 = 0, - /// monotonic ms when the last handshake completed — a crash shortly - /// after "ready" counts as a handshake failure for backoff purposes - ready_at_ms: i64 = 0, - timeouts: u8 = 0, - pid: libc.pid_t = -1, - sock: c_int = -1, - next_id: u32 = 1, - caps: Caps = .{}, - /// the workspace root sent in initialize (sa-owned) - root: []u8 = &.{}, - /// roots added since, via didChangeWorkspaceFolders (sa-owned entries) - extra_roots: std.ArrayList([]u8) = .empty, - docs: std.ArrayList(Doc) = .empty, - diags: std.ArrayList(DiagSet) = .empty, - /// The bytes `diags` holds, kept under max_diag_bytes. - diag_bytes: usize = 0, - /// the response mailbox: one request outstanding per connection - want_id: u32 = 0, - resp: ?[]u8 = null, - /// active $/progress begins, and the last begin's title for report rows - progress: i32 = 0, - title: [48]u8 = @splat(0), - title_len: u8 = 0, - /// The server says it is still loading its workspace (rust-analyzer's - /// serverStatus, not quiescent): an empty answer now is not one. - loading: bool = false, - /// its index in `conns`, for what it posts - si: usize = 0, - - fn alive(c: *const Conn) bool { - return c.state == .starting or c.state == .ready; - } -}; - -var conns: [specs.len]Conn = @splat(.{}); - -// ------------------------------------------------------------- status sink - -/// One registered listener for unsolicited state changes; both native shells -/// register at startup and DEREGISTER before tearing their loop down — the -/// registry lock is held across the callback, so a null-ing shell cannot race -/// a reader thread mid-post. The callback must copy `text` before returning. -var sink_mu: std.atomic.Mutex = .unlocked; -var sink_ctx: ?*anyopaque = null; -var sink_cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null; -/// throttle for chatty progress reports, per spec -var sink_last_ms: [specs.len]i64 = @splat(0); -var sink_last_text: [specs.len][96]u8 = @splat(@splat(0)); -var sink_last_len: [specs.len]u8 = @splat(0); - -pub fn setStatusSink(ctx: ?*anyopaque, cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void) void { - while (!sink_mu.tryLock()) std.atomic.spinLoopHint(); - defer sink_mu.unlock(); - sink_ctx = ctx; - sink_cb = cb; -} - -const Chat = enum { - /// a progress report: at most one per 150ms per server, dropped when it - /// repeats the previous text — rust-analyzer emits thousands over a big - /// index and the message row repaints per post - chatty, - /// a state change: starting, ready, exited, errors. Always posted. - always, -}; - -fn post(si: usize, chat: Chat, comptime fmt: []const u8, args: anytype) void { - var buf: [192]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - w.print(fmt, args) catch {}; // a long one is cut at the row's end - const text = w.buffered(); - while (!sink_mu.tryLock()) std.atomic.spinLoopHint(); - defer sink_mu.unlock(); - const cb = sink_cb orelse return; - // Repeating the row that is already showing is never news, whatever the - // class — and it is what makes the FINAL state deterministic for the - // snapshot harness: however many intermediate reports the throttle let - // through, an `.always` end state lands exactly once. - const cut = @min(text.len, sink_last_text[si].len); - if (std.mem.eql(u8, text[0..cut], sink_last_text[si][0..sink_last_len[si]])) return; - if (chat == .chatty) { - const now = nowMs(); - if (now - sink_last_ms[si] < 150) return; - sink_last_ms[si] = now; - } - sink_last_len[si] = @intCast(cut); - @memcpy(sink_last_text[si][0..cut], text[0..cut]); - cb(sink_ctx, text); -} - -// ------------------------------------------------------------- introspection - -const LogEntry = struct { - used: bool = false, - kind: lsp.Kind = .definition, - spec: u8 = 0, - us: u64 = 0, - rows: usize = 0, - err: [24]u8 = @splat(0), - err_len: u8 = 0, - file: [64]u8 = @splat(0), - file_len: u8 = 0, -}; -const log_cap = 24; -var log_buf: [log_cap]LogEntry = @splat(.{}); -var log_next: usize = 0; -var log_total: u64 = 0; -var log_mu: std.atomic.Mutex = .unlocked; - -fn record(si: usize, req: lsp.Req, us: u64, rows: usize, err: []const u8) void { - while (!log_mu.tryLock()) std.atomic.spinLoopHint(); - defer log_mu.unlock(); - const e = &log_buf[log_next]; - e.* = .{ .used = true, .kind = req.kind, .spec = @intCast(si), .us = us, .rows = rows }; - const base = std.Io.Dir.path.basename(req.path); - e.file_len = @intCast(@min(base.len, e.file.len)); - @memcpy(e.file[0..e.file_len], base[0..e.file_len]); - e.err_len = @intCast(@min(err.len, e.err.len)); - @memcpy(e.err[0..e.err_len], err[0..e.err_len]); - log_next = (log_next + 1) % log_cap; - log_total += 1; -} - -fn hideTime() bool { - return @import("../Messages.zig").Message.noTime(); -} - -/// `SPC l w` narration, threaded through the real path, so it cannot -/// disagree with what `gd` actually did. -const Trace = struct { - on: bool = false, - buf: [16 * 1024]u8 = undefined, - len: usize = 0, - - fn note(t: *Trace, comptime fmt: []const u8, args: anytype) void { - if (!t.on or t.len == t.buf.len) return; - var w: std.Io.Writer = .fixed(t.buf[t.len..]); - w.print(fmt ++ "\n", args) catch {}; - t.len += w.buffered().len; - } -}; - -// ------------------------------------------------------------------- query - -/// What answered a logged query: a server, or `scip`, the index. -fn sourceName(spec: u8) []const u8 { - return if (spec < specs.len) specs[spec].name else "scip"; -} - -fn status(io: std.Io, path: []const u8, out: *std.Io.Writer) !void { - // The index the file would ask first, what it holds and how old it is. - const dir = std.Io.Dir.path.dirname(path) orelse "/"; - if (Scip.find(io, dir)) |found| if (found) |ix| { - var symbols: usize = 0; - for (ix.infos.items) |info| symbols += @intFromBool(info.len > 0); - var newer: usize = 0; - var pbuf: [4096]u8 = undefined; - for (ix.documents) |d| newer += @intFromBool(ix.stale(io, std.fmt.bufPrint(&pbuf, "{s}/{s}", .{ ix.root(), d.path }) catch continue)); - try out.print("scip: {s}, {d} KB, {d} documents, {d} symbols", .{ ix.path(), (ix.size + 999) / 1000, ix.documents.len, symbols }); - if (!hideTime()) { - const secs: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@divTrunc(ix.mtime, std.time.ns_per_s)) }; - const day = secs.getEpochDay().calculateYearDay(); - const md = day.calculateMonthDay(); - try out.print(", indexed {d}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} UTC", .{ day.year, md.month.numeric(), md.day_index + 1, secs.getDaySeconds().getHoursIntoDay(), secs.getDaySeconds().getMinutesIntoHour() }); - } - try out.print(", {d} files newer\n", .{newer}); - } else { - try out.print("scip: no index.scip above {s}", .{dir}); - if (specFor(path)) |si| try out.print("; Index runs {s}", .{if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer}); - try out.writeByte('\n'); - } else |e| try out.print("scip: index.scip above {s}: {s}\n", .{ dir, @errorName(e) }); - try out.print("language servers:\n", .{}); - for (&specs, 0..) |*s, i| { - const c = &conns[i]; - c.mu.lockUncancelable(io); - const state = c.state; - var rootbuf: [256]u8 = undefined; - const rootlen = @min(c.root.len, rootbuf.len); - @memcpy(rootbuf[0..rootlen], c.root[0..rootlen]); - const root = rootbuf[0..rootlen]; - const enc = c.caps.enc; - const ndocs = c.docs.items.len; - const ndiag = c.diags.items.len; - const pull = c.caps.pull; - const chier = c.caps.call_hier; - const thier = c.caps.type_hier; - c.mu.unlock(io); - const env_v = if (libc.getenv(s.env)) |v| std.mem.span(v) else null; - // Never spawned is not off: the first query of its files starts it. - try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) }); - if (state == .ready or state == .starting) { - try out.print(" root {s} {s}", .{ root, @tagName(enc) }); - if (pull) try out.print(" pull-diags", .{}); - if (chier) try out.print(" call-hier", .{}); - if (thier) try out.print(" type-hier", .{}); - try out.print(" docs {d} diag-files {d}", .{ ndocs, ndiag }); - } - if (env_v) |v| try out.print(" [{s}={s}]", .{ s.env, if (v.len == 0) "(disabled)" else v }); - try out.print("\n ", .{}); - for (s.exts) |e| try out.print("{s} ", .{e}); - try out.print("\n", .{}); - } - - while (!log_mu.tryLock()) std.atomic.spinLoopHint(); - defer log_mu.unlock(); - try out.print("\nclient queries ({d} total, keeping {d}):\n", .{ log_total, log_cap }); - var shown: usize = 0; - for (0..log_cap) |i| { - const e = &log_buf[(log_next + i) % log_cap]; - if (!e.used) continue; - shown += 1; - if (hideTime()) { - try out.print(" {s:<18} {s:<14} {s:<20} {d:>4} row(s){s}{s}\n", .{ - @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.rows, - if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], - }); - } else { - try out.print(" {s:<18} {s:<14} {s:<20} {d:>7}us {d:>4} row(s){s}{s}\n", .{ - @tagName(e.kind), sourceName(e.spec), e.file[0..e.file_len], e.us, e.rows, - if (e.err_len > 0) " ERROR " else "", e.err[0..e.err_len], - }); - } - } - if (shown == 0) try out.print(" (none yet — press gd in a file with a server, then ask again)\n", .{}); -} - -/// The Index word's command line: the language's indexer, at the -/// project's root, where the index it writes answers for every file under -/// it (`PARDES_SCIP_RS` and the like name another indexer). -fn indexCommand(req: lsp.Req, out: *std.Io.Writer) !void { - const si = specFor(req.path) orelse return lsp.none(out, "no indexer for {s}", .{std.Io.Dir.path.basename(req.path)}); - const cmd = if (libc.getenv(indexer_envs[si])) |v| std.mem.span(v) else specs[si].indexer; - try out.writeAll("@run cd '"); - for (rootOf(std.Io.Dir.path.dirname(req.path) orelse "/", specs[si].markers)) |ch| try if (ch == '\'') out.writeAll("'\\''") else out.writeByte(ch); - try out.print("' && {s}\n", .{cmd}); -} - -fn nowUs() u64 { - var ts: libc.timespec = undefined; - _ = libc.clock_gettime(.MONOTONIC, &ts); - return @as(u64, @intCast(ts.sec)) *| 1_000_000 +| @as(u64, @intCast(ts.nsec)) / 1000; -} - -/// Byte offset -> LSP position. `lsp.lineCol` gives the line and the BYTE -/// column; only the column needs re-counting, and only when the server -/// refused utf-8. -fn posOf(src: []const u8, off: u32, enc: Enc) Pos { - const lc = lsp.lineCol(src, off); - if (enc == .utf8) return .{ .line = @intCast(lc.line), .ch = @intCast(lc.col) }; - const bol = @min(off, src.len) - lc.col; - var units: u32 = 0; - var i: usize = bol; - while (i < bol + lc.col) { - const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; - units += if (l == 4 and enc == .utf16) 2 else 1; - i += l; - } - return .{ .line = @intCast(lc.line), .ch = units }; -} - -fn emitOcc(cx: *Cx, ix: *const Scip.Index, o: u32, note: []const u8) Err!void { - const occ = ix.occurrences[o]; - try emitPath(cx, ix.documents[occ.doc].enc, try indexPath(cx.arena, ix, occ.doc), occ.range, note); -} - -/// A symbol's definitions, as rows: named by the symbol, as a type -/// hierarchy's are, or by their source lines. -fn emitDefinitions(cx: *Cx, ix: *Scip.Index, symbol: u32, named: bool) Err!void { - for (ix.of(symbol)) |o| if (ix.occurrences[o].roles & Scip.role_definition != 0) { - const sig = if (Scip.field(ix.infos.items[symbol], 7)) |f| (Scip.field(f.bytes, 5) orelse Scip.Field{ .num = 0 }).bytes else ""; - const note = if (!named) "" else if (sig.len == 0) displayName(ix, symbol) else try std.fmt.allocPrint(cx.arena, "{s} {s}", .{ displayName(ix, symbol), flat(cx.arena, sig) }); - try emitOcc(cx, ix, o, note); - }; -} - -/// The symbols `symbol`'s relationships name with flag `flag` set -/// (scip.proto Relationship: 2 is_reference, 3 is_implementation, 4 -/// is_type_definition), the ones the index knows. -fn related(a: std.mem.Allocator, ix: *const Scip.Index, symbol: u32, flag: u64) Err![]u32 { - var out: std.ArrayList(u32) = .empty; - var r: Scip.Reader = .{ .bytes = ix.infos.items[symbol] }; - while (r.next() catch null) |f| if (f.num == 4) { - const to = Scip.field(f.bytes, 1) orelse continue; - if ((Scip.field(f.bytes, flag) orelse continue).int == 0) continue; - if (ix.ids.get(to.bytes)) |id| try out.append(a, id); - }; - return out.items; -} - -/// The index's answer (Scip.zig), in the rows the server's would make: true -/// when it had one, false to ask the server: no index above the file, a -/// file it does not hold, unsaved changes it has not seen, nothing at the -/// cursor, a symbol it does not know, or a word only a server answers. -fn fromIndex(io: std.Io, arena: std.mem.Allocator, req: lsp.Req, kind: lsp.Kind, out: *std.Io.Writer, tr: *Trace) Err!bool { - switch (kind) { - .definition, .type_definition, .implementation, .references, .select_refs, .hover, .document_symbols, .workspace_symbols, .incoming_calls, .outgoing_calls, .callstack, .supertypes, .subtypes => {}, - else => return false, - } - if (req.dirty) { - tr.note("unsaved changes the index has not seen: the server", .{}); - return false; - } - const dir = std.Io.Dir.path.dirname(req.path) orelse return false; - const ix = (Scip.find(io, dir) catch |e| { - tr.note("index.scip above {s}: {s}", .{ dir, @errorName(e) }); - return false; - }) orelse { - tr.note("no index.scip above {s}", .{dir}); - return false; - }; - const doc = ix.document(req.path) orelse { - tr.note("{s} holds no {s}", .{ ix.path(), std.Io.Dir.path.basename(req.path) }); - return false; - }; - const si = specFor(req.path) orelse 0; - if (ix.stale(io, req.path)) { - tr.note("stale: {s} is newer than the index", .{std.Io.Dir.path.basename(req.path)}); - if (!ix.stale_said) post(si, .always, "{s} is older than {s}: Index makes it again", .{ ix.path(), std.Io.Dir.path.basename(req.path) }); - ix.stale_said = true; - } - const enc = ix.documents[doc].enc; - var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = kind == .callstack }; - for (req.others) |d| try cx.files.append(arena, .{ .path = d.path, .text = d.source }); - if (kind == .document_symbols or kind == .workspace_symbols) { - for (ix.occurrences, 0..) |o, i| { - if (kind == .document_symbols and o.doc != doc) continue; - // A name, never a local or a whole file's module. - if (o.roles & Scip.role_definition == 0 or o.range.sl != o.range.el or std.mem.startsWith(u8, ix.symbols.items[o.symbol], "local ")) continue; - const name = displayName(ix, o.symbol); - if (kind == .workspace_symbols and std.ascii.findIgnoreCase(name, req.arg) == null) continue; - try emitOcc(&cx, ix, @intCast(i), name); - } - tr.note("<- {d} row(s) from the index", .{cx.rows}); - return cx.rows > 0; - } - const pos = posOf(req.source, req.offset, enc); - const at = ix.at(doc, pos.line, pos.ch) orelse { - tr.note("no occurrence at {d}:{d} in {s}", .{ pos.line + 1, pos.ch + 1, ix.path() }); - return false; - }; - const sym = ix.occurrences[at].symbol; - tr.note("{s}: occurrence '{s}' at {d}:{d}", .{ ix.path(), ix.symbols.items[sym], pos.line + 1, pos.ch + 1 }); - switch (kind) { - .definition => try emitDefinitions(&cx, ix, sym, false), - .type_definition => for (try related(arena, ix, sym, 4)) |to| try emitDefinitions(&cx, ix, to, false), - .supertypes => for (try related(arena, ix, sym, 3)) |to| try emitDefinitions(&cx, ix, to, true), - .implementation, .subtypes => for (ix.infos.items, 0..) |_, from| { - if (std.mem.indexOfScalar(u32, try related(arena, ix, @intCast(from), 3), sym) != null) - try emitDefinitions(&cx, ix, @intCast(from), kind == .subtypes); - }, - .references, .select_refs => { - var also = try related(arena, ix, sym, 2); - also = try std.mem.concat(arena, u32, &.{ &.{sym}, also }); - for (also) |of| for (ix.of(of)) |o| if (kind == .references or ix.occurrences[o].doc == doc) try emitOcc(&cx, ix, o, ""); - }, - .hover => { - const info = ix.infos.items[sym]; - var said = false; - if (Scip.field(info, 7)) |sig| if (Scip.field(sig.bytes, 5)) |text| { - try out.writeAll(std.mem.trim(u8, text.bytes, " \t\r\n")); - said = true; - }; - var r: Scip.Reader = .{ .bytes = info }; - while (r.next() catch null) |f| if (f.num == 3) { - if (said) try out.writeAll("\n\n"); - try out.writeAll(std.mem.trim(u8, f.bytes, " \t\r\n")); - said = true; - }; - if (said) try out.writeByte('\n') else tr.note("no documentation for it in the index", .{}); - return said; - }, - .incoming_calls => for (try indexHops(arena, ix, sym)) |hop| for (hop.sites.items) |site| - try emitPath(&cx, ix.documents[hop.doc].enc, try indexPath(arena, ix, hop.doc), site, hop.call.name), - .outgoing_calls => for (ix.of(sym)) |d| { - // The calls inside its definition, each function once, at its - // own definition. - const def = ix.occurrences[d]; - if (def.roles & Scip.role_definition == 0) continue; - var seen: std.ArrayList(u32) = .empty; - const in = ix.documents[def.doc]; - for (ix.occurrences[in.first..][0..in.len]) |o| { - if (o.roles & Scip.role_definition != 0 or !Scip.holds(def.enclosing, o.range) or !Scip.callable(ix.infos.items[o.symbol])) continue; - if (std.mem.indexOfScalar(u32, seen.items, o.symbol) != null) continue; - try seen.append(arena, o.symbol); - try emitDefinitions(&cx, ix, o.symbol, true); - } - break; - }, - .callstack => { - const def = for (ix.of(sym)) |o| { - if (ix.occurrences[o].roles & Scip.role_definition != 0) break ix.occurrences[o]; - } else { - tr.note("no definition of it in the index", .{}); - return false; - }; - // The rows come from the tree alone: the core reads the sources. - cx.no_text = true; - const focus: CallTree.Call = .{ .uri = try indexUri(arena, ix, def.doc), .name = "", .at = def.range }; - try callTree(.{ .index = ix }, si, &cx, enc, focus, try indexHops(arena, ix, sym), tr, req.callstack_depth, req.budget); - return true; - }, - else => unreachable, - } - tr.note("<- {d} row(s) from the index", .{cx.rows}); - return cx.rows > 0; -} - -pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) Err!void { - const req = lsp.explaining(asked); - if (req.kind == .status) return status(io, req.path, out); - if (req.kind == .index) return indexCommand(req, out); - - var tr: Trace = .{ .on = req.kind == .explain }; - // Raw: `alloc` fills a safe build's new memory, all 51 MB of it, per query. - const scratch_buf = (arena.rawAlloc(max_rows * 512, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0 .. max_rows * 512]; - var scratch: std.Io.Writer = .fixed(scratch_buf); - - // The index first: what it answers wants no server. - const t0 = nowUs(); - if (fromIndex(io, arena, req, if (req.kind == .explain) req.explains else req.kind, &scratch, &tr) catch |e| blk: { - tr.note("index: {s}", .{@errorName(e)}); - break :blk false; - }) { - const us = nowUs() -| t0; - const rows = std.mem.count(u8, scratch.buffered(), "\n"); - record(specs.len, req, us, rows, ""); - if (req.kind == .explain) return traceOut(&tr, req, out, rows, us); - return out.writeAll(scratch.buffered()); - } - scratch.end = 0; - const si = specFor(req.path) orelse { - tr.note("STOP: no language server spec matches {s}", .{ - if (req.path.len == 0) "a pane with no file" else req.path, - }); - if (req.kind != .explain) return lsp.none(out, "no language server for {s}", .{if (req.path.len == 0) "a pane with no file" else std.Io.Dir.path.basename(req.path)}); - return traceOut(&tr, req, out, 0, 0); - }; - tr.note("file {s} -> {s} (languageId {s})", .{ std.Io.Dir.path.basename(req.path), specs[si].name, specs[si].lang }); - - const t1 = nowUs(); - var err_name: []const u8 = ""; - var failure: ?Err = null; - answer(io, arena, si, req, &scratch, &tr) catch |e| { - failure = e; - err_name = @errorName(e); - tr.note("ERROR: {s}", .{err_name}); - }; - const us = nowUs() -| t1; - const rows = std.mem.count(u8, scratch.buffered(), "\n"); - record(si, req, us, rows, err_name); - - if (req.kind == .explain) return traceOut(&tr, req, out, rows, us); - // No server to start for the language: said, not "did not answer". - if (failure) |err| if (err == error.NoServer) return lsp.none(out, "language server for {s} not found", .{std.Io.Dir.path.extension(req.path)}); - // Installed, but it failed a moment ago: said so, and when it is tried - // again, not that it is not there. - if (failure) |err| if (err == error.Backoff) { - const c = &conns[si]; - c.mu.lockUncancelable(io); - const left_ms = c.retry_after_ms -| nowMs(); - c.mu.unlock(io); - return lsp.none(out, "{s} failed recently; retry in {d}s", .{ specs[si].name, @divFloor(left_ms + 999, 1000) }); - }; - if (failure) |err| return err; - try out.writeAll(scratch.buffered()); -} - -fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us: u64) std.Io.Writer.Error!void { - if (req.kind != .explain) return; - try out.print("lsp explain — the {s} query at byte {d} of {s}\n\n", .{ - @tagName(req.explains), req.offset, if (req.path.len == 0) "(no file)" else std.Io.Dir.path.basename(req.path), - }); - try out.writeAll(tr.buf[0..tr.len]); - if (hideTime()) - try out.print("\n{d} row(s)\n", .{rows}) - else - try out.print("\n{d} row(s) in {d}us\n", .{ rows, us }); -} - -fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { - const c = &conns[si]; - try c.mu.lock(io); - defer c.mu.unlock(io); - const g = try ensure(c, io, si, arena, req, tr); - const before = out.end; - try attempt(c, io, si, arena, req, out, tr, g); - // An empty answer can beat the startup progress notification onto the wire. - const answered = out.buffered()[before..]; - if (c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) { - const startup_deadline = c.ready_at_ms + 250; - const starting = nowMs() < startup_deadline; - while (starting and !c.loading and c.progress == 0 and c.gen == g and c.alive()) { - if (!try timedWait(c, io, startup_deadline)) break; - } - if (starting or c.loading or c.progress > 0) { - tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); - post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); - while ((c.loading or c.progress > 0) and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); - out.end = before; - try attempt(c, io, si, arena, req, out, tr, g); - } - } -} - -/// One run of a query, and what its failure says of the server. -fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace, g: u32) Err!void { - run(c, io, si, arena, req, out, tr) catch |e| { - switch (e) { - // transport-level: this server is gone; forget it, and the next - // query respawns. Gen-checked so a respawn that happened while we - // waited is not the one we kill. - error.Dead, error.Protocol => shutdownIf(c, io, g), - error.Timeout => { - // Slow is only wedged when the server is IDLE. One with - // active `$/progress` work (rust-analyzer running cargo - // check over a thousand crates) is demonstrably alive, is - // narrating its own excuse on the message row, and killing - // it would throw the index away right before it pays off. - if (c.progress > 0) { - c.timeouts = 0; - } else { - c.timeouts +|= 1; - if (c.timeouts >= wedged_strikes and c.gen == g) { - post(si, .always, "{s} not answering — restarting", .{specs[si].name}); - shutdownIf(c, io, g); - } - } - }, - // Canceled: the shell asked something newer, not a wedged server. - error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed, error.Canceled => {}, - } - return e; - }; - c.timeouts = 0; -} - -/// didOpen the first time a file is seen, didChange when its bytes moved, -/// nothing when they did not — the common case between two presses of gd. -fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { - const hash = std.hash.Wyhash.hash(0, src); - var doc: ?*Doc = null; - for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { - doc = d; - break; - }; - if (doc) |d| if (d.hash == hash) return; - - var b: std.ArrayList(u8) = .empty; - if (doc) |d| { - d.version += 1; - d.hash = hash; - d.stale = true; - try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didChange\",\"params\":{{\"textDocument\":{{\"uri\":", .{}); - try jstr(&b, arena, uri); - try b.print(arena, ",\"version\":{d}}},\"contentChanges\":[{{\"text\":", .{d.version}); - try jstr(&b, arena, src); - try b.appendSlice(arena, "}]}}"); - } else { - if (c.docs.items.len >= 256) return; // a session does not open this many - const owned = try sa.dupe(u8, uri); - c.docs.append(sa, .{ .uri = owned, .version = 1, .hash = hash }) catch { - sa.free(owned); - return error.OutOfMemory; - }; - try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"textDocument\":{\"uri\":"); - try jstr(&b, arena, uri); - try b.print(arena, ",\"languageId\":\"{s}\",\"version\":1,\"text\":", .{specs[si].lang}); - try jstr(&b, arena, src); - try b.appendSlice(arena, "}}}"); - } - // A server busy with what it was sent last reads no more meanwhile - // (clangd parses its compile database at a first open): this waits as - // an answer does, for a cancel or a server that has stopped. - try send(c, io, b.items, nowMs() + wedge_ms); -} - -/// The current-buffer byte column for a (line, ch) position — used only for -/// rows that point at the asking position itself. -fn byteCol(src: []const u8, line: u32, ch: u32, enc: Enc) usize { - var bol: usize = 0; - var n: u32 = 0; - while (n < line) : (n += 1) - bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return ch) + 1; - const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; - return colBytes(src[bol..eol], ch, enc); -} - -fn hierText(arena: std.mem.Allocator, item: std.json.Value) []const u8 { - const name = str(get(item, "name")) orelse ""; - const detail = str(get(item, "detail")) orelse return name; - return std.fmt.allocPrint(arena, "{s} {s}", .{ name, flat(arena, detail) }) catch name; -} - -/// The two-step hierarchy kinds: prepare at the cursor, then follow every -/// item the server returned (usually one). Gated on the server capability so -/// an old server costs zero round trips. -fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { - const call_side = h == .incoming or h == .outgoing; - if (call_side and !c.caps.call_hier) { - tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); - return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); - } - if (!call_side and !c.caps.type_hier) { - tr.note("STOP: {s} does not advertise typeHierarchyProvider", .{specs[si].name}); - return lsp.none(cx.out, "{s} does not answer type hierarchy (no typeHierarchyProvider)", .{specs[si].name}); - } - const prepare: []const u8 = if (call_side) "textDocument/prepareCallHierarchy" else "textDocument/prepareTypeHierarchy"; - const follow: []const u8 = switch (h) { - .incoming => "callHierarchy/incomingCalls", - .outgoing => "callHierarchy/outgoingCalls", - .supers => "typeHierarchy/supertypes", - .subs => "typeHierarchy/subtypes", - }; - const b = try atPos(arena, uri, pos); - const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; - for (items(prepared)) |item| { - const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; - for (items(result)) |entry| switch (h) { - .incoming => { - // one row per CALL SITE, under the caller's name — that is - // what n/N want to walk - const from = get(entry, "from") orelse continue; - const fu = str(get(from, "uri")) orelse continue; - const name = str(get(from, "name")) orelse ""; - const ranges = items(get(entry, "fromRanges")); - if (ranges.len == 0) { - try emitRange(cx, c.caps.enc, fu, get(from, "selectionRange"), name); - } else for (ranges) |r| try emitRange(cx, c.caps.enc, fu, r, name); - }, - .outgoing => { - const to = get(entry, "to") orelse continue; - try emitRange(cx, c.caps.enc, str(get(to, "uri")) orelse continue, get(to, "selectionRange") orelse get(to, "range"), hierText(cx.arena, to)); - }, - .supers, .subs => try emitRange(cx, c.caps.enc, str(get(entry, "uri")) orelse continue, get(entry, "selectionRange") orelse get(entry, "range"), hierText(cx.arena, entry)), - }; - } -} - -fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { - // `explain` narrates the last query asked (a definition, `gd`, when - // none was) — dispatch below on the effective kind so the trace - // follows the code that query really runs. - const kind: lsp.Kind = if (req.kind == .explain) req.explains else req.kind; - - // Both arg-taking kinds are useless without one, and an empty - // workspace/symbol query means "every symbol in the project". - if ((kind == .rename or kind == .workspace_symbols) and req.arg.len == 0) return; - - var uri: std.ArrayList(u8) = .empty; - try uriOf(&uri, arena, req.path); - try syncDoc(c, io, si, arena, uri.items, req.source); - // Every other open file this server answers for, before a query whose - // answer reaches them: zls renames only in the documents it has. - if (lsp.reachesOtherFiles(kind)) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path)) { - var other: std.ArrayList(u8) = .empty; - try uriOf(&other, arena, doc.path); - try syncDoc(c, io, si, arena, other.items, doc.source); - tr.note("synced {s} first", .{std.Io.Dir.path.basename(doc.path)}); - }; - - const pos = posOf(req.source, req.offset, c.caps.enc); - var cx: Cx = .{ .io = io, .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack }; - for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); - tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ - @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), - }); - const deadline = nowMs() + req_ms; - - switch (kind) { - .definition, .declaration, .type_definition, .implementation, .references => { - const method = switch (kind) { - .definition => "textDocument/definition", - .declaration => "textDocument/declaration", - .type_definition => "textDocument/typeDefinition", - .implementation => "textDocument/implementation", - else => "textDocument/references", - }; - var b = try atPos(arena, uri.items, pos); - if (kind == .references) try b.appendSlice(arena, ",\"context\":{\"includeDeclaration\":true}"); - tr.note("-> {s} @ {d}:{d}", .{ method, pos.line + 1, pos.ch + 1 }); - const result = (try call(c, io, arena, method, b.items, deadline)) orelse { - tr.note("<- empty (no result, an error response, or null)", .{}); - return; - }; - try locations(&cx, c.caps.enc, result); - tr.note("<- {d} row(s)", .{cx.rows}); - }, - .select_refs => { - const b = try atPos(arena, uri.items, pos); - const result = (try call(c, io, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; - for (items(result)) |h| try emitRange(&cx, c.caps.enc, uri.items, get(h, "range"), ""); - }, - .hover => { - const b = try atPos(arena, uri.items, pos); - const result = (try call(c, io, arena, "textDocument/hover", b.items, deadline)) orelse return; - const contents = get(result, "contents") orelse return; - const text = str(contents) orelse str(get(contents, "value")) orelse blk: { - for (items(contents)) |m| if (str(m) orelse str(get(m, "value"))) |t| break :blk t; - break :blk ""; - }; - if (text.len == 0) return; - try out.writeAll(std.mem.trim(u8, text, " \t\r\n")); - try out.writeByte('\n'); - }, - .document_symbols => { - const b = try docParams(arena, uri.items); - const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; - try walkSymbols(&cx, c.caps.enc, uri.items, result, 0); - }, - .workspace_symbols => { - var b: std.ArrayList(u8) = .empty; - try b.appendSlice(arena, "\"query\":"); - try jstr(&b, arena, req.arg); - const result = (try call(c, io, arena, "workspace/symbol", b.items, deadline)) orelse return; - for (items(result)) |sym| { - const loc = get(sym, "location") orelse continue; - try emitRange(&cx, c.caps.enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), str(get(sym, "name")) orelse ""); - } - }, - .diagnostics => try diagnostics(c, io, arena, &cx, uri.items, deadline), - .workspace_diagnostics => try workspaceDiagnostics(c, io, arena, &cx, deadline), - .rename => { - var b = try atPos(arena, uri.items, pos); - try b.appendSlice(arena, ",\"newName\":"); - try jstr(&b, arena, req.arg); - const result = (try call(c, io, arena, "textDocument/rename", b.items, deadline)) orelse return; - // Other open files that say the old name, should the server - // answer for this file alone (zls renaming at a declaration does, - // whatever it was told): applied here, they would no longer build. - var also: std.ArrayList([]const u8) = .empty; - const old = identAt(req.source, req.offset); - if (old.len > 0) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path) and holdsWord(doc.source, old)) - try also.append(arena, doc.path); - try renameEdits(&cx, c.caps.enc, uri.items, result, req.source, old, also.items); - }, - .format => { - var b = try docParams(arena, uri.items); - try b.appendSlice(arena, ",\"options\":{\"tabSize\":4,\"insertSpaces\":true}"); - const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return; - try formatEdits(&cx, c.caps.enc, result, req.source); - }, - .code_action => { - var b = try docParams(arena, uri.items); - try b.print(arena, ",\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch }); - const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return; - for (items(result)) |ca| { - const title = str(get(ca, "title")) orelse continue; - try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title)); - cx.rows += 1; - } - }, - .completion => { - var b = try atPos(arena, uri.items, pos); - try b.appendSlice(arena, ",\"context\":{\"triggerKind\":1}"); - const result = (try call(c, io, arena, "textDocument/completion", b.items, deadline)) orelse return; - const list = if (get(result, "items")) |it| items(it) else items(result); - const here = lsp.rel(cx.base, cx.cur_path); - var n: usize = 0; - for (list) |item| { - if (n >= 100) break; - const label = str(get(item, "label")) orelse continue; - const detail = str(get(item, "detail")) orelse ""; - var text: std.ArrayList(u8) = .empty; - try text.appendSlice(arena, label); - if (detail.len > 0) { - try text.appendSlice(arena, " "); - try text.appendSlice(arena, flat(arena, detail)); - } - // Every row carries the ASKING position: a completion item has - // no location of its own, so the honest place is where it would - // be inserted. n/N still step the list; Enter goes nowhere new. - try lsp.row(cx.out, here, pos.line, byteCol(req.source, pos.line, pos.ch, c.caps.enc), text.items); - n += 1; - } - }, - .callstack => try callstack(c, io, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth, req.budget), - .incoming_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), - .outgoing_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), - .supertypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .supers, tr), - .subtypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .subs, tr), - .status, .explain, .index => unreachable, - } -} - -// -------------------------------------------------------- kind sub-handlers - -/// Goto/references result shapes: bare Location, Location[], LocationLink[]. -fn locations(cx: *Cx, enc: Enc, result: std.json.Value) Err!void { - if (result == .object) { - try emitRange(cx, enc, str(get(result, "uri")) orelse return, get(result, "range"), ""); - return; - } - for (items(result)) |loc| { - if (get(loc, "targetUri")) |tu| { - const r = get(loc, "targetSelectionRange") orelse get(loc, "targetRange"); - try emitRange(cx, enc, str(tu) orelse continue, r, ""); - } else { - try emitRange(cx, enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), ""); - } - } -} - -/// DocumentSymbol[] nests (`children`), SymbolInformation[] is flat. -fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: u8) Err!void { - if (depth > 8) return; - for (items(node)) |sym| { - const name = str(get(sym, "name")) orelse continue; - if (get(get(sym, "location"), "range")) |r| { - try emitRange(cx, enc, str(get(get(sym, "location"), "uri")) orelse uri, r, name); - } else { - try emitRange(cx, enc, uri, get(sym, "selectionRange") orelse get(sym, "range"), name); - } - if (get(sym, "children")) |kids| try walkSymbols(cx, enc, uri, kids, depth + 1); - } -} - -/// Pull when the server does (LSP 3.17), the push store otherwise. The store -/// path waits briefly for a publish that postdates the didChange we just -/// sent, so `]d` right after an edit sees the new truth, not the old one. -fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { - if (c.caps.pull) { - const b = try docParams(arena, uri); - const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; - for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); - return; - } - var stale = true; - for (c.docs.items) |d| if (std.mem.eql(u8, d.uri, uri)) { - stale = d.stale; - break; - }; - if (stale) try waitFresh(c, io, uri, nowMs() + diag_ms); - try renderStore(c, arena, cx, uri); -} - -fn workspaceDiagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { - if (c.caps.pull_workspace) { - const result = (try call(c, io, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; - for (items(get(result, "items"))) |per| { - const uri = str(get(per, "uri")) orelse continue; - for (items(get(per, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); - } - return; - } - try renderStore(c, arena, cx, null); -} - -/// One diagnostic row: `severity: message`, at the diagnostic's own range. -fn emitDiag(cx: *Cx, enc: Enc, uri: []const u8, dg: std.json.Value, arena: std.mem.Allocator) Err!void { - const sev = num(get(dg, "severity")) orelse 1; - const label: []const u8 = switch (sev) { - 1 => "error", - 2 => "warning", - 3 => "info", - else => "hint", - }; - const msg = try std.fmt.allocPrint(arena, "{s}: {s}", .{ label, flat(arena, str(get(dg, "message")) orelse "") }); - try emitRange(cx, enc, uri, get(dg, "range"), msg); -} - -fn renderStore(c: *Conn, arena: std.mem.Allocator, cx: *Cx, only_uri: ?[]const u8) Err!void { - for (c.diags.items) |d| { - if (only_uri) |u| if (!std.mem.eql(u8, d.uri, u)) continue; - const v = std.json.parseFromSliceLeaky(std.json.Value, arena, d.body, .{}) catch continue; - for (items(get(get(v, "params"), "diagnostics"))) |dg| try emitDiag(cx, c.caps.enc, d.uri, dg, arena); - } -} - -/// Block (mutex released) until the reader marks `uri` fresh or the deadline -/// passes. The reader broadcasts on every publishDiagnostics. -fn waitFresh(c: *Conn, io: std.Io, uri: []const u8, deadline: i64) error{Canceled}!void { - const g = c.gen; - while (c.gen == g and c.alive()) { - var fresh = false; - for (c.docs.items) |d| if (std.mem.eql(u8, d.uri, uri)) { - fresh = !d.stale; - break; - }; - if (fresh) return; - if (!try timedWait(c, io, deadline)) return; - } -} - -/// The identifier at byte `at` of `src`: the word a rename there names. -fn identAt(src: []const u8, at: usize) []const u8 { - const isId = struct { - fn f(ch: u8) bool { - return std.ascii.isAlphanumeric(ch) or ch == '_'; - } - }.f; - var start = @min(at, src.len); - while (start > 0 and isId(src[start - 1])) start -= 1; - var end = @min(at, src.len); - while (end < src.len and isId(src[end])) end += 1; - return src[start..end]; -} - -/// Whether `text` holds `word` as a whole identifier. -fn holdsWord(text: []const u8, word: []const u8) bool { - var from: usize = 0; - while (std.mem.indexOfPos(u8, text, from, word)) |i| : (from = i + 1) { - const before = i == 0 or !(std.ascii.isAlphanumeric(text[i - 1]) or text[i - 1] == '_'); - const end = i + word.len; - const after = end == text.len or !(std.ascii.isAlphanumeric(text[end]) or text[end] == '_'); - if (before and after) return true; - } - return false; -} - -/// (line, character) -> byte offset, or null when the line does not exist or -/// the character runs past its end. End-of-line (character == line length) is -/// a real position — that is where an insert-at-EOL lands. -fn strictOffset(src: []const u8, line: u32, ch: u32, enc: Enc) ?usize { - var bol: usize = 0; - var n: u32 = 0; - while (n < line) : (n += 1) - bol = (std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse return null) + 1; - const eol = std.mem.indexOfScalarPos(u8, src, bol, '\n') orelse src.len; - if (enc == .utf8) { - if (ch > eol - bol) return null; - return bol + ch; - } - var units: u32 = 0; - var i: usize = bol; - while (i < eol and units < ch) { - const l = std.unicode.utf8ByteSequenceLength(src[i]) catch 1; - units += if (l == 4 and enc == .utf16) 2 else 1; - i += l; - } - if (units < ch) return null; - return i; -} - -/// Whole-document Range -> half-open byte span for a MUTATING record. -/// STRICT: null unless both endpoints denote positions that exist in the -/// document — for edits, a clamped range is a wrong edit, and wrong edits -/// fail closed (the render paths keep their forgiving conversions; a row a -/// column off is an inconvenience, a splice a column off is corruption). -fn byteSpan(src: []const u8, range: ?std.json.Value, enc: Enc) ?struct { start: usize, end: usize } { - const r = rangeOf(range) orelse return null; - const start = strictOffset(src, r.sl, r.sc, enc) orelse return null; - const end = strictOffset(src, r.el, r.ec, enc) orelse return null; - if (end < start) return null; - return .{ .start = start, .end = end }; -} - -/// A WorkspaceEdit that stays inside the asked-about file becomes `@put` -/// records the core applies as one undo transaction; anything wider (a real -/// multi-file rename, file creates/renames) becomes a PREVIEW — one location -/// row per would-be edit, in the same buffer `gr` fills, because silently -/// applying a fraction of a workspace rename would be worse than either. -fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value, src: []const u8, old: []const u8, also: []const []const u8) Err!void { - var edits: std.ArrayList(PutEdit) = .empty; - var foreign = false; - - // (uri, edits) per file, from either shape of a WorkspaceEdit - var files: std.ArrayList(struct { []const u8, ?std.json.Value }) = .empty; - if (get(result, "documentChanges")) |dcs| { - for (items(dcs)) |dc| { - if (get(dc, "kind") != null) { - foreign = true; // create/rename/delete file operations - continue; - } - const u = str(get(get(dc, "textDocument"), "uri")) orelse continue; - try files.append(cx.arena, .{ u, get(dc, "edits") }); - } - } else if (get(result, "changes")) |ch| if (ch == .object) { - var it = ch.object.iterator(); - while (it.next()) |e| try files.append(cx.arena, .{ e.key_ptr.*, e.value_ptr.* }); - }; - for (files.items) |f| { - const in_self = std.mem.eql(u8, f[0], self_uri); - if (!in_self) foreign = true; - for (items(f[1])) |ed| { - if (in_self) { - // one malformed edit poisons the WHOLE mutating response: - // applying the valid remainder would be a partial edit set - const span = byteSpan(src, get(ed, "range"), enc) orelse return; - const text = str(get(ed, "newText")) orelse return; - try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }); - } else try emitRange(cx, enc, f[0], get(ed, "range"), flat(cx.arena, str(get(ed, "newText")) orelse "")); - } - } - - // Answered for this file alone while other open files say the old - // name: previewed, never applied, each such file named in a row. - const partial = !foreign and also.len > 0; - if (foreign or partial) { - // the preview needs the self-file rows too — the point is the full map - // Rows as the other files' are, `file:L:C-E` with the range's end. - for (edits.items) |ed| { - const lc = lsp.lineCol(src, ed.start); - const end = lsp.lineCol(src, ed.end); - try lsp.spanRow(cx.out, lsp.rel(cx.base, cx.cur_path), lc.line, lc.col, end.line, end.col, flat(cx.arena, ed.text)); - cx.rows += 1; - } - if (partial) for (also) |path| { - try cx.out.print("{s}: also says {s}, which the server did not rename\n", .{ lsp.rel(cx.base, path), old }); - cx.rows += 1; - }; - return; - } - sortEdits(edits.items); - for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text); -} - -/// TextEdit[] from formatting is by definition about the current document: -/// straight to sorted `@put` records. -fn formatEdits(cx: *Cx, enc: Enc, result: std.json.Value, src: []const u8) Err!void { - var edits: std.ArrayList(PutEdit) = .empty; - for (items(result)) |ed| { - // fail the whole response on the first malformed TextEdit — a subset - // of a format is not a format - const span = byteSpan(src, get(ed, "range"), enc) orelse return; - const text = str(get(ed, "newText")) orelse return; - try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text }); - } - sortEdits(edits.items); - for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text); -} - -/// One would-be buffer mutation, on its way to an `@put` record. -const PutEdit = struct { start: usize, end: usize, text: []const u8 }; - -fn sortEdits(edits: []PutEdit) void { - std.mem.sort(PutEdit, edits, {}, struct { - fn lt(_: void, a: PutEdit, b: PutEdit) bool { - return a.start < b.start; - } - }.lt); -} - -/// A bounded static hierarchy. Reuse the prepared item verbatim (including -/// server data), and retain every call-site range rather than just a declaration. -fn hierarchyResult(c: *Conn, io: std.Io, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { - if (jsonDepth(item, 0) > 96) return null; - var body: std.ArrayList(u8) = .empty; - try body.appendSlice(arena, "\"item\":"); - try body.appendSlice(arena, try std.json.Stringify.valueAlloc(arena, item, .{})); - return call(c, io, arena, method, body.items, deadline); -} - -const CallTree = struct { - /// What a node keeps of its caller: its own copies, so the response it - /// came in is freed once its subtree is walked. - const Call = struct { uri: []const u8, name: []const u8, at: Range }; - const Site = struct { range: Range, focus: bool }; - const Node = struct { - call: Call, - ranges: std.ArrayList(Site) = .empty, - children: std.ArrayList(usize) = .empty, - cycle: bool = false, - }; - nodes: std.ArrayList(Node) = .empty, - roots: std.ArrayList(usize) = .empty, - path: [lsp.callstack_max_depth]Hop = undefined, - depth_limit: usize = lsp.callstack_default_depth, - limited: bool = false, - out_of_time: bool = false, - out_of_memory: bool = false, - budget: ?*const std.heap.FixedBufferAllocator = null, - si: usize = 0, - collected: usize = 0, - started_ms: i64 = 0, - narrated: bool = false, - siblings: [lsp.callstack_max_depth]bool = @splat(false), - rendered: usize = 0, - /// The rows rendering the tree takes: the walk stops before `row_cap`, - /// as at the memory limit (`out_of_memory`). - rows: usize = 0, - row_cap: usize = max_rows - 16, - /// The bytes those rows take, over-estimated (the uri for the path it - /// becomes), kept under the answer writer's room. - bytes: usize = 0, - byte_cap: usize = std.math.maxInt(usize), - - /// A row of a caller at `depth`: its tree columns, the uri the path is - /// made from, the name, and room for the address. - fn rowBytes(depth: usize, caller: Call) usize { - return 5 * (depth + 2) + caller.uri.len + caller.name.len + 40; - } - - /// Incoming paths arrive nearest-first. Insert them outermost-first, - /// sharing common caller prefixes and retaining all their call sites. - fn addPath(tree: *CallTree, arena: std.mem.Allocator, path: []const Hop, cycle: bool) Err!void { - var parent: ?usize = null; - var at = path.len; - while (at > 0) { - at -= 1; - const hop = path[at]; - const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items; - const found = for (children) |id| { - if (sameCall(tree.nodes.items[id].call, hop.call)) break id; - } else null; - const depth = path.len - 1 - at; - const id = found orelse blk: { - const id = tree.nodes.items.len; - try tree.nodes.append(arena, .{ .call = .{ .uri = try arena.dupe(u8, hop.call.uri), .name = try arena.dupe(u8, hop.call.name), .at = hop.call.at } }); - tree.rows += 1; - tree.bytes += rowBytes(depth, tree.nodes.items[id].call); - if (parent) |pid| { - try tree.nodes.items[pid].children.append(arena, id); - } else try tree.roots.append(arena, id); - break :blk id; - }; - const node = &tree.nodes.items[id]; - node.cycle = node.cycle or (cycle and at == 0); - for (hop.sites.items) |parsed| { - for (node.ranges.items) |*other| { - if (std.meta.eql(parsed, other.range)) { - other.focus = other.focus or at == 0; - break; - } - } else { - try node.ranges.append(arena, .{ .range = parsed, .focus = at == 0 }); - tree.rows += 1; - tree.bytes += rowBytes(depth + 1, .{ .uri = node.call.uri, .name = "", .at = parsed }); - } - } - parent = id; - } - } -}; - -/// A caller one level up a Callstack: the function, the calls it makes -/// there, and what its own callers are asked by, the server's item or the -/// index's symbol (and document). -const Hop = struct { call: CallTree.Call, sites: std.ArrayList(Range) = .empty, item: ?std.json.Value = null, symbol: u32 = 0, doc: u32 = 0 }; - -/// Where a Callstack's callers come from: the index, else the server. -const Calls = union(enum) { - index: *Scip.Index, - server: struct { c: *Conn, io: std.Io, parse: ?*std.heap.FixedBufferAllocator }, -}; - -fn sameCall(a: CallTree.Call, b: CallTree.Call) bool { - return std.mem.eql(u8, a.uri, b.uri) and std.meta.eql(a.at, b.at); -} - -/// The server's incoming calls as hops, their strings the response's. -fn serverHops(a: std.mem.Allocator, incoming: ?std.json.Value) Err![]Hop { - var hops: std.ArrayList(Hop) = .empty; - for (items(incoming)) |entry| { - const from = get(entry, "from") orelse continue; - const uri = str(get(from, "uri")) orelse continue; - const at = rangeOf(get(from, "selectionRange") orelse get(from, "range")) orelse continue; - if (!std.mem.startsWith(u8, uri, "file:")) continue; - var hop: Hop = .{ .call = .{ .uri = uri, .name = str(get(from, "name")) orelse "(unnamed)", .at = at }, .item = from }; - for (items(get(entry, "fromRanges"))) |r| if (rangeOf(r)) |site| try hop.sites.append(a, site); - try hops.append(a, hop); - } - return hops.items; -} - -/// The index's callers of `symbol` as hops: the definition enclosing each -/// of its references, the references it holds its sites. -fn indexHops(a: std.mem.Allocator, ix: *Scip.Index, symbol: u32) Err![]Hop { - var hops: std.ArrayList(Hop) = .empty; - for (ix.of(symbol)) |o| { - if (ix.occurrences[o].roles & Scip.role_definition != 0) continue; - const def = ix.occurrences[ix.enclosingDefinition(o) orelse continue]; - const hop = for (hops.items) |*h| { - if (h.symbol == def.symbol) break h; - } else blk: { - try hops.append(a, .{ .call = .{ .uri = try indexUri(a, ix, def.doc), .name = displayName(ix, def.symbol), .at = def.range }, .symbol = def.symbol, .doc = def.doc }); - break :blk &hops.items[hops.items.len - 1]; - }; - try hop.sites.append(a, ix.occurrences[o].range); - } - return hops.items; -} - -fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { - for (tree.siblings[0..depth]) |more| try out.writeAll(if (more) "│ " else " "); -} - -fn callstack(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator) Err!void { - if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); - const b = try atPos(arena, uri, pos); - const prepared = (try call(c, io, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; - if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); - // The rows come from the tree alone: the core reads the sources. - cx.no_text = true; - // Each response is parsed into its own part of the region, freed once - // its subtree is walked; only the path being walked is live JSON. - // Raw, as query()'s scratch: `alloc` would fill all ~100 MB of it. - const parse_len = if (budget) |fixed| (fixed.buffer.len - fixed.end_index) / 2 else 0; - var parse_fba: std.heap.FixedBufferAllocator = .init(if (budget != null) - (arena.rawAlloc(parse_len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..parse_len] - else - &.{}); - const parse = if (budget != null) parse_fba.allocator() else arena; - for (items(prepared)) |item| { - const focus: CallTree.Call = .{ .uri = str(get(item, "uri")) orelse continue, .name = "", .at = rangeOf(get(item, "selectionRange") orelse get(item, "range")) orelse continue }; - const incoming = try hierarchyResult(c, io, parse, item, "callHierarchy/incomingCalls", deadline); - const src: Calls = .{ .server = .{ .c = c, .io = io, .parse = if (budget != null) &parse_fba else null } }; - try callTree(src, si, cx, c.caps.enc, focus, try serverHops(parse, incoming), tr, max_depth, budget); - } -} - -/// A Callstack from the first callers of the function asked at: walked to -/// the depth setting, rendered, and why it stopped said. -fn callTree(src: Calls, si: usize, cx: *Cx, enc: Enc, focus: CallTree.Call, first: []const Hop, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator) Err!void { - var tree: CallTree = .{ - .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth), - .si = si, - .started_ms = nowMs(), - .budget = budget, - // The walk stops while the answer's writer has room for the rest. - .byte_cap = if (cx.fixed_out) (cx.out.buffer.len - cx.out.end) -| (1 << 20) else std.math.maxInt(usize), - }; - const count = try collectCallers(src, cx.arena, focus, first, &tree, 0); - if (tree.narrated) post(si, .always, "Callstack: {d} callers", .{tree.collected}); - if (count == 0) try cx.out.writeAll("No callers reported\n"); - try renderCallers(cx, enc, &tree, tree.roots.items, 0); - if (tree.out_of_time) { - try cx.out.writeAll("… the language server ran out of time; continue from a function above with Callstack\n"); - } else if (tree.out_of_memory) { - try cx.out.writeAll("… stopped at the query's memory limit; continue from a function above with Callstack\n"); - } else if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); - tr.note("callstack: {d} callers", .{tree.rendered}); -} - -/// No caller count and no overall deadline: the walk narrates itself on the -/// message row after a second, and it stops when a request goes unanswered -/// or the answer is full (what was collected is shown, its last row saying -/// so), or when the shell cancels it for a newer query. -fn collectCallers(src: Calls, arena: std.mem.Allocator, focus: CallTree.Call, hops: []const Hop, tree: *CallTree, depth: usize) Err!usize { - var count: usize = 0; - for (hops) |hop| { - if (tree.budget) |b| if (b.buffer.len - b.end_index < callstack_reserve) { - tree.out_of_memory = true; - }; - if (tree.rows >= tree.row_cap or tree.bytes >= tree.byte_cap) tree.out_of_memory = true; - if (tree.out_of_time or tree.out_of_memory) break; - const cycle = sameCall(focus, hop.call) or for (tree.path[0..depth]) |ancestor| { - if (sameCall(ancestor.call, hop.call)) break true; - } else false; - tree.path[depth] = hop; - count += 1; - tree.collected += 1; - if (nowMs() - tree.started_ms >= 1000) { - tree.narrated = true; - post(tree.si, .chatty, "Callstack: {d} callers\u{2026}", .{tree.collected}); - } - var children: usize = 0; - if (!cycle) { - if (depth + 1 == tree.depth_limit) { - tree.limited = true; - } else if (src == .index) { - children = try collectCallers(src, arena, focus, try indexHops(arena, src.index, hop.symbol), tree, depth + 1); - } else { - const parse = src.server.parse; - const mark = if (parse) |fixed| fixed.end_index else 0; - defer if (parse) |fixed| { - fixed.end_index = mark; - }; - const a = if (parse) |fixed| fixed.allocator() else arena; - const ancestors = hierarchyResult(src.server.c, src.server.io, a, hop.item.?, "callHierarchy/incomingCalls", nowMs() + req_ms) catch |e| switch (e) { - error.Timeout => blk: { - tree.out_of_time = true; - break :blk null; - }, - // A response bigger than the parse region: this caller - // stops here, the walk with it. - error.OutOfMemory => blk: { - tree.out_of_memory = true; - break :blk null; - }, - else => return e, - }; - if (!tree.out_of_time and !tree.out_of_memory) children = try collectCallers(src, arena, focus, try serverHops(a, ancestors), tree, depth + 1); - } - } - if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); - } - return count; -} - -/// Test callers sink below the rest; each group keeps the usual order. -// ponytail: substring heuristic, "latest.zig" or "contest" count as tests too -fn testCaller(caller: CallTree.Call) bool { - return std.ascii.findIgnoreCase(caller.name, "test") != null or - std.ascii.findIgnoreCase(std.Io.Dir.path.basenamePosix(caller.uri), "test") != null; -} - -fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { - const left = tree.nodes.items[a].call; - const right = tree.nodes.items[b].call; - if (testCaller(left) != testCaller(right)) return testCaller(right); - const uri_order = std.mem.order(u8, left.uri, right.uri); - if (uri_order != .eq) return uri_order == .lt; - return rangeLess(left.at, right.at); -} - -fn rangeLess(left: Range, right: Range) bool { - return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc); -} - -fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void { - std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess); - for (children, 0..) |id, index| { - // emitRange's row ceiling and the writer's room, met here before a - // prefix is half written - if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { - tree.limited = true; - return; - } - const node = &tree.nodes.items[id]; - const more = index + 1 < children.len; - try callPrefix(cx.out, tree, depth); - const has_children = node.children.items.len > 0 or node.ranges.items.len > 0; - try cx.out.writeAll(if (more) "├" else "╰"); - try cx.out.writeAll(if (has_children) "──┬ " else "─── "); - const name = flat(cx.arena, node.call.name); - const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name; - try emitAt(cx, enc, node.call.uri, node.call.at, label); - tree.rendered += 1; - tree.siblings[depth] = more; - std.mem.sort(CallTree.Site, node.ranges.items, {}, struct { - fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool { - return rangeLess(a.range, b.range); - } - }.less); - for (node.ranges.items, 0..) |site, site_index| { - if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { - tree.limited = true; - return; - } - if (site.focus) try cx.out.writeAll(lsp.callstack_match); - try callPrefix(cx.out, tree, depth + 1); - try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else "╰─ "); - try emitAt(cx, enc, node.call.uri, site.range, ""); - } - try renderCallers(cx, enc, tree, node.children.items, depth + 1); - } -} - -const Hier = enum { incoming, outgoing, supers, subs }; - -/// Depth of a parsed json value, saturating just past `at`'s caller's cap — -/// the guard that keeps server-controlled nesting away from Stringify's -/// fixed-depth assertion. -fn jsonDepth(v: std.json.Value, at: u32) u32 { - if (at > 96) return at; - return switch (v) { - .object => |o| blk: { - var deepest = at; - var it = o.iterator(); - while (it.next()) |e| deepest = @max(deepest, jsonDepth(e.value_ptr.*, at + 1)); - break :blk deepest; - }, - .array => |a| blk: { - var deepest = at; - for (a.items) |e| deepest = @max(deepest, jsonDepth(e, at + 1)); - break :blk deepest; - }, - else => at, - }; -} - -// ---------------------------------------------------------------- the index - -/// A symbol's name to show: its display name, else its string's last -/// descriptor (`... lib/add().` is `add`). -fn displayName(ix: *const Scip.Index, symbol: u32) []const u8 { - if (Scip.field(ix.infos.items[symbol], 6)) |f| return f.bytes; - const s = std.mem.trimEnd(u8, ix.symbols.items[symbol], "().#/:!"); - return s[if (std.mem.lastIndexOfAny(u8, s, " /#.")) |cut| cut + 1 else 0..]; -} - -fn indexPath(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u8 { - return std.fmt.allocPrint(a, "{s}/{s}", .{ ix.root(), ix.documents[doc].path }); -} - -fn indexUri(a: std.mem.Allocator, ix: *const Scip.Index, doc: u32) Err![]const u8 { - var b: std.ArrayList(u8) = .empty; - try uriOf(&b, a, try indexPath(a, ix, doc)); - return b.items; -} - -// ------------------------------------------------------------ row rendering - -/// Files read while answering ONE query, so a references list over a handful -/// of files reads each once, not once per row. The current buffer never needs -/// reading: `req.source` IS its text, unsaved edits included. -const Cx = struct { - io: std.Io, - arena: std.mem.Allocator, - base: []const u8, - cur_path: []const u8, - cur_src: []const u8, - out: *std.Io.Writer, - /// `out` is the query's fixed answer buffer, whose room is checked. - fixed_out: bool = false, - /// Rows without their source text (Callstack: the core reads it). - no_text: bool = false, - rows: usize = 0, - relative_parents: bool = false, - files: std.ArrayList(struct { path: []const u8, text: []const u8 }) = .empty, - - fn text(cx: *Cx, path: []const u8) ?[]const u8 { - if (std.mem.eql(u8, path, cx.cur_path)) return cx.cur_src; - for (cx.files.items) |f| if (std.mem.eql(u8, f.path, path)) return f.text; - if (cx.files.items.len >= 32) return null; - const file = std.Io.Dir.cwd().openFile(cx.io, path, .{}) catch return null; - defer file.close(cx.io); - var chunk: [64 * 1024]u8 = undefined; - var file_reader = file.reader(cx.io, &chunk); - var buf: std.ArrayList(u8) = .empty; - // A file past max_doc_bytes is its first max_doc_bytes. - file_reader.interface.appendRemaining(cx.arena, &buf, .limited(max_doc_bytes)) catch |err| switch (err) { - error.StreamTooLong => {}, - else => return null, - }; - cx.files.append(cx.arena, .{ .path = path, .text = buf.items }) catch return null; - return buf.items; - } -}; - -/// One row from an LSP (uri, Range). The uri becomes a real path (percent- -/// decoded, `rel`'d against the asking window), utf-16 columns become byte -/// columns, and a single-line range becomes the `path:LINE:COL-ENDCOL` form a -/// look SELECTS. `note` overrides the source line as the row's text. -fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: []const u8) Err!void { - return emitAt(cx, enc, uri, rangeOf(range) orelse return, note); -} - -/// `file:///a/b%20c` -> `/a/b c`. Rows carry real paths; look.zig opens them -/// and `%20` is not a filename. A decoded CONTROL byte rejects the whole uri: -/// a `%0A` in a path would split one location into two physical rows — a -/// server-forged extra row in the results buffer — and no path worth opening -/// has a newline, tab or NUL in it. -fn pathOf(arena: std.mem.Allocator, uri: []const u8) ?[]const u8 { - var rest = uri; - if (std.mem.startsWith(u8, rest, "file://")) { - rest = rest["file://".len..]; - if (rest.len > 0 and rest[0] != '/') return null; // an authority we cannot open - } else if (std.mem.indexOf(u8, rest, "://") != null) return null; - var out: std.ArrayList(u8) = .empty; - var i: usize = 0; - while (i < rest.len) { - var byte: u8 = rest[i]; - if (rest[i] == '%' and i + 2 < rest.len) { - if (std.fmt.parseInt(u8, rest[i + 1 .. i + 3], 16)) |b| { - byte = b; - i += 3; - } else |_| i += 1; - } else i += 1; - if (byte < 0x20) return null; - out.append(arena, byte) catch return null; - } - return out.items; -} - -fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void { - return emitPath(cx, enc, pathOf(cx.arena, uri) orelse return, r, note); -} - -fn emitPath(cx: *Cx, enc: Enc, path: []const u8, r: Range, note: []const u8) Err!void { - if (cx.rows >= max_rows) return; - if (path.len == 0 or path[0] != '/') return; // rows promise absolute-or-rel-from-base - // Without sources (Callstack) the asking file is still known: its rows' - // columns convert from utf-16 as ever. - const src = if (cx.no_text and !std.mem.eql(u8, path, cx.cur_path)) null else cx.text(path); - - var bol: usize = 0; - var eol: usize = 0; - if (src) |t| { - var n: u32 = 0; - while (n < r.sl) : (n += 1) { - bol = (std.mem.indexOfScalarPos(u8, t, bol, '\n') orelse { - bol = t.len; - break; - }) + 1; - } - eol = std.mem.indexOfScalarPos(u8, t, @min(bol, t.len), '\n') orelse t.len; - } - const lntext: []const u8 = if (src) |t| t[@min(bol, t.len)..@min(eol, t.len)] else ""; - - const col = colBytes(lntext, r.sc, enc); - const shown = if (cx.relative_parents) blk: { - const relative = std.Io.Dir.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path; - break :blk if (relative.len < path.len) relative else path; - } else lsp.rel(cx.base, path); - // A same-line exclusive end byte offset is also the displayed inclusive - // one-based column. Multi-line ranges display only their starting address. - const end_col = if (r.el == r.sl and r.ec > r.sc) colBytes(lntext, r.ec, enc) else col; - if (note.len == 0) { - try lsp.sourceSpanRow(cx.out, shown, r.sl, col, r.el, end_col, lntext); - } else { - try lsp.spanRow(cx.out, shown, r.sl, col, r.el, end_col, note); - } - cx.rows += 1; -} - -/// utf-16 code units -> byte column within one line; identity for utf-8. -fn colBytes(lntext: []const u8, ch: u32, enc: Enc) usize { - if (enc == .utf8 or lntext.len == 0) return ch; - var units: u32 = 0; - var i: usize = 0; - while (i < lntext.len and units < ch) { - const l = std.unicode.utf8ByteSequenceLength(lntext[i]) catch 1; - units += if (l == 4 and enc == .utf16) 2 else 1; - i += l; - } - return i; -} - -/// Prose squashed onto the one line a row is: newlines and tabs to spaces, -/// cut to a width a pane can show. -fn flat(arena: std.mem.Allocator, s: []const u8) []const u8 { - var buf: std.ArrayList(u8) = .empty; - var sp = false; - for (s) |ch| { - if (ch == '\n' or ch == '\r' or ch == '\t' or ch == 0) { - if (!sp and buf.items.len > 0) buf.append(arena, ' ') catch break; - sp = true; - } else { - buf.append(arena, ch) catch break; - sp = false; - } - if (buf.items.len >= 200) break; - } - return std.mem.trim(u8, buf.items, " "); -} - -fn setCloexec(fd: c_int) void { - const FD_CLOEXEC: c_int = 1; - _ = libc.fcntl(fd, libc.F.SETFD, FD_CLOEXEC); -} - -// Darwin needs fcntl after socketpair; another concurrent fork can inherit the pair in that window. -fn transportPair(sv: *[2]libc.fd_t) bool { - const sock_type = if (comptime builtin.os.tag.isDarwin()) - libc.SOCK.STREAM - else - libc.SOCK.STREAM | libc.SOCK.CLOEXEC; - if (libc.socketpair(libc.AF.UNIX, sock_type, 0, sv) != 0) return false; - if (comptime builtin.os.tag.isDarwin()) { - setCloexec(sv[0]); - // The child dup2s this onto 0 and 1, and dup2 CLEARS close-on-exec on - // the copy, so the server still gets the socket; this marks only the - // number itself, which the child's 3..1024 sweep closes anyway. - setCloexec(sv[1]); - const one: c_int = 1; - _ = libc.setsockopt(sv[0], libc.SOL.SOCKET, libc.SO.NOSIGPIPE, @ptrCast(&one), @sizeOf(c_int)); - } - return true; -} - -// ----------------------------------------------------------- the connection - -/// Where the project starts: helix's find_root rule. Walk UP from `dir`; the -/// TOP-MOST directory holding a language marker wins (a cargo workspace's -/// root Cargo.toml beats the member crate's), the CLOSEST `.git` is the -/// fallback, the asking directory the last resort. -fn rootOf(dir: []const u8, markers: []const []const u8) []const u8 { - if (dir.len == 0 or dir[0] != '/') return "/"; - var top_marker: ?[]const u8 = null; - var git: ?[]const u8 = null; - var d = dir; - var buf: [4096:0]u8 = undefined; - while (true) { - for (markers) |marker| { - const p = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d, marker }, 0) catch continue; - if (libc.access(p.ptr, libc.F_OK) == 0) { - top_marker = d; - break; - } - } - if (git == null) { - if (std.fmt.bufPrintSentinel(&buf, "{s}/.git", .{d}, 0)) |p| { - if (libc.access(p.ptr, libc.F_OK) == 0) git = d; - } else |_| {} - } - d = std.Io.Dir.path.dirname(d) orelse break; - if (d.len <= 1) break; - } - return top_marker orelse git orelse dir; -} - -/// The spec's binary: the env override when set, else `bin`, PATH-searched -/// unless it names a path, then the standard per-user bin directory. -fn binOf(spec: *const Spec, buf: *[4096:0]u8) ?[:0]const u8 { - const name = if (libc.getenv(spec.env)) |v| std.mem.span(v) else spec.bin; - const path = if (libc.getenv("PATH")) |p| std.mem.span(p) else "/usr/local/bin:/usr/bin:/bin"; - const home = if (libc.getenv("HOME")) |p| std.mem.span(p) else ""; - return findBin(name, path, home, buf); -} - -fn findBin(name: []const u8, path: []const u8, home: []const u8, buf: *[4096:0]u8) ?[:0]const u8 { - if (name.len == 0) return null; - if (std.mem.indexOfScalar(u8, name, '/') != null) { - const z = std.fmt.bufPrintSentinel(buf, "{s}", .{name}, 0) catch return null; - return if (libc.access(z.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(z.ptr)) z else null; - } - var it = std.mem.tokenizeScalar(u8, path, ':'); - while (it.next()) |dir| { - const cand = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch continue; - if (libc.access(cand.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(cand.ptr)) return cand; - } - // Desktop launchers often omit ~/.local/bin even when shells include it. - if (std.fs.path.isAbsolute(home)) { - const cand = std.fmt.bufPrintSentinel(buf, "{s}/.local/bin/{s}", .{ home, name }, 0) catch return null; - if (libc.access(cand.ptr, libc.X_OK) == 0 and !@import("../host_io.zig").Shell.isDirectory(cand.ptr)) return cand; - } - return null; -} - -/// Spawn-or-return, and tell an existing server about a new project root. -/// Returns the generation the caller's whole query is bound to. -fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { - c.si = si; - if (c.state == .disabled) { - tr.note("STOP: {s} is disabled for this session (no binary; set {s})", .{ specs[si].name, specs[si].env }); - return error.NoServer; - } - if (c.alive()) { - const root = rootOf(req.root, specs[si].markers); - if (!std.mem.eql(u8, root, c.root)) { - var known = false; - for (c.extra_roots.items) |r| if (std.mem.eql(u8, r, root)) { - known = true; - break; - }; - if (!known and c.caps.folders) { - var b: std.ArrayList(u8) = .empty; - try b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"method\":\"workspace/didChangeWorkspaceFolders\",\"params\":{\"event\":{\"added\":[{\"name\":\"root\",\"uri\":\""); - try uriOf(&b, arena, root); - try b.appendSlice(arena, "\"}],\"removed\":[]}}}"); - try send(c, io, b.items, nowMs() + wedge_ms); - const owned = try sa.dupe(u8, root); - c.extra_roots.append(sa, owned) catch sa.free(owned); - } - } - return c.gen; - } - - // A recent failed spawn/handshake holds the fork back; the message row - // already said when the next try is due. - if (nowMs() < c.retry_after_ms) { - tr.note("STOP: {s} failed recently; retry due in {d}ms", .{ specs[si].name, c.retry_after_ms - nowMs() }); - return error.Backoff; - } - - // Look before forking; a missing binary must cost one probe and one - // message, not a doomed fork per keystroke. - var exe_buf: [4096:0]u8 = undefined; - const exe = binOf(&specs[si], &exe_buf) orelse { - c.state = .disabled; - post(si, .always, "{s} not found — install it or set {s}", .{ specs[si].name, specs[si].env }); - tr.note("STOP: no {s} binary on PATH (override: {s})", .{ specs[si].bin, specs[si].env }); - return error.NoServer; - }; - - const root = rootOf(req.root, specs[si].markers); - var root_buf: [4096:0]u8 = undefined; - const root_z = std.fmt.bufPrintSentinel(&root_buf, "{s}", .{root}, 0) catch return error.NoServer; - // Owned BEFORE anything spawns: the reader thread is the socket's only - // closer once it exists, so nothing fallible may sit between fork and - // reader-spawn — an abort there would strand the fd. - const owned_root = try sa.dupe(u8, root); - - var sv: [2]libc.fd_t = undefined; - if (!transportPair(&sv)) { - sa.free(owned_root); - tr.note("STOP: socketpair for {s} failed", .{specs[si].name}); - return error.NoServer; - } - if (!exit_hook.swap(true, .acq_rel)) _ = atexit(killAllAtExit); - // ponytail: hand-rolled, not std.process.spawn: 0.17's has no setsid - // (only setpgid), no signal mask/disposition reset and no fd sweep. - const pid = libc.fork(); - if (pid < 0) { - _ = libc.close(sv[0]); - _ = libc.close(sv[1]); - sa.free(owned_root); - tr.note("STOP: fork for {s} failed", .{specs[si].name}); - return error.NoServer; - } - if (pid == 0) { - // Between fork and exec, in a process with threads: only async- - // 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(); - _ = libc.dup2(sv[1], 0); - _ = libc.dup2(sv[1], 1); - const devnull = libc.open("/dev/null", .{ .ACCMODE = .WRONLY }); - if (devnull >= 0) _ = libc.dup2(devnull, 2); - var fd: c_int = 3; - while (fd < 1024) : (fd += 1) _ = libc.close(fd); - _ = libc.chdir(root_z.ptr); - var argv: [8:null]?[*:0]const u8 = @splat(null); - argv[0] = exe.ptr; - // args are comptime literals; the buffers live until execv - var argbufs: [6][64:0]u8 = undefined; - for (specs[si].args, 0..) |a, i| { - if (i >= argbufs.len) break; - const z = std.fmt.bufPrintSentinel(&argbufs[i], "{s}", .{a}, 0) catch break; - argv[1 + i] = z.ptr; - } - _ = execv(exe.ptr, &argv); - libc._exit(127); - } - _ = libc.close(sv[1]); - - // the slate the old generation may have left (a self-died server skips - // shutdownIf) must not leak into the new one: a stale doc entry would - // suppress the didOpen the new server never got - c.gen +%= 1; - const g = c.gen; - c.pid = pid; - c.sock = sv[0]; - c.state = .starting; - c.caps = .{}; - c.next_id = 1; - c.want_id = 0; - if (c.resp) |r| sa.free(r); - c.resp = null; - c.progress = 0; - c.loading = false; - c.timeouts = 0; - forgetDocs(c); - if (c.root.len > 0) sa.free(c.root); - c.root = owned_root; - - const th = std.Thread.spawn(.{}, reader, .{ io, si, g, sv[0] }) catch { - // no reader means nobody would ever close the fd our way; do it here, - // before anything else can see the conn - _ = libc.close(sv[0]); - _ = libc.kill(pid, .KILL); - _ = libc.waitpid(pid, null, 0); - c.state = .dead; - c.sock = -1; - return error.NoServer; - }; - th.detach(); - - post(si, .always, "{s} starting — {s}", .{ specs[si].name, root }); - tr.note("spawned {s} (pid {d}) at {s}", .{ specs[si].name, pid, root }); - - // A start runs to the end however soon the query that began it is - // canceled: killing a half-started server would only make the next - // query start it again. The cancel lands at the next wait instead. - const protection = io.swapCancelProtection(.blocked); - const started = handshake(c, io, arena, root); - _ = io.swapCancelProtection(protection); - started catch |e| { - shutdownIf(c, io, g); - // NOT a session disable. A handshake that misses the deadline is - // routinely environmental — a rustup shim deciding to download the - // project's pinned toolchain before launching the real server was - // the case that taught this — and it heals by itself. What must not - // happen is a fork per keystroke while it heals, so failures back - // off on backoffMs's schedule, reset by the next success. - c.handshake_fails +|= 1; - const wait = backoffMs(c.handshake_fails); - c.retry_after_ms = nowMs() + wait; - post(si, .always, "{s} not answering — retrying in {d}s", .{ - specs[si].name, @divTrunc(wait, 1000), - }); - return switch (e) { - error.OutOfMemory => error.OutOfMemory, - else => error.NoServer, - }; - }; - c.handshake_fails = 0; - c.retry_after_ms = 0; - c.ready_at_ms = nowMs(); - c.state = .ready; - post(si, .always, "{s} ready — {s}", .{ specs[si].name, root }); - return g; -} - -fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) Err!void { - var b: std.ArrayList(u8) = .empty; - try b.print(arena, "\"processId\":{d},\"clientInfo\":{{\"name\":\"pardes\"}},\"rootUri\":\"", .{@as(u32, @bitCast(libc.getpid()))}); - try uriOf(&b, arena, root); - try b.appendSlice(arena, "\",\"workspaceFolders\":[{\"name\":\"root\",\"uri\":\""); - try uriOf(&b, arena, root); - try b.appendSlice(arena, "\""); - try b.appendSlice(arena, - \\}],"capabilities":{"general":{"positionEncodings":["utf-8","utf-16"]}, - \\"window":{"workDoneProgress":true}, - \\"workspace":{"configuration":true,"workspaceFolders":true,"symbol":{}, - \\"diagnostics":{"refreshSupport":false}}, - \\"textDocument":{"synchronization":{"dynamicRegistration":false,"willSave":false,"didSave":false}, - \\"publishDiagnostics":{"relatedInformation":false}, - \\"diagnostic":{"dynamicRegistration":false,"relatedDocumentSupport":false}, - \\"hover":{"contentFormat":["plaintext","markdown"]}, - \\"definition":{"linkSupport":true},"declaration":{"linkSupport":true}, - \\"typeDefinition":{"linkSupport":true},"implementation":{"linkSupport":true}, - \\"references":{},"documentHighlight":{}, - \\"documentSymbol":{"hierarchicalDocumentSymbolSupport":true}, - \\"formatting":{},"rename":{"prepareSupport":false}, - \\"completion":{"completionItem":{"snippetSupport":false,"documentationFormat":["plaintext"]}}, - \\"callHierarchy":{},"typeHierarchy":{}, - \\"codeAction":{"codeActionLiteralSupport":{"codeActionKind":{"valueSet":[]}}}}, - \\"experimental":{"serverStatusNotification":true}} - ); - // strip the literal's newlines: legal JSON either way, but the frame - // length must match what is sent - var body: std.ArrayList(u8) = .empty; - for (b.items) |ch| if (ch != '\n') try body.append(arena, ch); - - const deadline = nowMs() + init_ms; - const reply = (try call(c, io, arena, "initialize", body.items, deadline)) orelse return error.Protocol; - - const caps = get(reply, "capabilities"); - c.caps.enc = if (std.mem.eql(u8, str(get(caps, "positionEncoding")) orelse "utf-16", "utf-8")) .utf8 else .utf16; - if (get(caps, "diagnosticProvider")) |dp| { - c.caps.pull = provider(dp); - c.caps.pull_workspace = if (get(dp, "workspaceDiagnostics")) |w| w == .bool and w.bool else false; - } - c.caps.call_hier = provider(get(caps, "callHierarchyProvider")); - c.caps.type_hier = provider(get(caps, "typeHierarchyProvider")); - c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false; - - try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); -} - -/// A server capability that may be `true`, an options object, or absent. -fn provider(v: ?std.json.Value) bool { - const o = v orelse return false; - return switch (o) { - .bool => |b| b, - .object => true, - else => false, - }; -} - -/// Send a request and wait on the mailbox. Returns the parsed `result`, or -/// null for an error response / null result — both are legal "no answer". -/// Runs with the conn mutex held; the mutex is released inside the wait. -fn call(c: *Conn, io: std.Io, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { - const g = c.gen; - const id = c.next_id; - c.next_id +%= 1; - - var b: std.ArrayList(u8) = .empty; - try b.print(arena, "{{\"jsonrpc\":\"2.0\",\"id\":{d},\"method\":\"{s}\",\"params\":{{", .{ id, method }); - try b.appendSlice(arena, params); - try b.appendSlice(arena, "}}"); - - if (c.resp) |r| sa.free(r); - c.resp = null; - c.want_id = id; - defer c.want_id = 0; - - try send(c, io, b.items, if (c.state == .ready) nowMs() + wedge_ms else deadline); - - // The handshake (still `.starting`) has its deadline. A ready server is - // waited for until it answers or the shell cancels this query for a - // newer one, so the first query after a start is answered, not lost: - // past `deadline` the message row says it is still working, and only - // silent and idle for wedge_ms is it not answering. - var said = false; - var busy_at = nowMs(); - while (c.resp == null and c.gen == g and c.alive()) { - const ready = c.state == .ready; - const waiting = timedWait(c, io, if (ready) nowMs() + 500 else deadline) catch |e| { - cancelRequest(c, io, arena, id); - return e; - }; - if (!ready) { - if (waiting) continue; - break; - } - if (c.progress > 0) busy_at = nowMs(); - if (!said and nowMs() >= deadline) { - said = true; - post(c.si, .always, "{s} is still working on it\u{2026}", .{specs[c.si].name}); - } - if (nowMs() - busy_at >= wedge_ms) break; - } - if (said and c.resp != null) post(c.si, .always, "{s} answered", .{specs[c.si].name}); - if (c.gen != g or !c.alive()) return error.Dead; - const raw = c.resp orelse { - cancelRequest(c, io, arena, id); - return error.Timeout; - }; - c.resp = null; - defer sa.free(raw); - const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return error.Protocol; - const result = get(v, "result") orelse return null; - if (result == .null) return null; - return result; -} -/// Give the server leave to abandon the work we stopped waiting for. -fn cancelRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, id: u32) void { - var cb: std.ArrayList(u8) = .empty; - cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return; - send(c, io, cb.items, nowMs() + reply_ms) catch {}; -} - -/// One bounded cond wait, and a cancelation point: a worker the shell -/// cancels for a newer query stops here. False when the deadline has passed. -fn timedWait(c: *Conn, io: std.Io, deadline: i64) error{Canceled}!bool { - const left = deadline - nowMs(); - if (left <= 0) return false; - const wait_ms = @min(left, 500); // tick so gen/state changes are noticed - c.cond.waitTimeout(io, &c.mu, .{ .duration = .{ .raw = .fromMilliseconds(wait_ms), .clock = .awake } }) catch |e| switch (e) { - error.Timeout => {}, - error.Canceled => return error.Canceled, - }; - return true; -} - -/// Forget a server, but only the generation the caller actually used — a -/// respawn that happened during the caller's wait must not be killed for its -/// predecessor's crimes. Mutex held. The reader closes the fd; this only -/// shuts the transport down and reaps the child. -fn shutdownIf(c: *Conn, io: std.Io, g: u32) void { - if (c.gen != g or c.sock < 0) return; - _ = libc.shutdown(c.sock, 2); // SHUT_RDWR: the reader sees EOF and closes - reap(c.pid); - c.sock = -1; - c.pid = -1; - if (c.state != .disabled) c.state = .dead; - forgetDocs(c); - if (c.resp) |r| sa.free(r); - c.resp = null; - c.cond.broadcast(io); -} - -/// TERM, a bounded grace, then KILL, to the server's whole process group -/// (it is its group's leader, setsid at spawn): what it started -- zls's -/// `zig build --build-runner` -- goes with it, never left an orphan. Never -/// blocks unboundedly: a reaped or foreign pid answers -1 immediately. -fn reap(pid: libc.pid_t) void { - if (pid <= 0) return; - _ = libc.kill(-pid, .TERM); - var tries: u8 = 0; - while (tries < 20) : (tries += 1) { - const w = libc.waitpid(pid, null, libc.W.NOHANG); - if (w == pid or w < 0) { - // Its children may still be finishing their TERM. - _ = libc.kill(-pid, .KILL); - return; - } - _ = usleep(10_000); - } - _ = libc.kill(-pid, .KILL); - _ = libc.waitpid(pid, null, 0); -} - -/// At this process's exit, every server's group is killed: a server busy -/// in a build (zls at a cold start) would not notice its socket close, and -/// lived on with its children after the editor. Registered once, at the -/// first spawn; signals only, no locks (other threads may hold them). -fn killAllAtExit() callconv(.c) void { - for (&conns) |*c| if (c.pid > 0) { - _ = libc.kill(-c.pid, .KILL); - }; -} -var exit_hook = std.atomic.Value(bool).init(false); - -/// Free every per-document accumulation. Mutex held. -fn forgetDocs(c: *Conn) void { - for (c.extra_roots.items) |r| sa.free(r); - c.extra_roots.clearRetainingCapacity(); - for (c.docs.items) |d| sa.free(d.uri); - c.docs.clearRetainingCapacity(); - for (c.diags.items) |d| { - sa.free(d.uri); - sa.free(d.body); - } - c.diags.clearRetainingCapacity(); - c.diag_bytes = 0; -} - -// ------------------------------------------------------------ reader thread - -/// Owns the read side of one socket for one generation, and is the only -/// closer of that fd. Routes responses to the mailbox, answers server -/// requests, feeds the diagnostics store, narrates progress. -fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void { - const c = &conns[si]; - var buf = sa.alloc(u8, 256 * 1024) catch { - readerExit(c, io, si, g, sock); - return; - }; - defer sa.free(buf); - var len: usize = 0; - var parse_arena: std.heap.ArenaAllocator = .init(sa); - defer parse_arena.deinit(); - - outer: while (true) { - // drain every complete frame already buffered - drain: while (true) switch (frameNext(buf[0..len])) { - .frame => |m| { - dispatch(c, io, si, g, sock, buf[m.body_start..m.body_end], &parse_arena); - std.mem.copyForwards(u8, buf[0 .. len - m.consumed], buf[m.consumed..len]); - len -= m.consumed; - }, - .incomplete => break :drain, - // a complete header that is not a frame we can speak: nothing - // after it can ever re-synchronize, so the connection is over — - // this must NOT read as "incomplete", which would buffer the - // poison forever while every request quietly times out - .poison => break :outer, - }; - // grow when a frame is bigger than the space that is left - if (len == buf.len) { - if (buf.len >= 64 << 20) break :outer; - const bigger = sa.realloc(buf, buf.len * 2) catch break :outer; - buf = bigger; - } - var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.IN, .revents = 0 }}; - const pr = libc.poll(&pfd, 1, 1000); - if (pr < 0) { - if (libc.errno(pr) == .INTR) continue; - break :outer; - } - if (pr == 0) { - // tick: a respawn while the server was silent leaves this thread - // reading a corpse; notice and go - c.mu.lockUncancelable(io); - const stale = c.gen != g; - c.mu.unlock(io); - if (stale) break :outer; - continue; - } - const got = libc.recv(sock, buf.ptr + len, buf.len - len, 0); - if (got < 0) { - const e = libc.errno(got); - if (e == .INTR or e == .AGAIN) continue; - break :outer; - } - if (got == 0) break :outer; // the server exited or shutdownIf spoke - len += @intCast(got); - } - readerExit(c, io, si, g, sock); -} - -fn readerExit(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int) void { - c.mu.lockUncancelable(io); - if (c.gen == g and c.alive()) { - // the server died on its own — shutdownIf never saw it, so the corpse - // is ours to reap and the conn's transport fields are ours to clear - c.state = .dead; - reap(c.pid); - c.pid = -1; - c.sock = -1; - // A server that keeps crashing right after its handshake would - // otherwise respawn on every keystroke — the handshake SUCCEEDING - // resets the backoff, so the crash has to count as the failure it - // is. A long-lived server that dies gets one free respawn. - if (nowMs() - c.ready_at_ms < 30_000) { - c.handshake_fails +|= 1; - const wait = backoffMs(c.handshake_fails); - c.retry_after_ms = nowMs() + wait; - post(si, .always, "{s} crashed — retrying in {d}s", .{ specs[si].name, @divTrunc(wait, 1000) }); - } else { - post(si, .always, "{s} exited — restarts on the next query", .{specs[si].name}); - } - c.cond.broadcast(io); - } - c.mu.unlock(io); - // A query writes with the mutex let go (send): the fd stays its until - // that write is done, and shutdown(2) has already made it fail fast. - c.write_mu.lockUncancelable(io); - _ = libc.close(sock); - c.write_mu.unlock(io); -} - -/// 10s doubling to 2min: the fork-per-keystroke guard's schedule. -fn backoffMs(fails: u8) i64 { - const shift: u5 = @min(fails -| 1, 4); - return @as(i64, 10_000) << shift; -} - -const Framed = struct { body_start: usize, body_end: usize, consumed: usize }; - -const FrameStep = union(enum) { - /// keep reading; the head of the buffer may still become a frame - incomplete, - /// a complete, valid frame - frame: Framed, - /// a complete header that cannot be a frame (no/invalid/oversized - /// Content-Length): the stream can never re-synchronize - poison, -}; - -/// One Content-Length-framed message at the head of `data`. Pure — this is -/// the whole wire format, and it is testable without a socket. -fn frameNext(data: []const u8) FrameStep { - const sep = std.mem.indexOf(u8, data, "\r\n\r\n") orelse return .incomplete; - var clen: ?usize = null; - var it = std.mem.splitSequence(u8, data[0..sep], "\r\n"); - while (it.next()) |line| { - const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue; - if (!std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " "), "content-length")) continue; - clen = std.fmt.parseInt(usize, std.mem.trim(u8, line[colon + 1 ..], " "), 10) catch null; - } - const n = clen orelse return .poison; - const start = sep + 4; - if (n > 64 << 20) return .poison; - if (data.len < start + n) return .incomplete; - return .{ .frame = .{ .body_start = start, .body_end = start + n, .consumed = start + n } }; -} - -/// One message from the server. Parses into a throwaway arena; touches conn -/// state only under the mutex; replies never hold it (bounded writes must not -/// stall the mailbox). -fn dispatch(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int, raw: []const u8, arena_state: *std.heap.ArenaAllocator) void { - // The reader's one parse arena, reset per message: no mapping per - // `$/progress` report, and no more than parse_kept kept between them. - defer _ = arena_state.reset(.{ .retain_with_limit = parse_kept }); - const arena = arena_state.allocator(); - const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return; - if (v != .object) return; - - if (str(get(v, "method"))) |method| { - if (get(v, "id")) |id| return serverRequest(c, io, arena, sock, method, id, get(v, "params")); - return notification(c, io, si, g, raw, method, get(v, "params")); - } - - // a response: deliver to the one waiting query, if it is still waiting - const id = num(get(v, "id")) orelse return; - c.mu.lockUncancelable(io); - defer c.mu.unlock(io); - if (c.gen == g and c.want_id != 0 and id == c.want_id and c.resp == null) { - c.resp = sa.dupe(u8, raw) catch null; - c.cond.broadcast(io); - } -} - -/// The server asked US something. Everything optional was declined in the -/// handshake, so a null-ish answer is always legal — but it must ARRIVE, or -/// the server blocks forever on its own question. -fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { - var b: std.ArrayList(u8) = .empty; - b.appendSlice(arena, "{\"jsonrpc\":\"2.0\",\"id\":") catch return; - switch (id) { - .integer => |n| b.print(arena, "{d}", .{n}) catch return, - .string => |t| jstr(&b, arena, t) catch return, - else => b.appendSlice(arena, "null") catch return, - } - if (std.mem.eql(u8, method, "workspace/configuration")) { - // one null per asked item — a bare null here is a protocol violation - // some servers punish with a parse loop - const n = items(get(params, "items")).len; - b.appendSlice(arena, ",\"result\":[") catch return; - for (0..n) |i| b.appendSlice(arena, if (i == 0) "null" else ",null") catch return; - b.appendSlice(arena, "]}") catch return; - } else if (std.mem.eql(u8, method, "workspace/applyEdit")) { - b.appendSlice(arena, ",\"result\":{\"applied\":false}}") catch return; - } else { - b.appendSlice(arena, ",\"result\":null}") catch return; - } - answerServer(c, io, sock, b.items); -} - -fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { - const Method = enum { @"textDocument/publishDiagnostics", @"$/progress", @"window/showMessage", @"experimental/serverStatus" }; - switch (std.meta.stringToEnum(Method, method) orelse return) { - .@"textDocument/publishDiagnostics" => { - const uri = str(get(params, "uri")) orelse return; - // keep the raw MESSAGE (params included); re-parsing it per query - // beats owning a parsed tree past this arena's life - const body = sa.dupe(u8, raw) catch return; - c.mu.lockUncancelable(io); - defer c.mu.unlock(io); - if (c.gen != g) { - sa.free(body); - return; - } - for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { - d.stale = false; - break; - }; - var slot: ?*DiagSet = null; - for (c.diags.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { - slot = d; - break; - }; - // Bounded in files and bytes: a new set that does not fit pushes - // out the oldest files' (the server sends a file's again when it - // changes); one bigger than the whole store is not kept. - if (body.len > max_diag_bytes) { - sa.free(body); - return; - } - if (slot) |d| { - c.diag_bytes -= d.body.len; - sa.free(d.body); - d.body = body; - c.diag_bytes += body.len; - } else { - while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { - const old = c.diags.orderedRemove(0); - c.diag_bytes -= old.body.len; - sa.free(old.uri); - sa.free(old.body); - } - const owned = sa.dupe(u8, uri) catch { - sa.free(body); - return; - }; - c.diags.append(sa, .{ .uri = owned, .body = body }) catch { - sa.free(owned); - sa.free(body); - return; - }; - c.diag_bytes += body.len; - } - c.cond.broadcast(io); // waitFresh watches this - }, - .@"$/progress" => { - const value = get(params, "value") orelse return; - const pkind = str(get(value, "kind")) orelse return; - const msg = str(get(value, "message")) orelse ""; - c.mu.lockUncancelable(io); - if (c.gen != g) { - c.mu.unlock(io); - return; - } - if (std.mem.eql(u8, pkind, "begin")) { - c.progress += 1; - c.cond.broadcast(io); - const title = str(get(value, "title")) orelse ""; - c.title_len = @intCast(@min(title.len, c.title.len)); - @memcpy(c.title[0..c.title_len], title[0..c.title_len]); - var tbuf: [48]u8 = undefined; - const t = tbuf[0..c.title_len]; - @memcpy(t, c.title[0..c.title_len]); - c.mu.unlock(io); - post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); - return; - } - if (std.mem.eql(u8, pkind, "report")) { - var tbuf: [48]u8 = undefined; - const t = tbuf[0..c.title_len]; - @memcpy(t, c.title[0..c.title_len]); - const pct = num(get(value, "percentage")); - c.mu.unlock(io); - if (pct) |p| - post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) - else - post(si, .chatty, "{s}: {s} {s}", .{ specs[si].name, t, msg }); - return; - } - // end - c.progress -= 1; - const idle = c.progress <= 0; - if (idle) c.progress = 0; - c.cond.broadcast(io); - c.mu.unlock(io); - // the setpoint every burst of progress ends on; `.always` + the - // dedupe above means it lands exactly once however the reports raced - if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); - }, - .@"window/showMessage" => { - const t = num(get(params, "type")) orelse 3; - if (t > 2) return; // info/log are the server's diary, not the user's - post(si, .always, "{s}: {s}", .{ specs[si].name, str(get(params, "message")) orelse "" }); - }, - // rust-analyzer's precise quiescence signal, opted into via - // experimental.serverStatusNotification - .@"experimental/serverStatus" => { - const health = str(get(params, "health")) orelse "ok"; - const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; - c.mu.lockUncancelable(io); - if (c.gen == g) { - c.loading = !quiescent; - c.cond.broadcast(io); - } - c.mu.unlock(io); - if (!std.mem.eql(u8, health, "ok")) - post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) - else if (quiescent) - post(si, .always, "{s}: ready", .{specs[si].name}); - }, - } -} - -// ------------------------------------------------------------- introspection - -// ------------------------------------------------------------------ plumbing - -/// `"textDocument":{"uri":U}` — the params every request about a file -/// starts with. -fn docParams(arena: std.mem.Allocator, uri: []const u8) Err!std.ArrayList(u8) { - var b: std.ArrayList(u8) = .empty; - try b.appendSlice(arena, "\"textDocument\":{\"uri\":"); - try jstr(&b, arena, uri); - try b.appendSlice(arena, "}"); - return b; -} - -/// `"textDocument":{"uri":U},"position":{...}` — the params shared by every -/// position request. -fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList(u8) { - var b = try docParams(arena, uri); - try b.print(arena, ",\"position\":{{\"line\":{d},\"character\":{d}}}", .{ pos.line, pos.ch }); - return b; -} - -/// A message to the server from a query, the conn's mutex let go while it is -/// written: the reader goes on taking the server's output meanwhile, which a -/// server may be waiting to write before it reads more of ours. -fn send(c: *Conn, io: std.Io, body: []const u8, deadline: i64) Err!void { - const sock = c.sock; - c.mu.unlock(io); - defer c.mu.lockUncancelable(io); - return frame(c, io, sock, body, deadline); -} - -fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err!void { - if (sock < 0) return error.Dead; - c.write_mu.lockUncancelable(io); - defer releaseWrite(c, io, sock); - var hdr: [64]u8 = undefined; - const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return error.Protocol; - var started = false; - try sockWrite(io, sock, h, deadline, &started); - try sockWrite(io, sock, body, deadline, &started); -} - -/// The reader's answer to a server request: written now if the socket is -/// free, else queued for the query writing (bounded; one that does not fit is -/// dropped, and the server's request goes unanswered). -fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void { - var hdr: [64]u8 = undefined; - const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch unreachable; // a usize's 20 digits and a short header fit 64 - c.replies_mu.lockUncancelable(io); - const half = &c.replies[c.filling]; - const len = &c.replies_len[c.filling]; - if (len.* + h.len + body.len <= half.len) { - @memcpy(half[len.*..][0..h.len], h); - @memcpy(half[len.* + h.len ..][0..body.len], body); - len.* += h.len + body.len; - } - c.replies_mu.unlock(io); - if (c.write_mu.tryLock()) releaseWrite(c, io, sock); -} - -/// Lets the socket go, first sending what the reader queued meanwhile, and -/// again for what it queues while that goes out. -fn releaseWrite(c: *Conn, io: std.Io, sock: c_int) void { - while (true) { - c.replies_mu.lockUncancelable(io); - const sent = c.filling; - const n = c.replies_len[sent]; - if (n > 0) c.filling ^= 1; - c.replies_mu.unlock(io); - if (n > 0) { - var started = false; - sockWrite(null, sock, c.replies[sent][0..n], nowMs() + reply_ms, &started) catch {}; - c.replies_len[sent] = 0; - } - c.write_mu.unlock(io); - c.replies_mu.lockUncancelable(io); - const more = c.replies_len[c.filling] > 0; - c.replies_mu.unlock(io); - if (!more or !c.write_mu.tryLock()) return; - } -} - -/// Writes `bytes`, `started` once any byte of their message is out. Before -/// then, the deadline and a cancel stop it; after, the message is finished -/// however long the server takes to read it (bounded by wedge_ms), since -/// half of one ends the server's reading of every message after it. -fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started: *bool) Err!void { - var off: usize = 0; - while (off < bytes.len) { - if (!started.*) { - if (deadline - nowMs() <= 0) return error.Timeout; - if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled; - } else if (nowMs() - deadline > wedge_ms) return error.Dead; - var pfd = [_]libc.pollfd{.{ .fd = sock, .events = libc.POLL.OUT, .revents = 0 }}; - const pr = libc.poll(&pfd, 1, 500); - if (pr < 0) { - if (libc.errno(pr) == .INTR) continue; - return error.Dead; - } - if (pr == 0) continue; - const n = libc.send(sock, bytes.ptr + off, bytes.len - off, msg_nosignal); - if (n < 0) { - const e = libc.errno(n); - if (e == .INTR or e == .AGAIN) continue; - return error.Dead; - } - if (n == 0) return error.Dead; - started.* = true; - off += @intCast(n); - } -} - -fn nowMs() i64 { - var ts: libc.timespec = undefined; - _ = libc.clock_gettime(.MONOTONIC, &ts); - return @as(i64, @intCast(ts.sec)) * 1000 + @divTrunc(@as(i64, @intCast(ts.nsec)), 1_000_000); -} - -/// A path as a `file://` URI, raw (no JSON quotes). Everything outside the -/// unreserved set is percent-encoded; `/` stays a separator. -fn uriOf(b: *std.ArrayList(u8), arena: std.mem.Allocator, path: []const u8) Err!void { - try b.appendSlice(arena, "file://"); - for (path) |ch| { - if (std.ascii.isAlphanumeric(ch) or ch == '/' or ch == '-' or ch == '_' or ch == '.' or ch == '~') { - try b.append(arena, ch); - } else { - try b.print(arena, "%{X:0>2}", .{ch}); - } - } -} - -/// A JSON string. Invalid UTF-8 becomes `?` one byte at a time rather than -/// U+FFFD: a buffer being typed into may be invalid mid-keystroke, and a -/// replacement that changed byte lengths would move every offset after it. -fn jstr(b: *std.ArrayList(u8), arena: std.mem.Allocator, s: []const u8) Err!void { - try b.append(arena, '"'); - var i: usize = 0; - while (i < s.len) { - const ch = s[i]; - if (ch < 0x80) { - switch (ch) { - '"' => try b.appendSlice(arena, "\\\""), - '\\' => try b.appendSlice(arena, "\\\\"), - '\n' => try b.appendSlice(arena, "\\n"), - '\r' => try b.appendSlice(arena, "\\r"), - '\t' => try b.appendSlice(arena, "\\t"), - else => if (ch < 0x20) - try b.print(arena, "\\u{x:0>4}", .{ch}) - else - try b.append(arena, ch), - } - i += 1; - continue; - } - const l = std.unicode.utf8ByteSequenceLength(ch) catch { - try b.append(arena, '?'); - i += 1; - continue; - }; - if (i + l > s.len or !std.unicode.utf8ValidateSlice(s[i .. i + l])) { - try b.append(arena, '?'); - i += 1; - continue; - } - try b.appendSlice(arena, s[i .. i + l]); - i += l; - } - try b.append(arena, '"'); -} - -const Pos = struct { line: u32, ch: u32 }; - -// std.json.Value navigation: optional-in, optional-out, so a missing field -// and a wrongly-typed one read the same and neither can panic on a server -// that sends the unexpected. - -fn get(v: ?std.json.Value, key: []const u8) ?std.json.Value { - const o = v orelse return null; - if (o != .object) return null; - return o.object.get(key); -} - -fn str(v: ?std.json.Value) ?[]const u8 { - const o = v orelse return null; - return if (o == .string) o.string else null; -} - -fn num(v: ?std.json.Value) ?i64 { - const o = v orelse return null; - return if (o == .integer) o.integer else null; -} - -fn items(v: ?std.json.Value) []std.json.Value { - const o = v orelse return &.{}; - return if (o == .array) o.array.items else &.{}; -} - -const Range = Scip.Range; - -fn rangeOf(range: ?std.json.Value) ?Range { - const st = get(range, "start") orelse return null; - const en = get(range, "end") orelse return null; - return .{ - .sl = coord(get(st, "line")) orelse return null, - .sc = coord(get(st, "character")) orelse return null, - .el = coord(get(en, "line")) orelse return null, - .ec = coord(get(en, "character")) orelse return null, - }; -} - -/// One protocol coordinate, VALIDATED rather than clamped: a negative line is -/// not "line zero", it is a malformed response, and a value past u32 would -/// panic the @intCast that follows. Server bytes are not trusted bytes. -fn coord(v: ?std.json.Value) ?u32 { - const n = num(v) orelse return null; - if (n < 0 or n > std.math.maxInt(u32)) return null; - return @intCast(n); -} - -// ----------------------------------------------------------------- tests - -test "caller trees reverse incoming paths and merge shared callers and sites" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const arena = arena_state.allocator(); - const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"left\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}]},{\"from\":{\"name\":\"right\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":2,\"character\":0},\"end\":{\"line\":2,\"character\":4}}]},{\"from\":{\"name\":\"main\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}]}]", .{}); - const entries = try serverHops(arena, fixture); - var tree: CallTree = .{}; - try tree.addPath(arena, &.{ entries[0], entries[2], entries[4] }, false); - try tree.addPath(arena, &.{ entries[1], entries[3], entries[4] }, false); - try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len); - try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len); - const root = tree.nodes.items[tree.roots.items[0]]; - try std.testing.expectEqualStrings("main", root.call.name); - try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len); - const page = tree.nodes.items[root.children.items[0]]; - try std.testing.expectEqual(@as(usize, 2), page.children.items.len); - try std.testing.expectEqual(@as(usize, 2), page.ranges.items.len); - try std.testing.expect(!root.ranges.items[0].focus); - for (page.ranges.items) |site| try std.testing.expect(!site.focus); - for (page.children.items) |id| try std.testing.expect(tree.nodes.items[id].ranges.items[0].focus); - var out: std.Io.Writer.Allocating = .init(arena); - var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer }; - try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); - const text = out.written(); - try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, lsp.callstack_match)); - const main_at = std.mem.indexOf(u8, text, " main\n").?; - const page_at = std.mem.indexOf(u8, text, " page\n").?; - const left_at = std.mem.indexOf(u8, text, " left\n").?; - const right_at = std.mem.indexOf(u8, text, " right\n").?; - try std.testing.expect(main_at < page_at and page_at < left_at and left_at < right_at); - try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "main_call();")); - try std.testing.expect(std.mem.indexOf(u8, text, "page_left();").? < std.mem.indexOf(u8, text, "page_right();").?); - try std.testing.expect(std.mem.indexOf(u8, text, "├──┬ test.c:4:") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "╰──┬ test.c:1:") != null); - var recursive: CallTree = .{}; - try recursive.addPath(arena, &.{ entries[0], entries[0] }, true); - try std.testing.expect(!recursive.nodes.items[recursive.roots.items[0]].cycle); - try std.testing.expect(recursive.nodes.items[1].cycle); -} - -test "test callers sort after the rest, each group by place" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const arena = arena_state.allocator(); - const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"test b\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"z\",\"uri\":\"file:///b.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"x\",\"uri\":\"file:///a_test.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}}},{\"from\":{\"name\":\"y\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":5,\"character\":0},\"end\":{\"line\":5,\"character\":1}}}}]", .{}); - var tree: CallTree = .{}; - for (try serverHops(arena, fixture)) |hop| try tree.nodes.append(arena, .{ .call = hop.call }); - var order = [_]usize{ 0, 1, 2, 3 }; - std.mem.sort(usize, &order, @as(*const CallTree, &tree), callerLess); - try std.testing.expectEqualSlices(usize, &.{ 3, 1, 0, 2 }, &order); -} - -test "a mailbox wait is a cancelation point: a canceled worker stops waiting" { - const io = std.testing.io; - var c: Conn = .{}; - const Waiter = struct { - fn run(conn: *Conn, wio: std.Io) error{Canceled}!void { - conn.mu.lockUncancelable(wio); - defer conn.mu.unlock(wio); - while (true) _ = try timedWait(conn, wio, nowMs() + 60_000); - } - }; - var future = try io.concurrent(Waiter.run, .{ &c, io }); - try std.testing.expectError(error.Canceled, future.cancel(io)); -} - -test "callstack cross-crate paths remain resolvable without absolute path clutter" { - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const arena = arena_state.allocator(); - const range = try std.json.parseFromSliceLeaky(std.json.Value, arena, - \\{"start":{"line":1,"character":3},"end":{"line":1,"character":6}} - , .{}); - var out: std.Io.Writer.Allocating = .init(arena); - var cx: Cx = .{ .io = std.testing.io, .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true }; - try emitRange(&cx, .utf8, "file:///workspace/entry/src/entry.rs", range, "fn run()"); - try std.testing.expectEqualStrings("../../entry/src/entry.rs:2:4-6 fn run()\n", out.written()); -} - -test "LSP client rename and format propagate incomplete edit encoding" { - const gpa = std.testing.allocator; - const uri = "file:///file.c"; - const parsed = try std.json.parseFromSlice(std.json.Value, gpa, - \\{"changes":{"file:///file.c":[{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":3}},"newText":"A%\n"},{"range":{"start":{"line":0,"character":4},"end":{"line":0,"character":7}},"newText":"B"}]}} - , .{}); - defer parsed.deinit(); - const expected = "@put 0 3 A%25%0A\n@put 4 7 B\n"; - for ([_]bool{ true, false }) |rename| { - var buffer: [128]u8 = undefined; - for (0..expected.len + 1) |capacity| { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var out: std.Io.Writer = .fixed(buffer[0..capacity]); - var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = "abc xyz", .out = &out }; - const result = if (rename) - renameEdits(&cx, .utf8, uri, parsed.value, cx.cur_src, "abc", &.{}) - else - formatEdits(&cx, .utf8, get(get(parsed.value, "changes"), uri).?, cx.cur_src); - if (capacity < expected.len) { - try std.testing.expectError(error.WriteFailed, result); - } else { - try result; - try std.testing.expectEqualStrings(expected, out.buffered()); - } - } - } -} - -test "a rename answered for this file alone, while another open file says the old name, previews and names it" { - const gpa = std.testing.allocator; - const parsed = try std.json.parseFromSlice(std.json.Value, gpa, - \\{"changes":{"file:///w/util.zig":[{"range":{"start":{"line":0,"character":7},"end":{"line":0,"character":10}},"newText":"sum"}]}} - , .{}); - defer parsed.deinit(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var buffer: [512]u8 = undefined; - var out: std.Io.Writer = .fixed(&buffer); - var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/w", .cur_path = "/w/util.zig", .cur_src = "pub fn add() void {}", .out = &out }; - try renameEdits(&cx, .utf8, "file:///w/util.zig", parsed.value, cx.cur_src, "add", &.{"/w/main.zig"}); - try std.testing.expectEqualStrings("util.zig:1:8-10 sum\nmain.zig: also says add, which the server did not rename\n", out.buffered()); - try std.testing.expectEqualStrings("add", identAt("x = add(1);", 6)); - try std.testing.expect(holdsWord("util.add(1)", "add") and !holdsWord("addNumbers", "add")); -} - -test "frameNext distinguishes incomplete, valid and poison frames" { - try std.testing.expectEqual(FrameStep.incomplete, frameNext("Content-Length: 5\r\n")); - try std.testing.expectEqual(FrameStep.incomplete, frameNext("Content-Length: 5\r\n\r\nhel")); - const one = frameNext("Content-Length: 5\r\n\r\nhello").frame; - try std.testing.expectEqualStrings("hello", "Content-Length: 5\r\n\r\nhello"[one.body_start..one.body_end]); - const two = "content-length: 2\r\nX-Other: y\r\n\r\nab" ++ "Content-Length: 1\r\n\r\nz"; - const first = frameNext(two).frame; - try std.testing.expectEqualStrings("ab", two[first.body_start..first.body_end]); - const second = frameNext(two[first.consumed..]).frame; - try std.testing.expectEqualStrings("z", two[first.consumed..][second.body_start..second.body_end]); - // complete-but-unusable headers can never re-synchronize: poison, not - // "keep buffering" — the wedge a review found and this line pins - try std.testing.expectEqual(FrameStep.poison, frameNext("Content-Length: nope\r\n\r\n")); - try std.testing.expectEqual(FrameStep.poison, frameNext("X-Only: y\r\n\r\n")); - try std.testing.expectEqual(FrameStep.poison, frameNext("Content-Length: 67108865\r\n\r\n")); -} - -test "server coordinates are validated, not clamped" { - var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena_state.deinit(); - const arena = arena_state.allocator(); - const bad = [_][]const u8{ - \\{"start":{"line":-1,"character":0},"end":{"line":0,"character":1}} - , - \\{"start":{"line":0,"character":0},"end":{"line":0,"character":4294967296}} - , - \\{"start":{"line":0,"character":0},"end":{"line":0}} - }; - for (bad) |json| { - const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}); - try std.testing.expect(rangeOf(v) == null); - } - // strict offsets: past-EOL and past-EOF are refusals, EOL itself is real - const src = "ab\ncd"; - try std.testing.expectEqual(@as(?usize, 2), strictOffset(src, 0, 2, .utf8)); - try std.testing.expect(strictOffset(src, 0, 3, .utf8) == null); - try std.testing.expect(strictOffset(src, 2, 0, .utf8) == null); - try std.testing.expectEqual(@as(?usize, 5), strictOffset(src, 1, 2, .utf8)); -} - -test "uri round-trips spaces and utf-8" { - var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena_state.deinit(); - const arena = arena_state.allocator(); - var b: std.ArrayList(u8) = .empty; - try uriOf(&b, arena, "/a dir/naïve.rs"); - try std.testing.expectEqualStrings("file:///a%20dir/na%C3%AFve.rs", b.items); - try std.testing.expectEqualStrings("/a dir/naïve.rs", pathOf(arena, b.items).?); - try std.testing.expect(pathOf(arena, "file://host/x") == null); - // a %0A would split one location into two rows: rejected wholesale - try std.testing.expect(pathOf(arena, "file:///tmp/a%0A/tmp/b:1:1") == null); - try std.testing.expect(pathOf(arena, "file:///tmp/a%00b") == null); - try std.testing.expect(pathOf(arena, "https://x/y") == null); -} - -test "posOf and strictOffset invert each other under both encodings" { - const src = "aé𝕏b\ncd\n"; // é: 2 bytes/1 unit, 𝕏: 4 bytes/2 units - inline for (.{ Enc.utf8, Enc.utf16 }) |enc| { - const off: u32 = 7; // the 'b' - const p = posOf(src, off, enc); - try std.testing.expectEqual(@as(u32, 0), p.line); - try std.testing.expectEqual(@as(?usize, off), strictOffset(src, p.line, p.ch, enc)); - } - const p2 = posOf("aé𝕏b\ncd\n", 10, .utf16); // the 'd' - try std.testing.expectEqual(@as(u32, 1), p2.line); - try std.testing.expectEqual(@as(u32, 1), p2.ch); -} - -test "rootOf takes the top-most marker and falls back to git then dir" { - // libc mkdtemp under /tmp rather than std.testing.tmpDir: rootOf probes - // with access(2) on ABSOLUTE paths, and /tmp has no ancestor markers to - // muddy the fallback assertions the way the repo's own .zig-cache does. - var tpl: [64:0]u8 = undefined; - _ = std.fmt.bufPrintSentinel(&tpl, "/tmp/pardes-rootof-XXXXXX", .{}, 0) catch unreachable; - const base_z = mkdtemp(&tpl) orelse return error.TestUnexpectedResult; - const base = std.mem.span(base_z); - defer { - var cmd: [128:0]u8 = undefined; - if (std.fmt.bufPrintSentinel(&cmd, "rm -rf {s}", .{base}, 0)) |z| _ = system(z.ptr) else |_| {} - } - var pb: [128:0]u8 = undefined; - for ([_][]const u8{ "/ws", "/ws/member", "/ws/member/src" }) |d| { - const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, d }, 0); - try std.testing.expect(libc.mkdir(z.ptr, 0o700) == 0); - } - for ([_][]const u8{ "/ws/Cargo.toml", "/ws/member/Cargo.toml" }) |f| { - const z = try std.fmt.bufPrintSentinel(&pb, "{s}{s}", .{ base, f }, 0); - const fd = libc.open(z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true }, @as(libc.mode_t, 0o600)); - try std.testing.expect(fd >= 0); - _ = libc.close(fd); - } - const deep = try std.fmt.bufPrintSentinel(&pb, "{s}/ws/member/src", .{base}, 0); - const markers = [_][]const u8{"Cargo.toml"}; - const root = rootOf(deep, &markers); - try std.testing.expect(std.mem.endsWith(u8, root, "/ws")); - // no language marker and no .git anywhere under /tmp: the asking dir wins - const nothing = rootOf(deep, &.{"no-such-marker"}); - try std.testing.expect(std.mem.startsWith(u8, deep, nothing)); -} - -test "language server discovery honours PATH and overrides before the user bin directory" { - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const io = std.testing.io; - try tmp.dir.createDirPath(io, ".local/bin"); - try tmp.dir.createDirPath(io, "path-bin"); - for ([_][]const u8{ ".local/bin/zls", "path-bin/zls" }) |path| { - const file = try tmp.dir.createFile(io, path, .{ .permissions = .fromMode(0o700) }); - file.close(io); - } - var home_buf: [4096]u8 = undefined; - const home = home_buf[0..try tmp.dir.realPath(io, &home_buf)]; - var path_buf: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/path-bin", .{home}); - var out: [4096:0]u8 = undefined; - try std.testing.expect(std.mem.endsWith(u8, findBin("zls", path, home, &out).?, "/path-bin/zls")); - try std.testing.expect(std.mem.endsWith(u8, findBin("zls", "/no-such-bin", home, &out).?, "/.local/bin/zls")); - try std.testing.expect(findBin("", path, home, &out) == null); - try std.testing.expect(findBin("/no-such-bin/zls", path, home, &out) == null); - try std.testing.expect(findBin("zls", "", "", &out) == null); - try std.testing.expect(findBin(path, "", home, &out) == null); // a directory is not executable code -} - -test "specFor routes extensions and honours the disable env" { - try std.testing.expect(specFor("/x/main.rs") != null); - try std.testing.expect(specFor("/x/README.md") == null); - try std.testing.expectEqualStrings("rust-analyzer", specs[specFor("/x/main.rs").?].name); - if (libc.getenv("PARDES_LSP_ZIG") == null) try std.testing.expectEqualStrings("zls", specs[specFor("/x/main.zig").?].name); -} - -test "the transport this host actually gives us is a pair, and both ends are close-on-exec" { - // The spawn's FIRST fallible step, and for one release on macOS its last: - // `SOCK.CLOEXEC` is spelled for darwin in zig's libc bindings and rejected - // by darwin's socketpair(2), so this returned EPROTONOSUPPORT and no - // language server was ever forked on that platform. Nothing above the - // transport can notice — `ensure` reports the same `NoServer` a missing - // binary does — so the check belongs here, on the real function, in a test - // that runs on the host rather than on the linux target the snapshot - // suite cross-compiles to. - var sv: [2]libc.fd_t = undefined; - try std.testing.expect(transportPair(&sv)); - defer { - _ = libc.close(sv[0]); - _ = libc.close(sv[1]); - } - - // close-on-exec on both ends, however the platform got there: the flag on - // linux, fcntl on darwin. Without it every pty shell forked afterwards - // inherits the server's socket, which is the bug host_io.zig fixed for the - // pty master. - const FD_CLOEXEC: c_int = 1; - for (sv) |fd| try std.testing.expect(libc.fcntl(fd, libc.F.GETFD, @as(c_int, 0)) & FD_CLOEXEC != 0); - - // and it is a connected PAIR, not two unrelated descriptors - const msg = "ping"; - try std.testing.expectEqual(@as(isize, msg.len), libc.write(sv[0], msg, msg.len)); - var got: [8]u8 = undefined; - try std.testing.expectEqual(@as(isize, msg.len), libc.read(sv[1], &got, got.len)); - try std.testing.expectEqualStrings(msg, got[0..msg.len]); -} - -test "LSP source snippets preserve indentation with UTF16 byte ranges and prose stays trimmed" { - const gpa = std.testing.allocator; - const source = "\t const 𝕏 = target; \t\r\n"; - for ([_]bool{ false, true }) |multiline| { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const json = try std.fmt.allocPrint(arena.allocator(), "{{\"start\":{{\"line\":0,\"character\":14}},\"end\":{{\"line\":{d},\"character\":20}}}}", .{@as(u8, if (multiline) 1 else 0)}); - const parsed = try std.json.parseFromSlice(std.json.Value, arena.allocator(), json, .{}); - for ([_]bool{ false, true }) |prose| { - var buffer: [256]u8 = undefined; - var out: std.Io.Writer = .fixed(&buffer); - var cx: Cx = .{ .io = std.testing.io, .arena = arena.allocator(), .base = "/", .cur_path = "/file.c", .cur_src = source, .out = &out }; - try emitRange(&cx, .utf16, "file:///file.c", parsed.value, if (prose) " explanatory label \t" else ""); - const expected = try std.fmt.allocPrint(arena.allocator(), "file.c:1:17{s} {s}\n", .{ - if (multiline) "" else "-22", - if (prose) "explanatory label" else "\t const 𝕏 = target; \t", - }); - try std.testing.expectEqualStrings(expected, out.buffered()); - try std.testing.expectEqual(@as(usize, 1), cx.rows); - } - } -} - -test "a language with no server to start says so, not that it did not answer" { - const si = specFor("/x/a.py") orelse return; - const was = conns[si].state; - conns[si].state = .disabled; - defer conns[si].state = was; - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - var buf: [256]u8 = undefined; - var out: std.Io.Writer = .fixed(&buf); - try query(std.testing.io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); - try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); -} - -test "Lspinfo before any query says a server is not started yet, not off" { - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - try status(std.testing.io, "/x/notes.txt", &out.writer); - try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null); -} - -test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" { - if (libc.getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest; - const io = std.testing.io; - const si = specFor("/x/a.zig").?; - const c = &conns[si]; - c.mu.lockUncancelable(io); - const was = .{ c.state, c.retry_after_ms }; - c.state = .dead; - c.retry_after_ms = nowMs() + 4500; - c.mu.unlock(io); - defer { - c.mu.lockUncancelable(io); - c.state = was[0]; - c.retry_after_ms = was[1]; - c.mu.unlock(io); - } - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - var out: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer out.deinit(); - try query(std.testing.io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); - try std.testing.expect(std.mem.indexOf(u8, out.written(), "zls failed recently; retry in 5s") != null); -} - -test "reaping a server takes what it started with it: its process group goes, its children too" { - var fds: [2]libc.fd_t = undefined; - if (libc.pipe(&fds) != 0) return error.SkipZigTest; - const pid = libc.fork(); - if (pid < 0) return error.SkipZigTest; - if (pid == 0) { - _ = libc.setsid(); - const child = libc.fork(); - if (child == 0) { - while (true) _ = usleep(100_000); - } - var word: [4]u8 = @bitCast(@as(i32, child)); - _ = libc.write(fds[1], &word, 4); - while (true) _ = usleep(100_000); - } - _ = libc.close(fds[1]); - var word: [4]u8 = undefined; - try std.testing.expectEqual(@as(isize, 4), libc.read(fds[0], &word, 4)); - _ = libc.close(fds[0]); - const grandchild: libc.pid_t = @bitCast(word); - reap(pid); - // Gone, or a zombie waiting for its new parent to reap it: not running. - var tries: u32 = 0; - const running = while (tries < 200) : (tries += 1) { - var path: [64]u8 = undefined; - const stat_path = try std.fmt.bufPrintSentinel(&path, "/proc/{d}/stat", .{grandchild}, 0); - const fd = libc.open(stat_path, .{ .ACCMODE = .RDONLY }); - if (fd < 0) break false; - var buf: [256]u8 = undefined; - const n = libc.read(fd, &buf, buf.len); - _ = libc.close(fd); - if (n > 0) if (std.mem.lastIndexOfScalar(u8, buf[0..@intCast(n)], ')')) |close| { - if (buf[close + 2] == 'Z') break false; - }; - _ = usleep(10_000); - } else true; - if (running) _ = libc.kill(grandchild, .KILL); - try std.testing.expect(!running); -} diff --git a/src/macos/Info.plist b/src/macos/Info.plist deleted file mode 100644 index 3cb2e488..00000000 --- a/src/macos/Info.plist +++ /dev/null @@ -1,76 +0,0 @@ - - - - - CFBundleName - pardes - CFBundleIdentifier - cafe.0x4200.pardes - CFBundleExecutable - pardes - CFBundlePackageType - APPL - - CFBundleShortVersionString - 0.0.0 - CFBundleVersion - 3 - - CFBundleIconFile - pardes - NSHighResolutionCapable - - - LSMinimumSystemVersion - 13.0 - LSApplicationCategoryType - public.app-category.developer-tools - NSPrincipalClass - NSApplication - - NSSupportsAutomaticTermination - - NSSupportsSuddenTermination - - - CFBundleDocumentTypes - - - CFBundleTypeName - Text Document - CFBundleTypeRole - Editor - LSHandlerRank - Alternate - LSItemContentTypes - - public.plain-text - - - - CFBundleTypeName - Folder - CFBundleTypeRole - Editor - LSHandlerRank - Alternate - LSItemContentTypes - - public.folder - - - - - diff --git a/src/macos/Sources/AppDelegate.swift b/src/macos/Sources/AppDelegate.swift deleted file mode 100644 index dbc0fbc9..00000000 --- a/src/macos/Sources/AppDelegate.swift +++ /dev/null @@ -1,704 +0,0 @@ -import AppKit - -// The macOS host: one window, one view, one core. libpardes owns the state -// machine, the ptys and every worker thread; this file owns the window, the -// menu bar, and the pump that lets the core move at all. -// -// PardesView translates events and calls pardes_key / pardes_mouse / -// pardes_scroll itself, but never pardes_tick — the core only queues what it -// was told and does nothing until it is pumped. Rather than grow the view's -// delegate a third method for "I just fed the core", the view posts -// pardesDidInputNotification after every input call and we answer it with -// pump(). That name is declared once, in PardesView.swift, precisely so the two -// files cannot drift apart on a string literal. - -final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { - private var window: NSWindow! - private var view: PardesView! - // One display-clock chain at a time. Input and pty notifications may all - // call pump(), but none advances animation; they only observe this flag and - // leave the already-scheduled frame alone. - private var pumpScheduled: Bool = false - /// The display's own clock, when the OS will lend us one. - /// - /// The fallback below is a `DispatchQueue.asyncAfter(0.016)` chain re-armed - /// AFTER each frame's tick, drain and draw, so its real period is 16 ms plus - /// all of that — comfortably slower than 60 Hz, and jittery, and never in - /// phase with the refresh. That is what makes an animation look choppy even - /// when nothing is dropping frames. A display link fires once per refresh, - /// phase-locked to vsync, which is the cadence the picture is actually - /// presented at. - /// - /// Cadence is now only a SMOOTHNESS question: `pardes_animation_tick` - /// spends measured elapsed time, so a 120 Hz link does not double-speed an - /// animation and a slow one does not halve it. - /// Held as `AnyObject` because a stored property cannot carry - /// `@available`, and this file still deploys to macOS 13. - private var displayLink: AnyObject? - // The core is a singleton with no "is it alive" query, and Finder can hand - // us documents before applicationDidFinishLaunching runs. Every entry point - // that would call into libpardes from outside the launch sequence checks - // this first; opens that arrive early queue below instead of crashing in a - // core that has not been constructed. - private var coreIsUp: Bool = false - private var pendingOpens: [URL] = [] - - func applicationDidFinishLaunching(_ notification: Notification) { - // Captured before the chdir below, because `pardes ./foo.zig` from a - // terminal means foo.zig in the shell's directory, not in $HOME. - let launchDirectory = FileManager.default.currentDirectoryPath - - // A bundle launched from Finder, the Dock or `open(1)` inherits cwd `/` - // — launchd's, not any shell's — so the first pane's shell would start - // at the root of the disk and every relative path the user types would - // resolve there. A binary run from a terminal inherits that terminal's - // directory, which is already what was meant, so only the `/` case is - // corrected: anything else is somebody's deliberate choice. - if launchDirectory == "/" { - FileManager.default.changeCurrentDirectoryPath(NSHomeDirectory()) - } - - installMainMenu() - - // Initial body size. PardesView owns later Ctrl+/Ctrl- changes and - // rebuilds both body and tagline metrics before publishing the resize. - view = PardesView(fontSize: defaultFontSize) - - let want = NSSize(width: 1000, height: 700) - window = NSWindow( - contentRect: NSRect(origin: .zero, size: want), - styleMask: [.titled, .closable, .miniaturizable, .resizable], - backing: .buffered, - defer: false) - window.title = "pardes" - // We hold this window strongly for the life of the app. Leaving - // isReleasedWhenClosed on would have AppKit release it out from under - // that reference the moment the close button is pressed. - window.isReleasedWhenClosed = false - let container = NSView(frame: NSRect(origin: .zero, size: want)) - container.autoresizesSubviews = true - view.frame = container.bounds - view.autoresizingMask = [.width, .height] - container.addSubview(view) - window.contentView = container - - // Trim the content box down to whole cells: a partial column or row is - // dead space the core can never draw into. - window.setContentSize(NSSize( - width: (want.width / view.cellWidth).rounded(.down) * view.cellWidth, - height: (want.height / view.cellHeight).rounded(.down) * view.cellHeight)) - // Autosave after the snap, never before: on a first run there is no - // saved frame and the window must still open at the snapped default, - // and registering the name first would have AppKit write the unsnapped - // 1000x700 out as the remembered geometry. - window.setFrameAutosaveName("pardes") - // setFrameAutosaveName only arms the saving half; the restore is this - // call, and it reports whether there was anything to restore. Both must - // happen before pardes_init, because the grid we boot the core with has - // to be the grid the window actually ends up at. - if !window.setFrameUsingName("pardes") { - window.center() - } - // Resize in whole cells. Increments are measured from the window's - // current size rather than from zero, which is why the snap above still - // matters: without it every drag would land a half-column short of the - // frame, and the view would draw a strip it can never put a glyph in. - window.contentResizeIncrements = NSSize(width: view.cellWidth, height: view.cellHeight) - // One core per process, so a second tab would be an empty window with - // no grid behind it. macOS offers tabs on any titled resizable window - // unless told otherwise. - window.tabbingMode = .disallowed - // What the core is wearing, not a constant agreed by hand — two things - // draw and both have to say the same thing: the view fills its own - // bounds, and AppKit fills the titlebar and every pixel of a live - // resize the view has not caught up with yet. Without that agreement - // the gap flashes on every drag. It also owns window.appearance: a dark - // window with a light-mode titlebar reads as a bug, and so does the - // reverse the moment someone wears `acme`. - applyTheme() - // On screen before pardes_init, so that the backingScaleFactor read - // when seeding the cell metrics below is the one of the screen the - // window actually landed on. Drawing before the core exists costs an - // empty frame; metrics seeded at 1x would stay wrong forever, because - // a scale change moves no bounds and so fires no resize. - window.makeKeyAndOrderFront(nil) - // AppKit may promote a content view that accepts first responder on its - // own, but "may" is not something to bet every keystroke on, and there - // is no click-to-focus path here that would recover it. - window.makeFirstResponder(view) - // activate(ignoringOtherApps:) is deprecated in favour of activate() on - // the 14 SDK, but activate() does not exist at our 13.0 deployment - // target and the deprecation does not fire below it. This is the call - // to change the day macos_min_version reaches 14. - NSApp.activate(ignoringOtherApps: true) - - var runtime = pardes_runtime_s( - userdata: Unmanaged.passUnretained(self).toOpaque(), - wakeup: { ud in - // A pty reader thread. Every other function in pardes.h is - // main-thread-only, so this hop is the entire body — touching - // any core state here would be the race the hop exists to - // avoid. - let host = Unmanaged.fromOpaque(ud!).takeUnretainedValue() - DispatchQueue.main.async { host.pump() } - }, - set_clipboard: { _, text, len in - // Main thread, from inside pardes_tick. `text` is borrowed for - // the length of the call, so the String has to be a copy. - var yank: String = "" - if let text = text, len > 0 { - let bytes = UnsafeRawBufferPointer(start: UnsafeRawPointer(text), count: len) - yank = String(decoding: bytes, as: UTF8.self) - } - let pasteboard = NSPasteboard.general - pasteboard.clearContents() - _ = pasteboard.setString(yank, forType: .string) - }, - read_clipboard: { _ in - // Also the main thread, also inside pardes_tick — but this one - // answers immediately: NSPasteboard reads are synchronous, so - // the paste lands back in the core before this call returns. - // No pump, deliberately: the tick that emitted the effect is - // still draining and picks up whatever the paste queued. - guard let text = NSPasteboard.general.string(forType: .string) else { return } - AppDelegate.paste(text) - }) - - // The real grid, never a placeholder: the core holds each shell's - // greeting until it has seen a size, so a correction sent afterwards - // arrives with the first prompt already wrapped to the wrong width. - let grid = view.gridSize - let rc = pardes_init(&runtime, grid.cols, grid.rows) - if rc != 0 { - NSLog("pardes: the core failed to boot at \(grid.cols)x\(grid.rows), pardes_init returned \(rc)") - // Not NSApp.terminate — that runs applicationWillTerminate, which - // would call pardes_deinit on a core that never came up. - exit(1) - } - coreIsUp = true - - // Only now, after init. setContentSize above resized the view, and a - // pardesViewDidResize landing before pardes_init would have pushed a - // resize into a core that did not exist yet. - view.delegate = self - NotificationCenter.default.addObserver( - self, selector: #selector(inputArrived(_:)), name: pardesDidInputNotification, object: nil) - - // pardes_init takes no cell metrics, so the core's PDF placement would - // have none until the user first dragged the window. This seeds them, - // and pumps. Repeating the size init just saw is safe by design: the - // core compares the effective pixel viewport, not the resize event, so - // duplicate SIGWINCH-shaped notifications are already a no-op. - pardesViewDidResize(view) - // That pump also consumes a Font from startup config, if present. Only - // now is the face on screen final enough to seed Config's effective - // name and point size; later adopts and zooms report from wear(). - view.reportEffectiveFont() - - // Positional paths, after the first frame's worth of state exists. - // Anything starting with `-` is skipped rather than opened: the core - // has no flags yet, and Finder itself passes `-psn_0_...` on some - // launch paths, which would otherwise become a Look for a file that - // does not exist. - for argument in CommandLine.arguments.dropFirst() where !argument.hasPrefix("-") { - look(absolutePath(of: argument, relativeTo: launchDirectory)) - } - - // Documents that Finder handed us before the core existed. - let queued = pendingOpens - pendingOpens = [] - for url in queued { - look(url.path) - } - } - - // Finder double-click, Dock drop, `open -a pardes file`, and "Open With". - // The URL-array form rather than application(_:openFile:), which has been - // deprecated since 10.13 and only ever reports one path at a time. - func application(_ application: NSApplication, open urls: [URL]) { - // A non-file URL would arrive here only through a URL scheme we do not - // register, but Look wants a path and would treat the scheme prefix as - // part of one. - let files = urls.filter { $0.isFileURL } - guard coreIsUp else { - // Finder sends these between applicationWillFinishLaunching and - // applicationDidFinishLaunching, so they arrive before the core is - // constructed and are replayed at the end of launch. They land - // after the argv paths, which costs nothing: each path is an - // independent Look and only the last one takes focus. - pendingOpens.append(contentsOf: files) - return - } - for url in files { - look(url.path) - } - } - - // ---------------------------------------------------------------- menu - - // Built in code rather than loaded from a nib. There is no Xcode project - // here (see docs/macos.md), so a MainMenu.xib would be a binary blob nobody - // in this tree can edit; the menu is thirty lines of Swift instead. - // - // Every item that reaches the core goes through run(), which is - // pardes_command — the core's own `command` event, the same channel a - // pardes nested inside another one speaks over. So a menu item is exactly - // the text you could have typed into a tag and executed, and there is no - // second vocabulary to keep in step with builtins.zig. - // - // The cost of having a menu at all is that these chords are now the menu's - // and the core can never see them: Cmd+Q, Cmd+H, Opt+Cmd+H, Cmd+O, Cmd+N, - // Cmd+S, Cmd+W, Cmd+V, Cmd+M and Cmd+?. AppKit offers a key equivalent to - // the main menu before the event ever reaches the key window. Every other - // Cmd chord still dies in PardesView, which swallows them because the ABI's - // modifier mask has ctrl, alt and shift and no super bit — a Cmd chord - // handed to the core would arrive as its unmodified letter and type itself - // into the buffer. - private func installMainMenu() { - let appName = ProcessInfo.processInfo.processName - let main = NSMenu() - - // AppKit treats the first top-level item as the application menu - // whatever it is titled, and substitutes the bundle name in bold. - let app = submenu(appName, of: main) - app.addItem(withTitle: "About \(appName)", - action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), - keyEquivalent: "") - app.addItem(.separator()) - app.addItem(withTitle: "Hide \(appName)", - action: #selector(NSApplication.hide(_:)), keyEquivalent: "h") - let hideOthers = app.addItem(withTitle: "Hide Others", - action: #selector(NSApplication.hideOtherApplications(_:)), - keyEquivalent: "h") - hideOthers.keyEquivalentModifierMask = [.command, .option] - app.addItem(withTitle: "Show All", - action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "") - app.addItem(.separator()) - app.addItem(withTitle: "Quit \(appName)", - action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") - - let file = submenu("File", of: main) - file.addItem(command("Open\u{2026}", #selector(menuOpen(_:)), "o")) - file.addItem(command("New", #selector(menuNew(_:)), "n")) - file.addItem(command("Save", #selector(menuSave(_:)), "s")) - file.addItem(.separator()) - // performClose: goes to the key window through the responder chain, so - // it keeps working if this app ever grows a panel. - file.addItem(withTitle: "Close Window", - action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") - - // The workspace tag row's commands, in the place macOS keeps window - // commands. The build hands that row to this menu bar (see - // docs/macos.md): the words are the same builtins the tag carried, - // spelled exactly as a tag Exec would type them, and nothing here is - // editable — the menu is the tag's buttons, not the tag. - let builtins = submenu("Builtins", of: main) - for word in ["Newcol", "Joincol", "Find", "Grep", "Changelog", - "Dump", "NextColor", "Debug", "Kill"] { - builtins.addItem(command(word, #selector(menuBuiltin(_:)), "")) - } - let edit = submenu("Edit", of: main) - // Paste and nothing else. Copy, Cut, Undo and Select All have no - // builtin behind them — the core yanks into the clipboard on its own - // selection gestures and has no undo command to call — and a greyed or - // silently dead menu item teaches the user the menu lies. When the core - // grows those commands they belong here, spelled as run("...") like - // everything else. - edit.addItem(command("Paste", #selector(menuPaste(_:)), "v")) - - // The only menu whose items are not core commands: the font size is a - // property of this shell and nothing else. `Font` picks the FACE and - // lives in the topbar with the other builtins; the size is where the - // window is, so it is where macOS keeps it. - let viewMenu = submenu("View", of: main) - // Cmd+= rather than Cmd++: the key is unshifted `=` on every layout - // that has a `+` above it, and AppKit matches the character, not the - // engraving. The item is titled with the plus users look for. - viewMenu.addItem(command("Zoom In", #selector(menuZoomIn(_:)), "=")) - viewMenu.addItem(command("Zoom Out", #selector(menuZoomOut(_:)), "-")) - viewMenu.addItem(command("Actual Size", #selector(menuZoomReset(_:)), "0")) - - let windowMenu = submenu("Window", of: main) - windowMenu.addItem(withTitle: "Minimize", - action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m") - windowMenu.addItem(withTitle: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "") - - let help = submenu("Help", of: main) - // Cmd+? is the system-wide help chord; AppKit draws it as the shift of - // Cmd+/ without being told about the shift. - help.addItem(command("\(appName) Help", #selector(menuHelp(_:)), "?")) - help.addItem(command("Tutorial", #selector(menuTutor(_:)), "")) - - NSApp.mainMenu = main - // Handing AppKit these two makes it keep the window list up to date and - // put the Help search field at the top of the Help menu. Both must come - // after mainMenu is assigned, or AppKit has nothing to attach them to. - NSApp.windowsMenu = windowMenu - NSApp.helpMenu = help - } - - private func submenu(_ title: String, of parent: NSMenu) -> NSMenu { - let holder = NSMenuItem(title: title, action: nil, keyEquivalent: "") - // The submenu's own title is what AppKit shows in the menu bar for the - // Window and Help menus, which it looks up by title rather than by the - // item that holds them. - let menu = NSMenu(title: title) - holder.submenu = menu - parent.addItem(holder) - return menu - } - - // An item that runs one of our own actions. Explicitly targeted at self - // rather than left to the responder chain: PardesView is the first - // responder and answers none of these, and an untargeted item that finds no - // handler renders greyed out. - private func command(_ title: String, _ action: Selector, _ key: String) -> NSMenuItem { - let item = NSMenuItem(title: title, action: action, keyEquivalent: key) - item.target = self - return item - } - - @objc private func menuOpen(_ sender: Any?) { - let panel = NSOpenPanel() - panel.canChooseFiles = true - // Directories are first-class Look targets — the core opens one as a - // directory pane, which is how you navigate in acme — so refusing them - // here would hide half of what Look does. - panel.canChooseDirectories = true - panel.allowsMultipleSelection = true - for url in panel.urls where url.isFileURL { - look(url.path) - } - } - - /// Any workspace-tag word. The title is the builtin's own spelling, so - /// this is the same `run` a tag Exec performs and there is no second - /// vocabulary to keep in step. - @objc private func menuBuiltin(_ sender: NSMenuItem) { run(sender.title) } - - - @objc private func menuNew(_ sender: Any?) { run("New") } - @objc private func menuSave(_ sender: Any?) { run("Save") } - @objc private func menuHelp(_ sender: Any?) { run("Help") } - @objc private func menuTutor(_ sender: Any?) { run("Tutor") } - - // Deliberately the view's paste path and not a second one: Cmd+V from the - // menu and Cmd+V in the view must put the same bytes in through - // pardes_paste, or the two would diverge the first time either grows a - // filter. - @objc private func menuPaste(_ sender: Any?) { - guard coreIsUp else { return } - pardesViewRequestsPaste(view) - } - - // Zoom does not go through the core at all: it changes the cell, the view - // reports the new grid, and the core reflows to it exactly as it does for - // a window drag. Guarded on coreIsUp only because the resize callback it - // triggers calls into libpardes. - @objc private func menuZoomIn(_ sender: Any?) { - guard coreIsUp else { return } - view.zoom(by: 1) - } - - @objc private func menuZoomOut(_ sender: Any?) { - guard coreIsUp else { return } - view.zoom(by: -1) - } - - @objc private func menuZoomReset(_ sender: Any?) { - guard coreIsUp else { return } - view.zoomReset() - } - - // ---------------------------------------------------------------- core - - // One builtin command line, run as if it had been typed into a tag and - // executed. `command` is bridged to a temporary NUL-terminated UTF-8 buffer - // that lives exactly as long as the call, which is exactly as long as the - // core borrows it. - private func run(_ command: String) { - guard coreIsUp else { return } - pardes_command(command, command.utf8.count) - pump() - } - - // Look's operand is the whole tail of the line (executeBuiltinLine in - // src/pardes.zig splits on the first space and trims the rest), so a path - // with spaces in it needs no quoting and must not get any — quotes would - // become part of the filename. - private func look(_ path: String) { run("Look \(path)") } - - // argv paths are whatever the shell handed us. The core resolves a relative - // Look against the pane's directory, not the process's, so `pardes - // ./foo.zig` would open the wrong foo.zig — or nothing — unless it is made - // absolute here against the directory the process was launched from. - private func absolutePath(of argument: String, relativeTo directory: String) -> String { - let expanded = (argument as NSString).expandingTildeInPath - guard !(expanded as NSString).isAbsolutePath else { - return (expanded as NSString).standardizingPath - } - return ((directory as NSString).appendingPathComponent(expanded) as NSString).standardizingPath - } - - /// Dress the WINDOW in what the core is wearing: the background AppKit - /// paints where the view does not (the titlebar, and the strip a live - /// resize outruns). - /// - /// Cheap enough to call every pump: the view compares before it dirties - /// itself, and the window properties are written only when the answer - /// moved. `dressed` is what makes the FIRST call unconditional — a boot - /// theme whose background happened to equal the view's starting guess - /// would otherwise leave the window in AppKit's default clothes forever. - private var dressed = false - - private func applyTheme() { - // Both reads happen every pump, and neither may be short-circuited by - // the other: `changed` has to be the OR of two adoptions, not the first - // one that answered true, or a Theme and a WindowOpacity in the same - // tick would leave one of them unworn. - let themeChanged = view.adoptThemeBG(pardes_theme_bg()) - let opacityChanged = view.adoptWindowOpacity(pardes_window_opacity()) - guard themeChanged || opacityChanged || !dressed else { return } - dressed = true - if let rgb = view.themeBG { - window.isOpaque = view.backgroundAlpha >= 1 - window.backgroundColor = view.backgroundAlpha < 1 ? .clear : NSColor( - srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, - green: CGFloat((rgb >> 8) & 0xFF) / 255, - blue: CGFloat(rgb & 0xFF) / 255, - alpha: view.backgroundAlpha) - // ...and follow the theme into light mode, so the titlebar, the - // traffic lights and the resize cursor stop belonging to a - // different application than the grid under them. Luminance off - // the same sRGB channels the grid is drawn with. - let luma = (0.2126 * CGFloat((rgb >> 16) & 0xFF) - + 0.7152 * CGFloat((rgb >> 8) & 0xFF) - + 0.0722 * CGFloat(rgb & 0xFF)) / 255 - window.appearance = NSAppearance(named: luma > 0.5 ? .aqua : .darkAqua) - } else { - // Transparent: the window stops painting anything of its own. - // isOpaque false lets the desktop show through at all — a titled - // window is opaque by default and would composite over it. - window.isOpaque = false - window.backgroundColor = .clear - window.appearance = NSAppearance(named: .darkAqua) - } - } - - /// The focused pane, in the titlebar: the proxy icon macOS lets you drag - /// and Cmd-click for the path, and the dot in the close button that means - /// unsaved. - /// - /// A pure read-out — the window says what the core already decided, and - /// nothing here can change it. There is no document ARCHITECTURE behind it - /// and deliberately so: no NSDocument, no save panel, no "do you want to - /// save" on close. Save is a builtin, the pane's tag says so, and this is - /// the same two facts spelled where a Mac user looks for them. - /// - /// Cached, because setting representedURL makes AppKit hit the filesystem - /// for the icon and this runs on every pump. - private var shownPath: String? - private var shownDirty = false - - private func applyDocument() { - let path = pardes_active_path().map { String(cString: $0) } - if path != shownPath { - shownPath = path - // A terminal or an output buffer is not a document: no path means - // no proxy icon, rather than a stale one from the last file pane. - window.representedURL = path.map { URL(fileURLWithPath: $0) } - // ...and the title goes with it. A proxy icon beside a title that - // names something else reads as a bug, and AppKit will not fill the - // title in for us while `title` has been set by hand. The window is - // a SESSION and not a document, so it falls back to the app's own - // name the moment focus lands somewhere with no file behind it. - window.title = path.map { ($0 as NSString).lastPathComponent } ?? "pardes" - } - let dirty = pardes_active_dirty() - if dirty != shownDirty { - shownDirty = dirty - window.isDocumentEdited = dirty - } - } - - @objc private func inputArrived(_ notification: Notification) { - pump() - } - - // Every path into the core ends here. pardes_tick drains the ptys and runs - // the effects the core queued, so nothing the user did takes hold until it - // runs. - private func pump() { - // Unconditionally dirty, and NOT `if pardes_tick()`. That return value - // answers "did I do any IO" — it is true when a pty produced bytes or - // an effect was performed, and false for everything the core changes on - // its own. A cursor moved with j, a selection, a mode change and a - // scroll all queue nothing and perform nothing, so gating the repaint - // on it leaves the screen showing the state before the keystroke until - // some unrelated event happens to force a frame. Measured: four `j` - // presses in a file pane produced a byte-identical screenshot. - // - // The waste is bounded and small. AppKit coalesces needsDisplay within - // a runloop pass, so a burst of pty output is still one frame, and an - // idle wakeup cannot happen — a reader only wakes the host after it has - // read bytes. - _ = pardes_tick() - view.needsDisplay = true - // TaglineSize is host-owned raster state just like Font, but unlike a - // body face change it does not resize the grid. Polling the one-byte - // core setting keeps startup config and live commands on one path. - view.adoptTaglinePercent(pardes_gui_tagline_font_percent()) - // After the tick, because a `Theme` command runs inside it and the - // window has to follow the grid in the same frame rather than at the - // next launch. - applyTheme() - applyDocument() - - // Two verbs, two patterns, because they are two different answers: - // Exec did something, so it gets .generic, the definite tap of a - // committed action; Look went somewhere, so it gets .alignment, the - // lighter detent AppKit uses when a dragged guide snaps into place. - // Same distinction the core draws in Haptic (src/pardes.zig). - // - // No capability check on purpose. perform() is a silent no-op on a Mac - // with no Force Touch trackpad and when the user has turned feedback - // off in System Settings, so a check here would only be a second place - // to get the answer wrong — and it would be wrong the moment an - // external trackpad is plugged in mid-session. - let pulse = pardes_take_haptic() - if pulse == PARDES_HAPTIC_EXEC { - NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now) - } else if pulse == PARDES_HAPTIC_LOOK { - NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now) - } - - // Beside the haptic, and for the same reason: the `Font` builtin ran - // synchronously inside whatever input reached the core, so its answer - // is already waiting by the time the tick returns. The view re-measures - // and calls back through pardesViewDidResize, so the grid the core is - // holding follows the cell that just changed size. - var fontSize: UInt16 = 0 - if let wanted = pardes_font_take(&fontSize) { - view.adoptFont(path: String(cString: wanted), sizeHundredths: fontSize) - } - - if pardes_should_quit() { - NSApp.terminate(nil) - return - } - // Input and pty pumps only drain work. A frame-count animation advances - // on this 16 ms clock, and only after the sample dirtied above was - // actually presented. A burst of input cannot make it run fast, while - // an occluded/coalesced AppKit view cannot consume invisible samples. - scheduleAnimationFrame() - } - - private func scheduleAnimationFrame() { - guard pardes_animating() else { - stopDisplayLink() - return - } - if #available(macOS 14.0, *) { - // One link for the whole animating run, not one callback armed per - // frame: re-arming after the work is what put the period at 16 ms - // PLUS the work, and no amount of tuning that constant fixes a - // clock that is not the display's. - if displayLink == nil { - let link = view.displayLink(target: self, selector: #selector(displayLinkFired)) - link.add(to: .main, forMode: .common) - displayLink = link - } - return - } - // macOS 13 has no NSView display link. Keep the old chain, which is now - // only a cadence compromise rather than a correctness one — the tick - // spends measured time either way. - guard !pumpScheduled else { return } - let awaitingPresentation = view.presentationSerial - pumpScheduled = true - DispatchQueue.main.asyncAfter(deadline: .now() + 0.016) { - self.pumpScheduled = false - self.animationFrame(after: awaitingPresentation) - } - } - - private func stopDisplayLink() { - if #available(macOS 14.0, *) { (displayLink as? CADisplayLink)?.invalidate() } - displayLink = nil - } - - @objc private func displayLinkFired() { - guard coreIsUp else { return } - animationFrame(after: pendingPresentation) - } - - /// The presentation serial the last dirtied sample is waiting on. Held - /// across display-link callbacks because the link, unlike the old chain, - /// does not carry it in a closure. - private var pendingPresentation: UInt64 = 0 - - private func animationFrame(after awaitingPresentation: UInt64) { - guard view.presentationSerial != awaitingPresentation else { - // Keep the dirty sample pending. AppKit may have coalesced this - // draw or the window may be occluded; retry on the next refresh - // without advancing, until draw(_:) supplies the presentation - // permit. On the link that costs ONE refresh; the old chain paid a - // fresh 16 ms for it, which is where the visible hitching came from. - view.needsDisplay = true - if #available(macOS 14.0, *) {} else { scheduleAnimationFrame() } - return - } - _ = pardes_animation_tick() - pendingPresentation = view.presentationSerial - pump() - } - - func pardesViewDidResize(_ view: PardesView) { - let grid = view.gridSize - // cell_w/cell_h are physical pixels. The core hands them to the native - // PDF placement path, and a point is two pixels on a Retina display, so - // passing points would place every page at half size. - let scale: CGFloat = window.backingScaleFactor - pardes_resize( - grid.cols, grid.rows, - UInt16((view.cellWidth * scale).rounded()), - UInt16((view.cellHeight * scale).rounded())) - pardes_row_metrics(UInt16(max(1,(view.cellWidth*scale).rounded())), UInt16(max(1,(view.cellHeight*scale).rounded())), - UInt16(max(1,(view.taglineCellWidth*scale).rounded())), UInt16(max(1,(view.taglineBandHeight*scale).rounded()))) - pump() - } - - func pardesViewRequestsPaste(_ view: PardesView) { - guard let text = NSPasteboard.general.string(forType: .string) else { return } - AppDelegate.paste(text) - pump() - } - - // Swift lends a temporary NUL-terminated UTF-8 buffer for the duration of - // the call, which is exactly as long as the core borrows it. Static, and - // pumping is the caller's business: the read_clipboard callback is a C - // function pointer that can capture nothing and is already inside a tick, - // where the gesture path is not. - private static func paste(_ text: String) { - pardes_paste(text, text.utf8.count) - } - - // ponytail: one window, no tabs — the core has no multi-window notion, so - // the last window closing really is the end of the process. - func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { - return true - } - - // Nothing in this app's UI state can be restored: the window is one view - // over a core that has to replay its own session, and the frame is already - // handled by setFrameAutosaveName. Answering true opts into the secure - // coder AppKit wants; leaving the method out makes macOS 14 and later log a - // deprecation warning on every launch. - func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { - return true - } - - func applicationWillTerminate(_ notification: Notification) { - pardes_deinit() - } -} diff --git a/src/macos/Sources/FileWatcher.swift b/src/macos/Sources/FileWatcher.swift deleted file mode 100644 index 1fee2fd8..00000000 --- a/src/macos/Sources/FileWatcher.swift +++ /dev/null @@ -1,122 +0,0 @@ -// Per-path live reload for the native app. One source watches the file for -// in-place writes; another watches its parent because editors normally save by -// renaming a new inode over the old one. The file source is rearmed after a -// quiet edge so it follows that replacement rather than the unlinked old inode. - -import Darwin -import Dispatch -import Foundation - -private final class WatchedPath { - let pane: UInt8 - let generation: UInt32 - private let path: String - private let directorySource: DispatchSourceFileSystemObject - private var fileSource: DispatchSourceFileSystemObject? - private var active = true - private var eventSerial: UInt64 = 0 - - init?(pane: UInt8, generation: UInt32, path: String) { - let directory = URL(fileURLWithPath: path) - .deletingLastPathComponent().path - let descriptor = directory.withCString { - Darwin.open($0, O_EVTONLY | O_CLOEXEC) - } - guard descriptor >= 0 else { return nil } - - self.pane = pane - self.generation = generation - self.path = path - directorySource = DispatchSource.makeFileSystemObjectSource( - fileDescriptor: descriptor, - eventMask: [.write, .delete, .rename, .extend, .attrib, .link, .revoke], - queue: .main) - directorySource.setCancelHandler { _ = Darwin.close(descriptor) } - directorySource.setEventHandler { [weak self] in self?.pathChanged() } - reopenFileSource() - directorySource.activate() - } - - /// The directory source catches rename-over saves, while the file source - /// catches programs which truncate/write the existing inode. Reopen the - /// latter after every quiet edge because an atomic save leaves it attached - /// to the unlinked old inode forever otherwise. - private func reopenFileSource() { - if let old = fileSource { old.cancel() } - fileSource = nil - guard active else { return } - let descriptor = path.withCString { Darwin.open($0, O_EVTONLY | O_CLOEXEC) } - guard descriptor >= 0 else { return } - let next = DispatchSource.makeFileSystemObjectSource( - fileDescriptor: descriptor, - eventMask: [.write, .delete, .rename, .extend, .attrib, .link, .revoke], - queue: .main) - next.setCancelHandler { _ = Darwin.close(descriptor) } - next.setEventHandler { [weak self] in self?.pathChanged() } - fileSource = next - next.activate() - } - - /// Vnode sources can emit several edges for one save. Reset a small quiet - /// period on every edge; generation plus exact Zig-side identity checks - /// remain authoritative, so this delay is latency control rather than - /// correctness state. - private func pathChanged() { - guard active else { return } - eventSerial &+= 1 - let scheduled = eventSerial - DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(45)) { [weak self] in - guard let self, self.active, self.eventSerial == scheduled else { return } - self.reopenFileSource() - pardes_watch_changed(self.pane, self.generation) - } - } - - func cancel() { - guard active else { return } - active = false - eventSerial &+= 1 - if let old = fileSource { old.cancel() } - fileSource = nil - directorySource.cancel() - } - - deinit { cancel() } -} - -private final class FileWatchRegistry { - static let shared = FileWatchRegistry() - private var slots: [UInt8: WatchedPath] = [:] - - func set(pane: UInt8, generation: UInt32, path: String?) { - if let old = slots.removeValue(forKey: pane) { old.cancel() } - guard let path, - let watched = WatchedPath( - pane: pane, generation: generation, path: path) - else { return } - slots[pane] = watched - } -} - -/// Called only by libpardes's main-thread effect drain. A nil pointer stops the -/// slot. The byte count avoids a second sentinel copy in Zig; Foundation paths -/// are Unicode, so malformed UTF-8 is rejected rather than watched under a -/// replacement spelling that could name a different file. -@_cdecl("pardes_host_watch_file") -func pardesHostWatchFile( - _ pane: UInt8, - _ generation: UInt32, - _ path: UnsafePointer?, - _ pathLength: Int -) { - guard let path, pathLength > 0 else { - FileWatchRegistry.shared.set(pane: pane, generation: generation, path: nil) - return - } - let bytes = UnsafeBufferPointer(start: path, count: pathLength) - guard let value = String(bytes: bytes, encoding: .utf8) else { - FileWatchRegistry.shared.set(pane: pane, generation: generation, path: nil) - return - } - FileWatchRegistry.shared.set(pane: pane, generation: generation, path: value) -} diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift deleted file mode 100644 index 23cd0f78..00000000 --- a/src/macos/Sources/PardesView.swift +++ /dev/null @@ -1,2728 +0,0 @@ -// The AppKit half of the macOS backend: NSEvent in, pardes_* out, one -// CoreGraphics pass per frame back. -// -// This file keeps no model of the screen. The core owns the grid and hands it -// over whole through src/macos/pardes.h, so everything here is translation, and -// the only state worth holding is the font metrics — expensive to measure and -// replaced only by Font/TaglineSize/zoom — plus the gesture state remembered -// between events: which button a click started with, and how hard it is being -// pressed. -// -// Every NSEvent override decodes and then calls one of the post-decode entry -// points below (press/release/drag/click/scroll/rotate/typeKey). That split is -// not decoration: NSTouch, pressure stages and rotation have no public -// constructors, so a test can never synthesize them, and the only way the -// trackpad behaviour is reachable by anything but a finger is for the decision -// to live one call below the event. test/macos_e2e.swift drives exactly those -// entry points. -// -// Every C constant below is wrapped in an explicit conversion (UInt16(...), -// UInt32(...)) rather than used bare. A macro's imported Swift type is decided -// by the importer, not by us, and this file should not have an opinion about it. - -import AppKit -import CoreText - -/// Posted after every call this view makes into the core, and answered by -/// AppDelegate.pump(). The core only queues what it was told and does nothing -/// until it is pumped, so an input without one of these is an input that -/// visibly did nothing. Declared here, where the posts are. -let pardesDidInputNotification = Notification.Name("pardesDidInput") - -/// A cell, already clamped to the frame the core last rendered. -struct GridPoint { - var col: UInt16 - var row: UInt16 -} - -protocol PardesViewDelegate: AnyObject { - func pardesViewDidResize(_ view: PardesView) - func pardesViewRequestsPaste(_ view: PardesView) -} - -/// What a click means, from the fingers resting on the trackpad and the button -/// stream AppKit chose to deliver it on. Pure on purpose: NSTouch cannot be -/// constructed, so this is the part of the gesture a test can reach. -/// -/// acme's three buttons are the whole vocabulary — 1 selects, 2 executes, -/// 3 looks — and a trackpad has one surface. More than one finger is Exec, -/// because running something is what a hand does over and over and it gets -/// the gesture that costs nothing; Look is the deep press, one deliberate -/// push past the click for the verb that goes somewhere. -/// -/// Two and three fingers are the same verb here, and that is the hardware -/// talking rather than a shrug. macOS's secondary click is "click or tap with -/// TWO OR MORE fingers": with it on — the default — a three-finger click is -/// delivered as rightMouseDown exactly like a two-finger one, and a view that -/// trusts the stream calls both of them Look. Measured on real hardware, which -/// is the only way this was ever going to be found: -/// `rightMouseDown: resting=3`. So the count is what keeps a multi-finger -/// click off Look, and the stream cannot be trusted to do it. -/// -/// The stream is only the fallback, for when there are no fingers to count: -/// a real mouse's right button is Look and its middle button is Exec, and both -/// arrive with an empty touch set. -enum Trackpad { - static func button(stream: pardes_mouse_button_e, fingers: Int) -> pardes_mouse_button_e { - switch fingers { - case 2...: return PARDES_MOUSE_MIDDLE - // One finger, or none to count: the stream is the answer. A trackpad - // single click comes in on the left stream and stays left; a real - // mouse's right and middle buttons keep their acme meanings. - default: return stream - } - } - - /// A force click is a deliberate second gesture on top of an ordinary one, - /// so it gets the verb that goes somewhere rather than the one that runs - /// something: press harder and you Look. - static let forceClickButton: pardes_mouse_button_e = PARDES_MOUSE_RIGHT -} - -// Matches bg_default/fg_default in src/gui/gui.zig. Two shells render the -// same core; if these drift, comparing -// a screenshot across backends stops meaning anything. -let pardesDefaultFG: UInt32 = 0xCC_CC_CC -let pardesDefaultBG: UInt32 = 0x12_12_12 - -/// Pinned sRGB for rasterized attachments, so a PDF page's bytes mean the same -/// thing here as they do in the SDL shell. DeviceRGB is the fallback rather -/// than a crash: a machine with no sRGB profile is not a reason to stop -/// drawing pages. -private let sRGB: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB() - -// UNVERIFIED: kCTFontAttributeName bridged through NSAttributedString.Key. It is -// the same string as .font, but spelling the CoreText key means the value stays -// a CTFont instead of being bridged to NSFont on the way in. -private let fontAttribute = NSAttributedString.Key(kCTFontAttributeName as String) - -// The named sixteen, then xterm's 6x6x6 cube, then the 24-step grey ramp. These -// sixteen are app.mjs's, not gui.zig's: gui.zig borrows ghostty's palette -// because it already links it, and the two disagree on the base colors. -private let ansi16: [UInt32] = [ - 0x00_00_00, 0xCC_00_00, 0x4E_9A_06, 0xC4_A0_00, - 0x34_65_A4, 0x75_50_7B, 0x06_98_9A, 0xD3_D7_CF, - 0x55_57_53, 0xEF_29_29, 0x8A_E2_34, 0xFC_E9_4F, - 0x72_9F_CF, 0xAD_7F_A8, 0x34_E2_E2, 0xEE_EE_EC, -] - -private func paletteColor(_ index: UInt8) -> UInt32 { - if index < 16 { return ansi16[Int(index)] } - if index >= 232 { - let grey = UInt32(8 + (Int(index) - 232) * 10) - return grey << 16 | grey << 8 | grey - } - let n = Int(index) - 16 - func level(_ part: Int) -> UInt32 { part == 0 ? 0 : UInt32(55 + part * 40) } - return level(n / 36) << 16 | level(n / 6 % 6) << 8 | level(n % 6) -} - -private func decodeColor(_ encoded: UInt32, _ fallback: UInt32) -> UInt32 { - if encoded == UInt32(PARDES_COLOR_DEFAULT) { return fallback } - if encoded & UInt32(PARDES_COLOR_TAG_MASK) == UInt32(PARDES_COLOR_INDEXED) { - return paletteColor(UInt8(encoded & 0xFF)) - } - return encoded & UInt32(PARDES_COLOR_RGB_MASK) -} - -/// The four faces, indexed by the two attribute bits that pick one. Also the -/// glyph cache's first key, which is why it is an ordinal and not four fields. -private enum Face: Int, CaseIterable { - case regular = 0, bold = 1, italic = 2, boldItalic = 3 - - init(bold: Bool, italic: Bool) { - self = Face(rawValue: (bold ? 1 : 0) | (italic ? 2 : 0))! - } -} - -/// A background run that must not be painted at all, so the window's own -/// backdrop shows through. Outside the 24-bit RGB range, so it can never -/// collide with a real colour, and distinct from the `.max` the run loop -/// flushes on. -let bgClear: UInt32 = 0x0100_0000 - -/// `block` means the filled cursor sits on this cell. `ground` is what a -/// DEFAULT background resolves to, and `clearGround` asks for those cells to -/// come back as `bgClear` instead of a colour. -private func resolve( - _ cell: pardes_cell_s, - block: Bool, - ground: UInt32, - clearGround: Bool -) -> (fg: UInt32, bg: UInt32, alpha: CGFloat, visible: Bool) { - // The core never painted this cell, which is most of the screen most of the - // time, so this branch is the one that has to stay cheap. - if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { - return block - ? (ground, pardesDefaultFG, 1, false) - : (pardesDefaultFG, clearGround ? bgClear : ground, 1, false) - } - let bgDefault = cell.bg == UInt32(PARDES_COLOR_DEFAULT) - var fg = decodeColor(cell.fg, pardesDefaultFG) - var bg = decodeColor(cell.bg, ground) - // The block cursor is a second reverse, so a cell that is already reversed - // cancels back to normal underneath it. Same rule as emitInstance in - // src/gui/gui.zig; the two must not drift. - var reverse = block - if cell.attrs & UInt16(PARDES_ATTR_REVERSE) != 0 { reverse = !reverse } - if reverse { swap(&fg, &bg) } - // ponytail: PARDES_ATTR_BLINK is decoded into nothing. Honouring it costs a - // timer plus a repaint budget for a bit nothing in pardes emits today; drive - // setNeedsDisplay from an NSTimer here when something does. - let visible = cell.attrs & UInt16(PARDES_ATTR_INVISIBLE) == 0 && cell.len > 0 - // The other shells scale the channels by 6/10. Over a dark background alpha - // lands in the same place and costs one blend instead of three multiplies. - let alpha: CGFloat = cell.attrs & UInt16(PARDES_ATTR_DIM) != 0 ? 0.6 : 1 - // Only an UNREVERSED default background is the ground. A reverse puts the - // text colour there, and text is a real colour that paints. - if clearGround && bgDefault && !reverse { bg = bgClear } - return (fg, bg, alpha, visible) -} - -private func advance(_ font: CTFont, _ character: UniChar) -> CGFloat { - var input = character - var glyph = CGGlyph(0) - guard CTFontGetGlyphsForCharacters(font, &input, &glyph, 1) else { return 0 } - var size = CGSize.zero - CTFontGetAdvancesForGlyphs(font, .horizontal, &glyph, &size, 1) - return size.width -} - -/// The size the window opens at and Cmd+0 returns to. Named here rather than -/// passed in because zoomReset has to know it too, and two spellings of one -/// number is how "actual size" stops being the size it actually opened at. -let defaultFontSize: CGFloat = 14 - -/// The faces CoreText should reach for when the grid face has no glyph. -/// -/// The SDL shell loads a chain of fallback faces itself and rasterizes from -/// whichever one has the codepoint. This shell draws its non-ASCII through -/// CTLine, which already walks a cascade — but the SYSTEM cascade, and the -/// system cascade has never heard of a Nerd Font. Measured on a machine with -/// Mononoki Nerd Font installed: U+E0B0, U+E5FF, U+E700 and U+F015 all resolved -/// to `LastResort`, which is the tofu box. Braille, emoji and CJK resolved -/// fine, which is exactly why this went unnoticed — everything Unicode has an -/// opinion about already worked, and only the Private Use Area did not. -/// -/// Two sources, in this order: -/// -/// 1. `fonts.fallback_names` over the C ABI, so the PREFERENCE ORDER is the -/// one the SDL shell uses and lives in one file. -/// 2. Installed Nerd Font families, found by name and then CONFIRMED BY -/// COVERAGE. Both halves are load-bearing. Coverage alone is not enough: a -/// scan of all 250 families here put `Hannotate TC` and `HanziPen TC` at -/// 4 of 6 probes, because CJK faces map the PUA for their own purposes and -/// would answer a powerline request with an unrelated ideograph. A name -/// alone is not enough either, because "Nerd Font" in a family name is a -/// convention, not a guarantee. So the name decides what a codepoint MEANS -/// and coverage decides whether the face can actually draw it. -/// -/// Computed once. The result is a list of descriptors, which carry no size, so -/// a zoom or a `Font` command reuses it; only installing a font invalidates it, -/// and that is a relaunch. -private enum FontFallbacks { - /// Representative codepoints, one per Nerd Font block that matters: - /// powerline separators, Seti file icons, devicons, Font Awesome. A face - /// answering all four is patched; a face answering one is a coincidence. - private static let nerdProbes: [UInt32] = [0xE0B0, 0xE5FF, 0xE700, 0xF015] - - static let descriptors: [CTFontDescriptor] = build() - - private static func build() -> [CTFontDescriptor] { - var out: [CTFontDescriptor] = [] - var seen = Set() - - func take(_ family: String, _ descriptor: CTFontDescriptor) { - guard seen.insert(family).inserted else { return } - out.append(descriptor) - } - - // 1. The shared preference order. - for index in 0.. 0 else { continue } - let name = String(decoding: UnsafeRawBufferPointer(start: bytes, count: Int(length)), as: UTF8.self) - guard let found = resolve(name) else { continue } - take(found.family, found.descriptor) - } - - // 2. Nerd Fonts that are installed AND cover the blocks. `Mono` cuts - // first: this is a fixed grid, and the propo/variable cuts of the - // same family are drawn to different advances. - let families = (CTFontManagerCopyAvailableFontFamilyNames() as? [String]) ?? [] - let nerd = families.filter { $0.range(of: "nerd font", options: .caseInsensitive) != nil } - for family in nerd.sorted(by: { rank($0) < rank($1) }) { - let descriptor = CTFontDescriptorCreateWithAttributes( - [kCTFontFamilyNameAttribute: family] as CFDictionary) - guard coverage(descriptor, nerdProbes) == nerdProbes.count else { continue } - take(family, descriptor) - } - return out - } - - /// "Mono" before "Propo" before the proportional cut. - private static func rank(_ family: String) -> Int { - if family.range(of: "nerd font mono", options: .caseInsensitive) != nil { return 0 } - if family.range(of: "nerd font propo", options: .caseInsensitive) != nil { return 2 } - return 1 - } - - /// A descriptor that really is the font asked for. CoreText SUBSTITUTES - /// rather than failing — asking it for an uninstalled `SymbolsNerdFont- - /// Regular` hands back Helvetica, and a cascade seeded with Helvetica is a - /// cascade that answers every missing glyph with the wrong one. - private static func resolve(_ name: String) -> (family: String, descriptor: CTFontDescriptor)? { - for attribute in [kCTFontNameAttribute, kCTFontFamilyNameAttribute] { - let query = CTFontDescriptorCreateWithAttributes([attribute: name] as CFDictionary) - guard let match = CTFontDescriptorCreateMatchingFontDescriptor(query, nil) else { continue } - let postScript = CTFontDescriptorCopyAttribute(match, kCTFontNameAttribute) as? String ?? "" - let family = CTFontDescriptorCopyAttribute(match, kCTFontFamilyNameAttribute) as? String ?? "" - guard postScript.compare(name, options: .caseInsensitive) == .orderedSame - || family.compare(name, options: .caseInsensitive) == .orderedSame - else { continue } - return (family.isEmpty ? postScript : family, match) - } - return nil - } - - /// How many of `codepoints` this face can actually draw. Size is irrelevant - /// to coverage, so the probe face is built at a nominal one. - private static func coverage(_ descriptor: CTFontDescriptor, _ codepoints: [UInt32]) -> Int { - let font = CTFontCreateWithFontDescriptor(descriptor, 12, nil) - var hits = 0 - for codepoint in codepoints { - guard let scalar = UnicodeScalar(codepoint) else { continue } - var units = Array(String(scalar).utf16) - var glyphs = [CGGlyph](repeating: 0, count: units.count) - if CTFontGetGlyphsForCharacters(font, &units, &glyphs, units.count) { hits += 1 } - } - return hits - } - - /// `face` with the chain attached. Every face pardes draws with goes through - /// here exactly once, at the base: `CTFontCreateCopyWithSymbolicTraits` and - /// `CTFontCreateCopyWithAttributes` both carry the cascade into the copy, so - /// the bold/italic cuts and the smaller tagline cuts inherit it. - static func attach(to face: CTFont, size: CGFloat) -> CTFont { - guard !descriptors.isEmpty else { return face } - let descriptor = CTFontDescriptorCreateCopyWithAttributes( - CTFontCopyFontDescriptor(face), - [kCTFontCascadeListAttribute: descriptors] as CFDictionary) - return CTFontCreateWithFontDescriptor(descriptor, size, nil) - } -} - -/// Everything that changes when the face or its size does, in one value so -/// that changing either is one assignment and cannot leave half the numbers -/// describing the old font. -/// -/// Built at init and again for a `Font` command or a zoom. The view clears its -/// body/tagline glyph caches beside replacing this value: a CGGlyph is an index -/// into a particular face, so carrying one across a font change is invalid. -private struct Metrics { - let fonts: [CTFont] - /// False only when a non-nil requested file could not produce a fixed-pitch - /// CoreText face. The caller rejects that request and keeps old Metrics. - let acceptedPath: Bool - let ascent: CGFloat - let cellWidth: CGFloat - let cellHeight: CGFloat - let ruleThickness: CGFloat - let underlineOffset: CGFloat - /// ASCII is very nearly the whole screen, so its glyphs are resolved once - /// per face here and never looked up again. - let asciiGlyphs: [[CGGlyph]] - - /// Round `v` onto the backing grid: `scale` is the display's - /// backingScaleFactor, so at 2x this lands on half-points, which are whole - /// device pixels. - private static func snap(_ v: CGFloat, _ scale: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { - (v * scale).rounded(rule) / scale - } - - init(size: CGFloat, path: String?, scale: CGFloat) { - let requested = path.flatMap { Metrics.fromFile($0, size) } - // Attached ONCE, at the base: the trait and size copies below inherit - // the cascade, so every cut and the tagline's smaller cuts reach the - // same fallbacks. Metrics is measured from `face` too, and a cascade - // changes no metric — CoreText measures the primary face and only - // consults the chain for a codepoint it lacks. - let face = FontFallbacks.attach(to: requested ?? Metrics.defaultFace(size: size), size: size) - let scale = max(1, scale) - - // UNVERIFIED: CTFontSymbolicTraits member spelling (.traitBold/.traitItalic). - // A face with no italic cut returns nil here, hence the fallback to `face`. - func variant(_ traits: CTFontSymbolicTraits) -> CTFont { - CTFontCreateCopyWithSymbolicTraits(face, size, nil, traits, traits) ?? face - } - let faces = [face, variant(.traitBold), variant(.traitItalic), variant([.traitBold, .traitItalic])] - - // The grid has to land on WHOLE DEVICE PIXELS, and that is the whole - // constraint — a fractional column boundary makes the background pass - // (which runs with antialiasing off, or touching fills seam) wobble by - // a pixel from column to column, and on a screen made of tag bars and - // selections that stripe is visible. - // - // Whole POINTS is how that used to be spelled, and on a Retina display - // it asks for twice what it needs: half a point IS a whole pixel at 2x. - // The difference is not academic — Monaco advances 8.4014pt at 14, so - // ceiling to 9 spaced every column 7.1% wider than the face was drawn - // for, which is loose, washed-out text that reads as bad rendering. - // Snapped to the backing grid it is 8.5, i.e. +1.2%. - // - // Width rounds to NEAREST — a monospace glyph is drawn to fit its own - // advance, so the half-pixel either way is slack — while height rounds - // UP, because losing a pixel off a descender is clipping. - let snap = Metrics.snap - fonts = faces - acceptedPath = path == nil || requested != nil - // The ascent lands on a pixel for a second reason: it is the baseline's - // offset inside the cell, so the rules hung off it are whole-pixel - // fills rather than one-pixel bars smeared across two rows. - let bodyAscent = max(1 / scale, snap(CTFontGetAscent(face), scale, .toNearestOrAwayFromZero)) - let bodyWidth = max(1 / scale, snap(advance(face, 0x4D), scale, .toNearestOrAwayFromZero)) - let bodyHeight = max(1 / scale, snap(CTFontGetAscent(face) + CTFontGetDescent(face) + CTFontGetLeading(face), scale, .up)) - ascent = bodyAscent - cellWidth = bodyWidth - cellHeight = bodyHeight - ruleThickness = max(1 / scale, snap(CTFontGetUnderlineThickness(face), scale, .toNearestOrAwayFromZero)) - underlineOffset = snap(CTFontGetUnderlinePosition(face), scale, .toNearestOrAwayFromZero) - asciiGlyphs = faces.map { font in - var chars = Array(UniChar(0).. CTFont { - let system = NSFont.monospacedSystemFont(ofSize: size, weight: .regular) - // Through the descriptor, not through CTFontCreateWithName(fontName): - // the system monospace face has a dot-prefixed internal name that a - // by-name lookup can miss entirely, and NSFontDescriptor is toll-free - // bridged, so this cannot resolve to a different font than AppKit just - // handed us. - let face = CTFontCreateWithFontDescriptor(system.fontDescriptor as CTFontDescriptor, size, nil) - // The whole layout is a fixed grid, so a proportional face is not a - // cosmetic problem, it is a broken screen. "M" and "i" disagreeing on - // advance is the cheapest possible proof that we got one. - return Metrics.isFixedPitch(face) ? face : CTFontCreateWithName("Menlo" as CFString, size, nil) - } - - /// A face out of a font FILE, which is what the core hands over — it found - /// the path by walking the font directories itself, so nothing here asks - /// CoreText to resolve a name that a different shell might resolve - /// differently. - /// - /// Nil rather than a substitute for anything wrong with the file, because - /// the caller's fallback is the face already on screen: a font that cannot - /// be measured would otherwise leave a terminal with no way back out. - private static func fromFile(_ path: String, _ size: CGFloat) -> CTFont? { - let url = URL(fileURLWithPath: path) as CFURL - guard let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url) as? [CTFontDescriptor], - !descriptors.isEmpty else { return nil } - // A .ttc holds a family's four cuts in one file. Take the one with - // neither trait set — the regular — because the bold and italic ones - // are derived from it below; falling back to the first face keeps a - // collection whose cuts are all styled from being unusable. - let plain = descriptors.first { descriptor in - let traits = CTFontDescriptorCopyAttribute(descriptor, kCTFontTraitsAttribute) as? [CFString: Any] - let symbolic = (traits?[kCTFontSymbolicTrait] as? UInt32) ?? 0 - return symbolic & UInt32(CTFontSymbolicTraits.traitBold.rawValue | CTFontSymbolicTraits.traitItalic.rawValue) == 0 - } - let chosen = CTFontCreateWithFontDescriptor(plain ?? descriptors[0], size, nil) - // A variable face's descriptor carries no variation, and CoreText - // picks whichever named instance it likes for it — Maple Mono's - // variable file comes up Thin. Pin every axis to its own default: - // the face the file itself calls regular. - var face = chosen - if let axes = CTFontCopyVariationAxes(face) as? [[CFString: Any]] { - var defaults: [CFNumber: Any] = [:] - for axis in axes { - guard let tag = axis[kCTFontVariationAxisIdentifierKey], - let value = axis[kCTFontVariationAxisDefaultValueKey] else { continue } - defaults[tag as! CFNumber] = value - } - if !defaults.isEmpty { - let descriptor = CTFontDescriptorCreateCopyWithAttributes( - CTFontCopyFontDescriptor(face), - [kCTFontVariationAttribute: defaults] as CFDictionary) - face = CTFontCreateWithFontDescriptor(descriptor, size, nil) - } - } - // The core already filtered for fixed pitch by reading the file's own - // advances. This is the same question asked of the face CoreText - // actually built, which is the one that will be drawn with. - return Metrics.isFixedPitch(face) ? face : nil - } - - private static func isFixedPitch(_ face: CTFont) -> Bool { - let em = advance(face, 0x4D) - return em > 0 && abs(em - advance(face, 0x69)) <= 0.01 - } -} - -/// The independently replaceable half of font state. A TaglineSize command -/// rebuilds only this value and its non-ASCII cache; body metrics and therefore -/// the core grid never move. `height` is also the painted tag-band height, not -/// merely a smaller glyph centred inside a body-height colour bar. -private struct TaglineMetrics { - let percent: UInt8 - let fonts: [CTFont] - /// The tagline face's OWN ascent. Deliberately not folded together with the - /// band's top offset the way it used to be: that offset is per-row now, and - /// a baseline carrying one row's offset would pin every band back to centre. - let ascent: CGFloat - /// The tagline face's OWN advance, clamped to the body cell it sits in. - /// A tag row steps by THIS, not by the body cell width: the band behind it - /// is still pane-wide on the body grid, but the text on top of it tracks at - /// the smaller face's own pitch. Centring a smaller glyph inside a - /// body-width cell instead — which is what this shell used to do — leaves - /// the tag text visibly looser than the same session in an SDL window. - let width: CGFloat - let height: CGFloat - let asciiGlyphs: [[CGGlyph]] - /// Kept so the band rules below can work in the physical pixels the core - /// states them in, and hand back points. - private let scale: CGFloat - private let bodyCellHeight: CGFloat - - init(body: Metrics, percent: UInt8, scale rawScale: CGFloat) { - let scale = max(1, rawScale) - func snap(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { - (value * scale).rounded(rule) / scale - } - self.percent = percent - self.scale = scale - bodyCellHeight = body.cellHeight - let size = CTFontGetSize(body.fonts[0]) * CGFloat(percent) / 100 - let faces = body.fonts.map { CTFontCreateCopyWithAttributes($0, size, nil, nil) } - fonts = faces - let face = faces[Face.regular.rawValue] - let measuredHeight = max(1 / scale, snap( - CTFontGetAscent(face) + CTFontGetDescent(face) + CTFontGetLeading(face), .up)) - // Runtime configuration caps the percentage at the body face. Keep the - // clamp here too: a malformed/custom host value must not paint a tag - // over the body row below it. - height = min(body.cellHeight, measuredHeight) - ascent = max(1 / scale, snap(CTFontGetAscent(face), .toNearestOrAwayFromZero)) - width = min(body.cellWidth, max(1 / scale, snap(advance(face, 0x4D), .toNearestOrAwayFromZero))) - asciiGlyphs = faces.map { font in - var chars = Array(UniChar(0).. CGFloat { - CGFloat(pardes_tagline_band_offset( - UInt16(clamping: row), Float(canvasHeight * scale), cellPixels, bandPixels)) / scale - } - - /// Canonical tag cells are physical grip slots; TagLayer positions text. - func glyphX(col: Int, row: Int, bodyCellWidth: CGFloat) -> CGFloat { - // Canonical tag cells are physical grips; TagLayer owns compact text. - CGFloat(col) * bodyCellWidth - } - - /// Thickness of the rule joining the topbar band to the first pane-tag band, - /// zero when the two are meant to join directly. - var borderThickness: CGFloat { - CGFloat(pardes_topbar_pane_border_px(cellPixels, bandPixels)) / scale - } - - /// Top of that rule. Placed the way the SDL shell places it, in WHOLE - /// pixels: half the rule above the topbar/pane boundary, floored, so a - /// one-pixel rule lands on the boundary instead of smeared across two rows. - var borderTop: CGFloat { - let px = pardes_topbar_pane_border_px(cellPixels, bandPixels) - return (CGFloat(cellPixels * UInt32(PARDES_TOPBAR_H)) - CGFloat(px / 2)) / scale - } - - /// One physical pixel, in points. The rules separating discontinuous - /// context rows inside a body layer are a single pixel in the SDL shell, - /// so they are stated there and converted here rather than handing `scale` - /// out and letting the caller reinvent the conversion. - var contextBorderThickness: CGFloat { 1 / scale } -} - -private func modifiers(_ flags: NSEvent.ModifierFlags) -> UInt32 { - var mods: UInt32 = 0 - if flags.contains(.control) { mods |= UInt32(PARDES_MOD_CTRL) } - if flags.contains(.option) { mods |= UInt32(PARDES_MOD_ALT) } - if flags.contains(.shift) { mods |= UInt32(PARDES_MOD_SHIFT) } - if flags.contains(.command) { mods |= UInt32(PARDES_MOD_SUPER) } - return mods -} - -final class PardesView: NSView { - weak var delegate: PardesViewDelegate? - - // The face and the numbers off it, replaced whole by `wear`. - private var metrics: Metrics - private var taglines: TaglineMetrics - /// What `metrics` was built from, so a zoom keeps the face and a font - /// change keeps the size. - private var fontSize: CGFloat - private var fontPath: String? - - var cellWidth: CGFloat { metrics.cellWidth } - var cellHeight: CGFloat { metrics.cellHeight } - - // Glyphs the ASCII table above did not answer for. A stored 0 is .notdef, - // meaning "this face does not have it", which is a cache hit too — the - // CTLine fallback below is far more expensive than the lookup it would - // repeat. Keyed by role, face and codepoint, and thrown away with both - // body and tagline variants whenever the body face changes. - private var bodyGlyphCache: [UInt32: CGGlyph] = [:] - private var taglineGlyphCache: [UInt32: CGGlyph] = [:] - private struct GripGlyph { - let line: CTLine - let ink: CGRect - } - private var gripGlyphCache: [String: GripGlyph] = [:] - // Scratch for one batched run of glyphs. Held rather than made per row so a - // full redraw does not allocate 24 times. - private var runGlyphs: [CGGlyph] = [] - private var runPositions: [CGPoint] = [] - /// Ligature shaping, keyed by face and text. A sequence ligates when - /// shaping it produces fewer glyphs than it has characters — the only - /// answer CoreText gives without interrogating the font's own features. - /// Cleared with the glyph caches, because it belongs to one face. - private var ligatureShaped: [String: Bool] = [:] - /// Columns the current row has already consumed as part of a ligature - /// drawn further left. One row's worth at a time. - private var ligatureCovered: Set = [] - /// Constructed lazily because the ordinary path is still a direct - /// CoreText/CoreGraphics frame. No scene bit and no panel track means no - /// bitmap, no Core Image context and no Metal work. - private lazy var scenePostprocessor: ScenePostprocessor? = ScenePostprocessor() - /// Kernel compilation is permanent for one executable. Runtime allocation - /// and device failures get three consecutive attempts before this session - /// stops advertising effects its GPU path cannot present. - private var postprocessorUnavailable = false - private var postprocessRetries = 0 - /// The scene mapping of the pixels AppKit most recently accepted. Pointer - /// events use this snapshot, not a clock that may already be one tick ahead. - private var lastPresentedScene: pardes_scene_s? - /// Whether the last frame reached the optional Metal owner successfully. - /// Ordinary direct draws and a runtime-kernel failure leave this false. - private(set) var lastFrameUsedPostprocessor = false - /// Monotonic count of frames AppKit actually let this view present. The - /// host animation clock uses it as a permit: no new sample is consumed - /// while an occluded/coalesced frame is still waiting to be drawn. - private(set) var presentationSerial: UInt64 = 0 - - private var reportedCols: UInt16 = 0 - private var reportedRows: UInt16 = 0 - - /// The backingScaleFactor `metrics` was snapped to, so a move between a - /// Retina and a 1x display re-measures the cell instead of leaving the grid - /// aligned to the other screen's pixels. - private var metricsScale: CGFloat = 2 - - /// The active theme's own background, or nil when it declares none — the - /// `*_transparent` themes and the curated `dark`. Nil is not a colour to - /// substitute but a decision: the ground stops being painted at all, the - /// view stops being opaque, and AppDelegate's NSVisualEffectView shows - /// through it. Read off pardes_theme_bg() once per pump, which is also - /// what makes a `Theme` command take hold without a relaunch. - private(set) var themeBG: UInt32? = pardesDefaultBG - - /// Adopt what the core is wearing. Returns whether anything moved, so the - /// host only reconfigures the window when it has to. - @discardableResult - func adoptThemeBG(_ encoded: UInt32) -> Bool { - let wanted: UInt32? = - encoded == UInt32(PARDES_COLOR_DEFAULT) ? nil : encoded & UInt32(PARDES_COLOR_RGB_MASK) - guard wanted != themeBG else { return false } - themeBG = wanted - needsDisplay = true - return true - } - - /// What `WindowOpacity` asked for, as the alpha every BACKGROUND is painted - /// at: the ground, cell and band backgrounds, and the chrome rules over - /// them. Glyph ink is never scaled by it, and neither is the block cursor — - /// it is foreground chrome that merely happens to be carried in a cell's - /// background, and it has to stay visible at `WindowOpacity 0`. - /// - /// The rule is stated once for the SDL shell in shaders/ui.frag.glsl; this - /// is the same rule in CoreGraphics, where painting the ground at this - /// alpha and the glyph over it at its own coverage composites to what that - /// shader writes premultiplied in one pass. - /// - /// Orthogonal to `themeBG`: a theme with no background of its own drops the - /// ground whatever this says, and an opaque theme still honours it. - private(set) var backgroundAlpha: CGFloat = 1 - - /// Adopt the core's percentage. Returns whether anything moved, on the same - /// contract as adoptThemeBG: the host redresses the window only when it has. - @discardableResult - func adoptWindowOpacity(_ percent: UInt8) -> Bool { - let wanted = CGFloat(min(percent, 100)) / 100 - guard wanted != backgroundAlpha else { return false } - backgroundAlpha = wanted - needsDisplay = true - return true - } - - // The button a left-stream click actually started with. mouseDown decides - // it from the fingers on the trackpad, and mouseDragged/mouseUp must use - // the same one: a press of right followed by a release of left leaves the - // core holding a drag nothing will ever end. - private var latchedButton: pardes_mouse_button_e? - private var latchedCell: GridPoint? - /// Last physical point delivered by AppKit and its mapping through the - /// accepted scene. The CRT's barrel moves a source cell under a stationary - /// hand, so successful scene presentations reconcile this point again. - private var pointerPoint: CGPoint? - private var pointerCell: GridPoint? - private var pointerMapped = false - private var pointerModifiers: UInt32 = 0 - // Force-click stage, reset per press. AppKit repeats stage-2 events for as - // long as the finger stays down, and only the transition is the gesture. - private var pressureStage: Int = 0 - // Fingers currently resting on the trackpad, kept from the touch stream. - // - // mouseDown was originally trusted to carry its own touch set, and on this - // hardware it does not always: AppKit routes NSTouch through the four - // touchesXxx callbacks, and the touch set hanging off a *mouse* event can - // come back empty depending on how the click was produced. Empty reads as - // one finger, which is a two-finger Exec silently degrading into a select - // — the exact failure this was supposed to avoid. So the count is - // maintained here and the mouse event's own set is preferred only when it - // has something in it. - private var restingFingers: Int = 0 - - init(fontSize size: CGFloat) { - // No window yet, so no backing scale to ask for: 2x is the guess every - // Mac shipped this decade would give, and viewDidChangeBackingProperties - // below re-measures the moment there is a real answer — including the - // 1x case, which a bare guess would otherwise leave wrong forever. - let built = Metrics(size: size, path: nil, scale: 2) - metrics = built - taglines = TaglineMetrics( - body: built, percent: pardes_gui_tagline_font_percent(), scale: 2) - fontSize = size - fontPath = nil - - // 80x24 only so the window has a size to open at; the AppDelegate reads - // gridSize back and boots the core with whatever it actually got. - super.init(frame: NSRect(x: 0, y: 0, width: built.cellWidth * 80, height: built.cellHeight * 24)) - - runGlyphs.reserveCapacity(256) - runPositions.reserveCapacity(256) - // Files dropped ON the grid. Finder and the Dock already reach the app - // through application(_:open:), but that path cannot say WHERE — and - // where is the whole difference between "a file opened somewhere" and - // acme's "a file opened next to the pane I pointed at". - registerForDraggedTypes([.fileURL]) - // Indirect touches are the trackpad's. Without this the touch set is - // always empty and every click looks like one finger, which is exactly - // the bug that would make two-finger Exec silently never fire. - allowedTouchTypes = [.indirect] - // Without a pressure configuration the deep-press stages are the - // system's business and stage 2 may never be delivered here. - // .primaryDeepClick is the one that means "a harder press is a second - // gesture", which is what it is being used for. - pressureConfiguration = NSPressureConfiguration(pressureBehavior: .primaryDeepClick) - } - - required init?(coder: NSCoder) { fatalError("PardesView is built in code, not a nib") } - - // MARK: - the face - - /// The PostScript name of the face on screen. The only way anything - /// outside this file can find out which font is being drawn with — the - /// core has no font, so a cell-buffer snapshot cannot see one. - var faceName: String { CTFontCopyPostScriptName(metrics.fonts[0]) as String } - var effectivePointSize: CGFloat { CTFontGetSize(metrics.fonts[0]) } - - /// Put on a face, or the same face at a different size, and tell the host - /// the grid moved under it. - /// - /// A cell that changed size means a different number of columns fit the - /// same window, so this is a resize as far as the core is concerned — and - /// the delegate's resize path is already the one that reports both the - /// grid and the physical cell the PDF placement reads. A requested file - /// which cannot produce a fixed-pitch face is rejected before assignment, - /// leaving the screen exactly as it was rather than substituting a face. - private func wear(size: CGFloat, path: String?, resolvesRequest: Bool = false) { - let scale = window?.backingScaleFactor ?? metricsScale - let next = Metrics(size: size, path: path, scale: scale) - guard next.acceptedPath else { - // The requested file never became the fixed-pitch face the grid - // requires. Keep every old metric and resolve the pending request - // as rejected rather than claiming the system fallback is it. - if resolvesRequest { pardes_font_reject() } - return - } - // A CGGlyph is an index into a particular face. Kept across a change - // it would draw a different character, not a missing one. - bodyGlyphCache.removeAll(keepingCapacity: true) - taglineGlyphCache.removeAll(keepingCapacity: true) - gripGlyphCache.removeAll(keepingCapacity: true) - ligatureShaped.removeAll(keepingCapacity: true) - metrics = next - taglines = TaglineMetrics(body: next, percent: taglines.percent, scale: scale) - metricsScale = scale - fontSize = size - fontPath = path - delegate?.pardesViewDidResize(self) - needsDisplay = true - reportEffectiveFont(resolvesRequest: resolvesRequest) - } - - /// Apply the core's live TaglineSize setting without touching body metrics, - /// the window grid, or PDF cell geometry. Called every pump; equality makes - /// the ordinary path one byte comparison. - @discardableResult - func adoptTaglinePercent(_ percent: UInt8) -> Bool { - guard percent != taglines.percent else { return false } - taglines = TaglineMetrics(body: metrics, percent: percent, scale: metricsScale) - taglineGlyphCache.removeAll(keepingCapacity: true) - gripGlyphCache.removeAll(keepingCapacity: true) - pardes_row_metrics(UInt16(max(1,(cellWidth*metricsScale).rounded())),UInt16(max(1,(cellHeight*metricsScale).rounded())), - UInt16(max(1,(taglines.width*metricsScale).rounded())),UInt16(max(1,(taglines.height*metricsScale).rounded()))) - needsDisplay = true - return true - } - - var taglinePercent: UInt8 { taglines.percent } - var taglineBandHeight: CGFloat { taglines.height } - var taglineCellWidth: CGFloat { taglines.width } - - /// Seed runtime Config after init and update it after every successful - /// adopt/zoom. Points are the native owner's unit; the cell's backing-pixel - /// dimensions continue to travel through pardes_resize separately. - func reportEffectiveFont(resolvesRequest: Bool = false) { - let hundredths = UInt16(min( - max((effectivePointSize * 100).rounded(), 1), - CGFloat(UInt16.max))) - let name = faceName - name.withCString { pointer in - if resolvesRequest { - _ = pardes_font_ack(pointer, name.utf8.count, hundredths) - } else { - _ = pardes_font_observe(pointer, name.utf8.count, hundredths) - } - } - } - - /// The file `Font ` resolved to, straight from the core. - func adoptFont(path: String, sizeHundredths: UInt16) { - let size = sizeHundredths == 0 ? fontSize : CGFloat(sizeHundredths) / 100 - wear(size: size, path: path, resolvesRequest: true) - } - - /// Cmd+ and Cmd-. Whole points, because the cell is rounded to whole - /// points anyway: a tenth-of-a-point step would spend several keystrokes - /// landing on the same grid and look like the key had stopped working. - /// The range is what stays legible at the bottom and still fits a useful - /// number of columns at the top. - func zoom(by step: CGFloat) { - let next = min(max(fontSize + step, 6), 72) - guard next != fontSize else { return } - wear(size: next, path: fontPath) - } - - func zoomReset() { - guard fontSize != defaultFontSize else { return } - wear(size: defaultFontSize, path: fontPath) - } - - // Row 0 at the top, so the drawing arithmetic reads like the grid it is. - override var isFlipped: Bool { true } - // Opaque only while the theme brings its own background AND that background - // is painted solid. A transparent theme has none, and an opaque view over a - // visual-effect backdrop is a grey rectangle where the blur should be; - // a WindowOpacity below 100 has the same problem against the desktop. - override var isOpaque: Bool { themeBG != nil && backgroundAlpha >= 1 } - override var acceptsFirstResponder: Bool { true } - // A click that focuses the window should also land in the grid: this is a - // text surface, and having to click twice after switching apps is the kind - // of thing that makes an app feel foreign. - override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } - - var gridSize: (cols: UInt16, rows: UInt16) { - let cols = min(max((bounds.width / cellWidth).rounded(.down), 1), CGFloat(UInt16.max)) - let rows = min(max((bounds.height / cellHeight).rounded(.down), 1), CGFloat(UInt16.max)) - return (UInt16(cols), UInt16(rows)) - } - - // MARK: - drawing - - override func draw(_ dirtyRect: NSRect) { - guard let destination = NSGraphicsContext.current?.cgContext else { return } - lastFrameUsedPostprocessor = false - // ponytail: dirtyRect is ignored. pardes_frame() re-renders the whole grid - // whatever we do, so clipping would save fills and nothing else. Narrow - // the row loops to the dirty band if that ever shows up in a profile. - let count = pardes_frame() - let nextPointer = pointerShape() - if nextPointer != pointer { - pointer = nextPointer - window?.invalidateCursorRects(for: self) - if let window, bounds.contains(convert(window.mouseLocationOutsideOfEventStream, from: nil)) { - cursorFor(pointer).set() - } - } - let scene = pardes_scene() - let trackCount = Int(pardes_frame_panel_tracks()) - let tracks: UnsafeBufferPointer - if trackCount > 0, let list = pardes_frame_panel_track_list() { - tracks = UnsafeBufferPointer(start: list, count: trackCount) - } else { - tracks = UnsafeBufferPointer(start: nil, count: 0) - } - let wantsPostprocess = scene.flags != 0 || !tracks.isEmpty - if wantsPostprocess { - if postprocessorUnavailable { - pardes_postprocessor_unavailable() - } else if let postprocessor = scenePostprocessor { - if let sceneContext = postprocessor.renderContext( - size: bounds.size, scale: window?.backingScaleFactor ?? metricsScale - ) { - drawFrame(sceneContext, count: count, hideCursor: !tracks.isEmpty) - let needsPrevious = tracks.contains { - $0.effect == UInt8(PARDES_PANEL_DISSOLVE) - || $0.effect == UInt8(PARDES_PANEL_VERTICAL) - } - var oldReady = !needsPrevious - let previousCells = pardes_frame_previous_cells() - let changedCells = pardes_frame_changed_cells() - if needsPrevious, let previousCells, changedCells != nil, - let oldContext = postprocessor.previousRenderContext( - size: bounds.size, - scale: window?.backingScaleFactor ?? metricsScale - ) { - drawFrame( - oldContext, count: count, cells: previousCells, - frozenImages: presentedImages, hideCursor: true) - oldReady = true - } - let outcome: ScenePostprocessor.CompositeOutcome = oldReady - ? postprocessor.composite( - scene: scene, tracks: tracks, - changedCells: changedCells, - changedAttachmentRects: changedAttachmentRects(), - gridSize: ( - cols: Int(pardes_frame_cols()), - rows: Int(pardes_frame_rows())), - cellSize: CGSize(width: cellWidth, height: cellHeight), - ground: themeBG, size: bounds.size, into: destination) - : .unavailable - switch outcome { - case .presented: - postprocessRetries = 0 - lastPresentedScene = scene - lastFrameUsedPostprocessor = true - acknowledgePresentation(animatedPanels: !tracks.isEmpty) - return - case .retry: - postprocessRetries += 1 - case .unavailable: - postprocessorUnavailable = true - } - } else { - postprocessRetries += 1 - } - // This draw now falls back to canonical content. Scene effects - // may retry, but a panel must not resume from a later sample - // after its final geometry has already been shown. - if !tracks.isEmpty { pardes_panel_animation_failed() } - if postprocessRetries >= 3 { postprocessorUnavailable = true } - if postprocessorUnavailable { pardes_postprocessor_unavailable() } - } else { - // The source, Metal device, or fixed kernel set was absent at - // lazy construction. None can recover within this process. - postprocessorUnavailable = true - pardes_postprocessor_unavailable() - } - } else { - postprocessRetries = 0 - } - lastPresentedScene = nil - drawFrame(destination, count: count, hideCursor: false) - acknowledgePresentation(animatedPanels: false) - } - - /// A presentation can materialize a Look target under a stationary mouse - /// after AppDelegate already decided whether to run its 60 Hz clock. Wake - /// the ordinary pump only for that null->active edge; repeated frame acks - /// remain inert and cannot create a redraw loop. - private func acknowledgePresentation(animatedPanels: Bool) { - // Only a canonical presentation advances the attachment baseline. - // During a transition deleted panes keep their cropped CGImages alive - // here even after both the core placement and image cache entry vanish. - if !animatedPanels { - presentedImages = frameImages - presentedBodyLayers = snapshotBodyLayers() - presentedTagLayers = snapshotTagLayers() - } - presentationSerial &+= 1 - let animationWoke = pardes_frame_presented(animatedPanels) - let pointerMoved = refreshPresentedPointer() - guard animationWoke || pointerMoved else { return } - DispatchQueue.main.async { - NotificationCenter.default.post(name: pardesDidInputNotification, object: self) - } - } - - /// Re-feed only a changed mapping. Sending motion on every 60 Hz scene - /// frame would keep resetting the core's hover debounce forever. - private func refreshPresentedPointer() -> Bool { - guard let point = pointerPoint else { return false } - guard let at = cellAt(point) else { - guard pointerMapped else { return false } - pointerMapped = false - pardes_pointer_leave() - return true - } - let changed: Bool - if let previous = pointerCell { - changed = !pointerMapped || previous.col != at.col || previous.row != at.row - } else { - changed = true - } - pointerMapped = true - pointerCell = at - guard changed else { return false } - if let button = latchedButton { - latchedCell = at - sendMouse(button, PARDES_MOUSE_DRAG, at.col, at.row, pointerModifiers) - } else { - sendMouse(PARDES_MOUSE_NONE, PARDES_MOUSE_MOTION, - at.col, at.row, pointerModifiers) - } - return true - } - - /// The canonical CoreText frame, independent of where it lands. Scene - /// effects change only the destination: direct view context when off, the - /// postprocessor's same-sized retained bitmap when on. - private func drawFrame( - _ ctx: CGContext, - count: UInt32, - cells suppliedCells: UnsafePointer? = nil, - frozenImages: [FrozenImage]? = nil, - hideCursor: Bool - ) { - let cols = Int(pardes_frame_cols()) - let rows = Int(pardes_frame_rows()) - // The ground, from the core rather than from a constant agreed by hand. - // A transparent theme has none: CLEAR rather than fill, because AppKit - // does not blank a non-opaque view and last frame's pixels would - // otherwise pile up on themselves. - let ground = themeBG ?? pardesDefaultBG - let clearGround = themeBG == nil - // AppKit does not blank a non-opaque view, so anything that leaves the - // ground short of solid has to clear first or last frame's pixels pile - // up on themselves — a translucent ground would darken toward opaque - // over a few frames otherwise. - if clearGround || backgroundAlpha < 1 { ctx.clear(bounds) } - if !clearGround { fillBackground(ctx, bounds, ground, backgroundAlpha) } - if frozenImages == nil { frameImages.removeAll(keepingCapacity: true) } - guard cols > 0, rows > 0, Int(count) == cols * rows, - let cells = suppliedCells ?? pardes_frame_cells() - else { return } - - // -1 when hidden, which never matches a real cell, so hidden and "bar, so - // not a block" collapse into the same comparison. - // A cursor has no pane/phase record. Match SDL and TTY by hiding it for - // the short panel transition instead of guessing whether it should - // move, stay fixed, or cover an overlapping opening pane. - let bar = !hideCursor && pardes_cursor_bar() - let blockX = hideCursor || bar ? -1 : Int(pardes_cursor_x()) - let blockY = hideCursor || bar ? -1 : Int(pardes_cursor_y()) - - // Background first, batched into runs of equal color. A full redraw is - // 80x24 cells at the low end and per-cell fills are exactly what makes - // that feel slow. Antialiasing is off because touching rects share an - // edge, and blending that edge twice draws a visible seam. - ctx.setShouldAntialias(false) - // Band geometry is stated against the whole canvas: the last row's rule - // depends on where the window edge is, not just on the row index. - let canvasHeight = bounds.height - for row in 0.. 0 { - let base = (rows - 1) * cols - for col in 0..() - if frozenImages == nil { - for index in 0..= 0 && x < cols && y >= 0 && y < rows { paneGripCells.insert(y * cols + x) } - } - } else { - for layer in presentedTagLayers where layer.values[1] == 2 { - let x = layer.values[4] - Int(pardes_tag_text_inset()), y = layer.values[5] - if x >= 0 && x < cols && y >= 0 && y < rows { paneGripCells.insert(y * cols + x) } - } - } - for row in 0..= 0, y >= 0, x < cols, y < rows { - // gui.zig paints U+258F here. A rect is the same picture without - // asking the font for a glyph it may not carry. - let cell = cells[y * cols + x] - let fg = resolve(cell, block: false, - ground: themeBG ?? pardesDefaultBG, clearGround: false).fg - let tagline = cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 - let caretY = CGFloat(y) * cellHeight - + (tagline ? taglines.top(row: y, canvasHeight: bounds.height) : 0) - let caretHeight = tagline ? taglines.height : cellHeight - // On the compact grid when the cell is, or the caret sits a - // growing distance to the left of the character it marks as the - // row runs on. The SDL shell puts its cursor bar through the - // same layout for the same reason. - let caretX = tagline - ? taglines.glyphX(col: x, row: y, bodyCellWidth: cellWidth) - : CGFloat(x) * cellWidth - let caretWidth = max(1, ((tagline ? taglines.width : cellWidth) / 8).rounded(.up)) - ctx.setShouldAntialias(false) - fill(ctx, CGRect(x: caretX, y: caretY, - width: caretWidth, height: caretHeight), fg, 1) - } - } - if frozenImages == nil { - drawBodyLayers(ctx, hideCursor:hideCursor) - drawTagLayers(ctx, hideCursor:hideCursor, canonical:cells, cols:cols, rows:rows) - } else { - for layer in presentedTagLayers { - layer.cells.withUnsafeBufferPointer { tagCells in - if let base = tagCells.baseAddress { - drawTagLayer(ctx, values: layer.values, cells: base, hideCursor: true, - canonical: cells, cols: cols) - } - } - drawTagGrip(ctx, values: layer.values, canonical: cells, cols: cols, rows: rows) - } - for layer in presentedBodyLayers { - layer.cells.withUnsafeBufferPointer { cells in - if let base = cells.baseAddress { drawBodyLayer(ctx, values:layer.values, cells:base, hideCursor:true) } - } - } - drawTagRules(ctx, layers: presentedTagLayers.map { $0.values }) - } - drawHoverGlass(ctx, cells: cells, cols: cols, rows: rows) - } - - private var presentedTagLayers: [FrozenBodyLayer] = [] - - private func snapshotTagLayers() -> [FrozenBodyLayer] { - var result: [FrozenBodyLayer] = [] - for index in 0.., cols: Int, rows: Int) { - var layers: [[Int]] = [] - for index in 0.. 0 { - fillBackground(ctx, CGRect(x: 0, y: taglines.borderTop, width: bounds.width, - height: taglines.borderThickness), - pardes_topbar_pane_border_rgb(), backgroundAlpha) - } - } - - private func gripGlyph(_ text: String, face: Face) -> GripGlyph? { - let key = "\(face.rawValue):\(text)" - if let cached = gripGlyphCache[key] { return cached } - let attributed = NSAttributedString(string: text, attributes: [fontAttribute: taglines.fonts[face.rawValue], - NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) - let line = CTLineCreateWithAttributedString(attributed as CFAttributedString) - let ink = CTLineGetBoundsWithOptions(line, [.useGlyphPathBounds]) - guard !ink.isNull, !ink.isInfinite, !ink.isEmpty else { return nil } - let measured = GripGlyph(line: line, ink: ink) - gripGlyphCache[key] = measured - return measured - } - - private func drawTagGrip(_ ctx: CGContext, values: [Int], canonical: UnsafePointer, cols: Int, rows: Int) { - let x = values[4] - Int(pardes_tag_text_inset()), y = values[5] - if values[1] != 2 || x < 0 || x >= cols || y < 0 || y >= rows { return } - var cell = canonical[y * cols + x] - let text = withUnsafeBytes(of: &cell.text) { String(decoding: $0.prefix(Int(cell.len)), as: UTF8.self) } - if text.isEmpty { return } - let style = resolve(cell, block:false, ground:themeBG ?? pardesDefaultBG, clearGround:false) - // The box drawTagLayer filled is this mark's ground, so the mark - // centres on that same square rather than on the grip columns: one - // rect measures both and the two cannot drift apart. - guard let square = anchorSquare(values: values) else { return } - let centerX = square.midX, centerY = square.midY - if text != " " { - let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, - italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) - guard style.visible, let measured = gripGlyph(text, face: face) else { return } - let originX = ((centerX - measured.ink.midX) * metricsScale).rounded() / metricsScale - let baseline = ((bounds.height - centerY - measured.ink.midY) * metricsScale).rounded() / metricsScale - ctx.saveGState() - ctx.clip(to: square) - ctx.translateBy(x: 0, y: bounds.height) - ctx.scaleBy(x: 1, y: -1) - ctx.textMatrix = .identity - ctx.textPosition = CGPoint(x: originX, y: baseline) - setFill(ctx, style.fg, style.alpha) - CTLineDraw(measured.line, ctx) - ctx.restoreGState() - return - } - if taglines.height < 6 || taglines.width < 3 { return } - let halfWidth = max(1, min(3, cellWidth - 2)) - fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY-2), width:2*halfWidth, height:1), style.fg, 1) - fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY+1), width:2*halfWidth, height:1), style.fg, 1) - } - - private func drawTagLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer, - hideCursor: Bool, canonical: UnsafePointer, cols: Int) { - let left = CGFloat(values[4]) * cellWidth - let y = CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height) - // SDL gives the tag a full body-row background; only its glyphs - // and per-cell highlights use the compact band. The band spans the - // row's whole extent, not just its text: the grip and the mode box - // live in the inset columns to the left of `values[4]`, and their - // own fills cover only the compact band — a row background that - // stops at the text leaves holes of ground under those anchors. - // The rule in drawTagRules spans exactly this left-to-right range. - let rowLeft = CGFloat(max(0, values[4] - Int(pardes_tag_text_inset()))) * cellWidth - let rowRight = CGFloat(values[4] + values[6]) * cellWidth - let viewport = CGRect(x: rowLeft, y: CGFloat(values[5]) * cellHeight, - width: rowRight - rowLeft, height: cellHeight) - ctx.saveGState() - ctx.clip(to: viewport) - fillBackground(ctx, viewport, UInt32(values[10]), backgroundAlpha) - // The anchor (grip, mode box) lives in the inset columns that fill - // just covered, so its own box goes back on top: one solid fill in - // the box colour the anchor cell wears, with drawTagGrip's mark - // drawn over it afterwards. - if let square = anchorSquare(values: values) { - let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) - let cell = canonical[values[5] * cols + anchorX] - let style = resolve(cell, block: false, - ground: UInt32(values[10]), clearGround: false) - if style.visible { fillBackground(ctx, square.integral, style.bg, backgroundAlpha) } - } - - for pass in 0...1 { - for col in 0.. CGRect? { - let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) - guard anchorX < values[4] else { return nil } - let pad = (cellHeight - taglines.height) / 2 - return CGRect(x: CGFloat(anchorX) * cellWidth + pad, - y: CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height), - width: taglines.height, height: taglines.height) - } - - /// The look-hover affordance as liquid glass: the core marks the word's - /// cells (PARDES_CELL_HOVER), and this composes a real material over the - /// run — the drawn frame snapshot refracted through CoreImage (a small - /// blur, then a lens scale about the pill's centre, which is what makes - /// the edges swim), the theme's selection colour as a faint tint, a - /// specular sheen from the top edge, and a light rim — with the word's - /// own glyphs drawn back on top, crisp, the way text sits on a real - /// material rather than behind one. - private func drawHoverGlass(_ ctx: CGContext, cells: UnsafePointer, cols: Int, rows: Int) { - var drew = false - for row in 0..= 0 { - let rect = CGRect(x: CGFloat(start) * cellWidth, y: CGFloat(row) * cellHeight, - width: CGFloat(col - start) * cellWidth, height: cellHeight) - drawLiquidGlass(ctx, rect, tint: tint) - redrawHoverRun(ctx, cells, cols: cols, row: row, start: start, end: col) - drew = true - start = -1 - } - } - } - // No affordance this frame: the held snapshot describes a frame - // that no longer exists, and the next hover must take a fresh one. - if !drew { glassShot = nil } - } - - /// A CoreImage context for the glass refraction, created once. - private lazy var glassContext = CIContext() - /// The snapshot behind the current pill. Refraction reads the already - /// drawn frame, and re-reading it every pump would blur a moving pill - /// out of its own budget, so the shot is taken when the rect changes. - private var glassShot: (rect: CGRect, image: CGImage)? - - private func drawLiquidGlass(_ ctx: CGContext, _ rect: CGRect, tint: UInt32) { - let radius = min(rect.height / 4, 6) - let pill = CGPath(roundedRect: rect.insetBy(dx: 1, dy: 1.5), - cornerWidth: radius, cornerHeight: radius, transform: nil) - // The refraction: the frame as drawn, blurred a little and scaled - // about the pill's centre, so the rim bends what surrounds it. The - // shot extends past the pill for exactly this — the lens needs - // pixels from outside the glass to pull in. - let lens = rect.insetBy(dx: -10, dy: -10) - if refract(ctx, pill: pill, rect: rect, lens: lens, tint: tint) { - // Specular: light caught at the top edge, fading as it falls. - ctx.saveGState() - ctx.addPath(pill) - ctx.clip() - let shine = [CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.22), - CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.0)] as CFArray - if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), - colors: shine, locations: [0, 0.55]) { - ctx.drawLinearGradient(gradient, - start: CGPoint(x: rect.minX, y: rect.minY), - end: CGPoint(x: rect.minX, y: rect.maxY), options: []) - } - ctx.restoreGState() - } else { - // No refraction without a snapshot: the tint alone, faint. - ctx.saveGState() - ctx.addPath(pill) - ctx.clip() - ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, - green: CGFloat((tint >> 8) & 0xFF) / 255, - blue: CGFloat(tint & 0xFF) / 255, - alpha: 0.18)) - ctx.fill(rect) - ctx.restoreGState() - } - // The lens edge: a light rim and a darker bottom hairline, the way a - // real material catches its own edge. - ctx.addPath(pill) - ctx.setStrokeColor(CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.35)) - ctx.setLineWidth(1) - ctx.strokePath() - ctx.addPath(pill) - ctx.setStrokeColor(CGColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.25)) - ctx.setLineWidth(0.5) - ctx.clip() - ctx.stroke(CGRect(x: rect.minX, y: rect.maxY - 2, width: rect.width, height: 1.5)) - } - - /// True when the refraction composited. The snapshot is taken when the - /// pill moves and reused while it sits still. - private func refract(_ ctx: CGContext, pill: CGPath, rect: CGRect, lens: CGRect, tint: UInt32) -> Bool { - guard let shot = snapshotFor(ctx, lens: lens) else { return false } - var image = CIImage(cgImage: shot) - // The blur is grown slightly past the crop and the whole thing is - // pulled toward the centre by a few percent: the rim bends what - // surrounds it, which is the refraction the eye reads as glass. - let blur = image.applyingGaussianBlur(sigma: 2 * metricsScale) - let grown = blur.extent.insetBy(dx: -8 * metricsScale, dy: -8 * metricsScale) - let centre = CGPoint(x: grown.midX, y: grown.midY) - let scale = 1.06 - let lensTransform = CGAffineTransform(translationX: centre.x * (1 - scale), - y: centre.y * (1 - scale)).scaledBy(x: scale, y: scale) - image = blur.transformed(by: lensTransform) - guard let filtered = glassContext.createCGImage(image, from: grown) else { return false } - ctx.saveGState() - ctx.addPath(pill) - ctx.clip() - ctx.draw(filtered, in: rect) - // The glass's own body colour: the theme's selection, faint — the - // refraction and the sheen carry the material, not opacity. - ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, - green: CGFloat((tint >> 8) & 0xFF) / 255, - blue: CGFloat(tint & 0xFF) / 255, - alpha: 0.15)) - ctx.fill(rect) - ctx.restoreGState() - return true - } - - private func snapshotFor(_ ctx: CGContext, lens: CGRect) -> CGImage? { - if let held = glassShot, held.rect == lens { return held.image } - guard let whole = ctx.makeImage() else { return nil } - // makeImage hands back backing pixels; the lens is in view points. - let region = CGRect(x: lens.minX * metricsScale, y: lens.minY * metricsScale, - width: lens.width * metricsScale, height: lens.height * metricsScale) - guard let cropped = whole.cropping(to: region) else { return nil } - glassShot = (lens, cropped) - return cropped - } - - /// The hovered word's glyphs, back on top of the material, crisp: text - /// sits on liquid glass, not behind it. - private func redrawHoverRun(_ ctx: CGContext, _ cells: UnsafePointer, - cols: Int, row: Int, start: Int, end: Int) { - ctx.saveGState() - ctx.textMatrix = .identity - ctx.translateBy(x: 0, y: bounds.height) - ctx.scaleBy(x: 1, y: -1) - let baseline = bounds.height - (CGFloat(row) * cellHeight + metrics.ascent) - for col in start.. [FrozenBodyLayer] { - var result: [FrozenBodyLayer] = [] - for index in 0.., hideCursor: Bool) { - func value(_ field: Int) -> Int { values[field] } - let rows = value(0), cols = value(1), contexts = value(2) - let left = CGFloat(value(3)) * cellWidth, top = CGFloat(value(4)) * cellHeight - let viewport = CGRect(x: left, y: top, width: CGFloat(value(5))*cellWidth, - height: CGFloat(value(6))*cellHeight) - ctx.saveGState() - ctx.clip(to: viewport) - fillBackground(ctx, viewport, themeBG ?? bgClear, backgroundAlpha) - for row in 0..= viewport.maxY { break } - let rowStyle = resolve(cells[row*cols], block: false, ground: themeBG ?? pardesDefaultBG, clearGround: themeBG == nil) - fillBackground(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, backgroundAlpha) - for pass in 0...1 { - for col in 0.. 0, let list = pardes_frame_image_list() else { - // Nothing on screen owns pixels any more: the pages a closed pane - // rendered would otherwise sit in here for the rest of the session. - if !imageCache.isEmpty { imageCache.removeAll(keepingCapacity: true) } - return - } - - // The core computed every rectangle in PHYSICAL pixels, because that is - // what pardes_resize handed it. The view draws in points. - let scale = max(1, metricsScale) - var live = Set() - live.reserveCapacity(count) - - ctx.setShouldAntialias(true) - for i in 0.. live.count { - imageCache = imageCache.filter { live.contains($0.key) } - } - } - - private func drawFrozenImages(_ ctx: CGContext, _ images: [FrozenImage]) { - ctx.setShouldAntialias(true) - for image in images { drawFrozenImage(ctx, image) } - } - - /// Native attachments do not occupy Cell graphemes, so the core's semantic - /// text/style mask cannot see a page appearing, disappearing, rerasterizing - /// or moving. Add only those changed placements to the shader mask; an - /// identical key and geometry remains immediate like any unchanged cell. - private func changedAttachmentRects() -> [CGRect] { - var oldByKey: [ImageKey: FrozenImage] = [:] - for image in presentedImages { oldByKey[image.key] = image } - var changed: [CGRect] = [] - changed.reserveCapacity(frameImages.count + presentedImages.count) - for image in frameImages { - guard let old = oldByKey.removeValue(forKey: image.key) else { - changed.append(image.destination.intersection(image.body)) - continue - } - if old.source != image.source - || old.body != image.body || old.destination != image.destination { - changed.append(old.destination.intersection(old.body)) - changed.append(image.destination.intersection(image.body)) - } - } - for old in oldByKey.values { - changed.append(old.destination.intersection(old.body)) - } - return changed.filter { !$0.isNull && !$0.isEmpty } - } - - private func drawFrozenImage(_ ctx: CGContext, _ placed: FrozenImage) { - ctx.saveGState() - ctx.clip(to: placed.body) - // isFlipped gives us a y-down CTM and CGImage draws +y up, so flip - // about this destination rather than changing the grid arithmetic. - let isPDF = placed.paperBG != UInt32(PARDES_COLOR_DEFAULT) - if isPDF { - fillBackground(ctx, placed.destination, placed.paperBG, backgroundAlpha) - } - ctx.translateBy(x: placed.destination.minX, y: placed.destination.maxY) - ctx.scaleBy(x: 1, y: -1) - ctx.interpolationQuality = .high - let rect = CGRect(x: 0, y: 0, - width: placed.destination.width, height: placed.destination.height) - if isPDF { - // Paper was painted at WindowOpacity. Content keeps the PDF's own - // coverage, so glyphs, photos and paths stay legible at zero opacity. - ctx.setAlpha(1) - ctx.setBlendMode(.normal) - ctx.draw(placed.image, in: rect) - ctx.restoreGState() - return - } - // Match image.frag.glsl/backgroundLayerBlend: source coverage removes - // the destination independently of WindowOpacity, then the source is - // added at that opacity. Ordinary source-over would compound alpha; - // copy would discard the background under transparent image pixels. - ctx.setAlpha(1) - ctx.setBlendMode(.destinationOut) - ctx.draw(placed.image, in: rect) - ctx.setAlpha(backgroundAlpha) - ctx.setBlendMode(.plusLighter) - ctx.draw(placed.image, in: rect) - ctx.restoreGState() - } - - /// The decoded raster for one attachment, made once per generation. - private func image(for place: pardes_image_s, key: ImageKey) -> CGImage? { - if let cached = imageCache[key] { return cached } - let bytes = Int(place.iw) * Int(place.ih) * 4 - guard bytes > 0, let rgba = place.rgba else { return nil } - // Copied, not referenced: the core lends these bytes until the next - // pardes_frame and this image outlives many of them. - guard let data = CFDataCreate(nil, rgba, bytes), - let provider = CGDataProvider(data: data) - else { return nil } - // Straight alpha, R,G,B,A in memory — the same bytes the SDL shell - // uploads as R8G8B8A8_UNORM and blends with ONE_MINUS_SRC_ALPHA. - let made = CGImage( - width: Int(place.iw), height: Int(place.ih), - bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(place.iw) * 4, - space: sRGB, - bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue | CGBitmapInfo.byteOrder32Big.rawValue), - provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) - if let made { imageCache[key] = made } - return made - } - - /// One row of glyphs, batched. Consecutive cells that share a face and a - /// colour go to CoreText as a single call with a position array: a row of - /// plain text is then one draw instead of eighty, which is the difference - /// between a full redraw being free and being felt. - private func drawRow( - _ ctx: CGContext, - _ cells: UnsafePointer, - base: Int, - cols: Int, - /// This row's grid index. Needed per cell rather than per row for the - /// compact tagline anchor: a column split puts two panes' tags side by - /// side on ONE row, so the origin is a question about the cell. - row: Int, - baseline: CGFloat, - /// Where this row's tagline band starts, from the row's top. Passed in - /// rather than recomputed per cell: it is one answer per row, and the - /// glyph has to sit in the band the background pass painted. - taglineTop: CGFloat, - blockCol: Int, - paneGripCells: Set - ) { - var runFace = Face.regular - var runTagline = false - var runColor: UInt32 = 0 - var runAlpha: CGFloat = 1 - runGlyphs.removeAll(keepingCapacity: true) - runPositions.removeAll(keepingCapacity: true) - ligatureCovered.removeAll(keepingCapacity: true) - - func flush() { - guard !runGlyphs.isEmpty else { return } - setFill(ctx, runColor, runAlpha) - let font = runTagline - ? taglines.fonts[runFace.rawValue] - : metrics.fonts[runFace.rawValue] - CTFontDrawGlyphs(font, runGlyphs, runPositions, runGlyphs.count, ctx) - runGlyphs.removeAll(keepingCapacity: true) - runPositions.removeAll(keepingCapacity: true) - } - - for col in 0..> UInt16(PARDES_ATTR_UL_SHIFT) != 0 - || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { - flush() - drawRules(ctx, cell, style, x: x, width: advanceWidth, baseline: cellBaseline) - } - guard style.visible else { continue } - - // UNVERIFIED: withUnsafeBytes over an imported C fixed-size array, which - // Swift models as an 8-tuple. String(decoding:) substitutes U+FFFD rather - // than trapping, and the core has shipped invalid UTF-8 through here - // before — the renderer must not be the thing that dies over it. prefix - // clamps, so a bogus len cannot walk off the eight bytes either. - let text = withUnsafeBytes(of: cell.text) { raw in - String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) - } - guard !text.isEmpty, text != " " else { continue } - - let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, - italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) - if paneGripCells.contains(base + col) && gripGlyph(text, face: face) != nil { - // The layer pass centers this symbol by its actual ink bounds. - continue - } - let units = text.utf16 - let known = units.count == 1 ? glyph(face, units.first!, tagline: tagline) : 0 - if known != 0 { - // Ligatures: consecutive cells shaped together when the face - // collapses them into fewer glyphs. A monospace coding - // ligature advances by the same whole cells its characters - // did, so the grid cannot drift and only the ink changes. - if !tagline, let ligature = ligatureSpan(cells, base: base, cols: cols, col: col, - face: face, fg: style.fg, alpha: style.alpha, - blockCol: blockCol, paneGripCells: paneGripCells) { - flush() - setFill(ctx, style.fg, style.alpha) - let attributed = NSAttributedString(string: ligature.text, - attributes: [fontAttribute: metrics.fonts[face.rawValue], - NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) - ctx.textPosition = CGPoint(x: x, y: cellBaseline) - CTLineDraw(CTLineCreateWithAttributedString(attributed as CFAttributedString), ctx) - ctx.textMatrix = .identity - for covered in 1.. CGGlyph { - if character < 128 { - let ascii = tagline ? taglines.asciiGlyphs : metrics.asciiGlyphs - return ascii[face.rawValue][Int(character)] - } - let key = UInt32(face.rawValue) << 16 | UInt32(character) - if tagline, let cached = taglineGlyphCache[key] { return cached } - if !tagline, let cached = bodyGlyphCache[key] { return cached } - var input = character - var found = CGGlyph(0) - let font = tagline ? taglines.fonts[face.rawValue] : metrics.fonts[face.rawValue] - _ = CTFontGetGlyphsForCharacters(font, &input, &found, 1) - if tagline { - taglineGlyphCache[key] = found - } else { - bodyGlyphCache[key] = found - } - return found - } - - /// Ligature-prone character heads: a coding ligature always begins with - /// one of these, and refusing everything else keeps the per-frame cost of - /// ligature detection a set lookup rather than a shape. - private static let ligatureHeads: Set = [ - "<", ">", "=", "!", "&", "|", "-", "/", ":", ".", "#", "*", "+", "~", "^", "%", - ] - - private func ligates(_ face: Face, _ text: String) -> Bool { - let key = "\(face.rawValue):\(text)" - if let cached = ligatureShaped[key] { return cached } - let attributed = NSAttributedString(string: text, attributes: [fontAttribute: metrics.fonts[face.rawValue], - NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) - let shaped = CTLineCreateWithAttributedString(attributed as CFAttributedString) - var glyphs: [CGGlyph] = [] - for run in (CTLineGetGlyphRuns(shaped) as? [CTRun]) ?? [] { - let count = CTRunGetGlyphCount(run) - var runGlyphs = [CGGlyph](repeating: 0, count: count) - CTRunGetGlyphs(run, CFRange(location: 0, length: count), &runGlyphs) - glyphs.append(contentsOf: runGlyphs) - } - // A ligature is any divergence from per-character mapping. A font may - // collapse the pair into one glyph (JetBrains Mono) or swap each - // character for a joining half kept at the same count (Maple Mono) — - // either way the sequence must be shaped, not mapped. - let singles = text.utf16.map { glyph(face, $0, tagline: false) } - let result = glyphs.count != singles.count - || zip(glyphs, singles).contains { $0 != $1 } - ligatureShaped[key] = result - return result - } - - /// When the cells at `col` ligate under `face`, the text to shape and how - /// many cells the ligature covers. Nil when they do not. Ligature cells - /// must carry the same face, colour and alpha and no rules of their own — - /// a ligature is one glyph of one style, not a style transition. - private func ligatureSpan(_ cells: UnsafePointer, base: Int, cols: Int, col: Int, - face: Face, fg: UInt32, alpha: CGFloat, - blockCol: Int, paneGripCells: Set) -> (text: String, covered: Int)? { - func eligible(_ index: Int) -> String? { - let cell = cells[base + index] - if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { return nil } - if cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 { return nil } - if cell.attrs >> UInt16(PARDES_ATTR_UL_SHIFT) != 0 - || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { return nil } - if paneGripCells.contains(base + index) { return nil } - let text = withUnsafeBytes(of: cell.text) { raw in - String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) - } - guard text.utf16.count == 1 else { return nil } - let other = resolve(cell, block: blockCol == index, - ground: themeBG ?? pardesDefaultBG, clearGround: false) - guard other.visible, other.fg == fg, other.alpha == alpha, - Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, - italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) == face else { return nil } - return text - } - guard let head = eligible(col), PardesView.ligatureHeads.contains(head.first!) else { return nil } - guard col + 1 < cols, let second = eligible(col + 1) else { return nil } - let pair = head + second - if col + 2 < cols, let third = eligible(col + 2) { - let triple = pair + third - if ligates(face, triple) { return (triple, 3) } - } - if ligates(face, pair) { return (pair, 2) } - return nil - } - - private func drawRules( - _ ctx: CGContext, - _ cell: pardes_cell_s, - _ style: (fg: UInt32, bg: UInt32, alpha: CGFloat, visible: Bool), - x: CGFloat, - /// The cell's advance: the body cell, or the narrower tagline one. A - /// rule is as wide as the character it belongs to, and on a tag row - /// that stopped being the body cell when the text compacted. - width: CGFloat, - baseline: CGFloat - ) { - let underline = Int(cell.attrs >> PARDES_ATTR_UL_SHIFT) & 7 - if underline != Int(PARDES_UL_OFF) { - let y = baseline + metrics.underlineOffset - fill(ctx, CGRect(x: x, y: y, width: width, height: metrics.ruleThickness), style.fg, style.alpha) - // ponytail: curly, dotted and dashed all come out solid; only double - // earns its second rule. ctx.setLineDash for two of them and a sine - // path for the third is the upgrade, once anyone notices. - if underline == Int(PARDES_UL_DOUBLE) { - fill(ctx, CGRect(x: x, y: y - metrics.ruleThickness * 2, width: width, height: metrics.ruleThickness), - style.fg, style.alpha) - } - } - if cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { - // Rounded like every other rule offset: a third of the ascent is a - // fraction, and a fractional one-pixel bar is a two-pixel smear. - fill(ctx, CGRect(x: x, y: baseline + (metrics.ascent * 0.3).rounded(), width: width, height: metrics.ruleThickness), - style.fg, style.alpha) - } - } - - private func setFill(_ ctx: CGContext, _ rgb: UInt32, _ alpha: CGFloat) { - // Theme channels, like PDF raster bytes, are sRGB. Device RGB can - // brighten them when AppKit's backing bitmap uses another profile. - ctx.setFillColor(CGColor(srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, - green: CGFloat((rgb >> 8) & 0xFF) / 255, - blue: CGFloat(rgb & 0xFF) / 255, - alpha: alpha)) - } - - /// One surface pixel has one background opacity, even when a compact - /// layer covers a canonical cell. Source-over would turn 71% into 92%, - /// then 98%, as the ground, row and cell are painted over each other. - private func fillBackground(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { - ctx.saveGState() - ctx.setShouldAntialias(false) - if rgb == bgClear { - ctx.clear(rect) - } else { - ctx.setBlendMode(.copy) - fill(ctx, rect, rgb, alpha) - } - ctx.restoreGState() - } - - private func fill(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { - setFill(ctx, rgb, alpha) - ctx.fill(rect) - } - - // MARK: - the core, and the pump - - /// Everything below ends here. Posting the notification in one place is - /// what guarantees no entry point can feed the core and forget to ask for - /// the tick that performs it. - private func fed() { - NotificationCenter.default.post(name: pardesDidInputNotification, object: self) - } - - /// A point inside the NSView can still be outside the CRT's curved tube. - /// For input that is the same as leaving the grid: discard a pending hover - /// preview, but do not manufacture a clamped click or wheel gesture. - private func leftGrid() { - pardes_pointer_leave() - fed() - } - - func typeKey(_ cp: UInt32, text: String, mods: UInt32) { - // The pointer is borrowed for the call and nowhere else, which is the only - // thing the header promises about it. - text.withCString { pardes_key(cp, $0, text.utf8.count, mods) } - fed() - } - - // `mods` defaults to none because a synthesized gesture carries no - // keyboard state; the NSEvent overrides always pass the real mask. Ctrl is - // the one the core actually consults — a left press with it held is - // goto-definition — so dropping it here would silently delete a feature. - private var sampledBodyPointer: CGPoint? - - private func sendMouse(_ button: pardes_mouse_button_e, _ kind: pardes_mouse_kind_e, - _ col: UInt16, _ row: UInt16, _ mods: UInt32) { - guard let point = sampledBodyPointer else { - pardes_mouse(button, kind, col, row, mods) - return - } - let scale = metricsScale - pardes_mouse_pixel(button, kind, col, row, mods, Float(point.x*scale), Float(point.y*scale), - Float(cellWidth*scale), Float(cellHeight*scale), Float(taglines.width*scale), Float(taglines.height*scale)) - } - - func press(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { - sendMouse(button, PARDES_MOUSE_PRESS, cell.col, cell.row, mods) - fed() - } - - func release(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { - sendMouse(button, PARDES_MOUSE_RELEASE, cell.col, cell.row, mods) - fed() - } - - func drag(_ button: pardes_mouse_button_e, to cell: GridPoint, mods: UInt32 = 0) { - sendMouse(button, PARDES_MOUSE_DRAG, cell.col, cell.row, mods) - fed() - } - - func motion(to cell: GridPoint, mods: UInt32 = 0) { - sendMouse(PARDES_MOUSE_NONE, PARDES_MOUSE_MOTION, cell.col, cell.row, mods) - fed() - } - - /// A press and its release with nothing in between, which is what every - /// synthesized click is: a trackpad gesture we recognised rather than a - /// button the user held. - func click(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { - press(button, at: cell, mods: mods) - release(button, at: cell, mods: mods) - } - - /// One discrete wheel notch, as opposed to the continuous travel below. - func wheel(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { - sendMouse(button, PARDES_MOUSE_PRESS, cell.col, cell.row, mods) - fed() - } - - func scroll(rows: CGFloat, cols: CGFloat = 0, at cell: GridPoint) { - guard rows != 0 || cols != 0 else { return } - pardes_scroll(Float(rows), Float(cols), cell.col, cell.row) - fed() - } - - /// Fingers down and fingers up on a precise scroll. Entry points of their - /// own for the same reason rotateEnd is one: NSEvent phases have no public - /// constructor, and a fling nothing can synthesize is a fling nothing can - /// assert. - func scrollBegin() { - pardes_scroll_begin() - fed() - } - - func scrollEnd() { - pardes_scroll_end() - fed() - } - - func rotate(degrees: CGFloat) { - guard degrees != 0 else { return } - pardes_rotate(Float(degrees)) - fed() - } - - /// The fingers came off the trackpad. A post-decode entry point of its own - /// so the e2e harness can throw the dial: NSEvent phases have no public - /// constructor, and a fling nothing can synthesize is a fling nothing can - /// assert. - func rotateEnd() { - pardes_rotate_end() - fed() - } - - // MARK: - keyboard - - override func keyDown(with event: NSEvent) { - let flags = event.modifierFlags - // Same reason as the trackpad trace below: whether AppKit delivered a - // keystroke at all is not something this process can otherwise answer, - // and "Escape does nothing" has two entirely different causes - // depending on whether this line prints. - trace("key: code=\(event.keyCode) mods=\(flags.rawValue) chars=" + - (event.charactersIgnoringModifiers?.unicodeScalars - .map { String($0.value, radix: 16) }.joined(separator: ",") ?? "-")) - // The ABI has no super bit, so a Command chord cannot be expressed at all. - // Anything the main menu claims never reaches here; the rest is swallowed - // rather than delivered as the bare keystroke the core would insert. - if flags.contains(.command) { - if event.charactersIgnoringModifiers?.lowercased() == "v" { - delegate?.pardesViewRequestsPaste(self) - } - return - } - - let control = flags.contains(.control) - let option = flags.contains(.option) - // With ctrl or option down, `characters` is already the composed result — - // Ctrl-A is U+0001, Option-A is "å". The core wants the base key and no - // text, which is what app.mjs does with the same two bits. - let composed = (control || option ? event.charactersIgnoringModifiers : event.characters) ?? "" - guard let scalar = composed.unicodeScalars.first else { return } - - var codepoint = scalar.value - // 0xF700..0xF8FF is AppKit's private-use block for function keys. The nine - // the core names get translated; the rest (F1-F12, Insert, the keypad) are - // dropped, because passing one through paints a stray glyph. - // These constants come from an unnamed C enum, so which width Swift picks - // for them is not something this file should depend on: wrapping each in - // UInt32() compiles whether they import as Int, Int32 or UInt32. - if scalar.value >= 0xF700 && scalar.value <= 0xF8FF { - switch scalar.value { - case UInt32(NSUpArrowFunctionKey): codepoint = UInt32(PARDES_KEY_UP) - case UInt32(NSDownArrowFunctionKey): codepoint = UInt32(PARDES_KEY_DOWN) - case UInt32(NSLeftArrowFunctionKey): codepoint = UInt32(PARDES_KEY_LEFT) - case UInt32(NSRightArrowFunctionKey): codepoint = UInt32(PARDES_KEY_RIGHT) - case UInt32(NSHomeFunctionKey): codepoint = UInt32(PARDES_KEY_HOME) - case UInt32(NSEndFunctionKey): codepoint = UInt32(PARDES_KEY_END) - case UInt32(NSPageUpFunctionKey): codepoint = UInt32(PARDES_KEY_PAGE_UP) - case UInt32(NSPageDownFunctionKey): codepoint = UInt32(PARDES_KEY_PAGE_DOWN) - case UInt32(NSDeleteFunctionKey): codepoint = UInt32(PARDES_KEY_DELETE) - default: return - } - } - - // Enter, Tab, Escape and Backspace already arrive as the ASCII controls the - // header names. Two keys do not: the keypad's Enter is U+0003 and Shift-Tab - // is U+0019, neither of which is in the function-key block above, so without - // this both reach the core as a control it has no binding for and do - // nothing. The browser shell resolves them from the DOM key name and this - // is what keeps the two hosts saying the same thing. - if codepoint == 0x03 { codepoint = UInt32(PARDES_KEY_ENTER) } - if codepoint == 0x19 { codepoint = UInt32(PARDES_KEY_TAB) } - - // A control character is functional, and functional keys must not also - // carry text. - let functional = codepoint < 0x20 || codepoint == 0x7F || codepoint >= 0xF0000 - let text = functional || control || option ? "" : composed - // Typing is the moment the pointer stops being interesting and starts - // sitting on top of the words. It comes back on the next mouse move. - NSCursor.setHiddenUntilMouseMoves(true) - typeKey(codepoint, text: text, mods: modifiers(flags)) - } - - // MARK: - trackpad - - // NSTouch arrives through these four and nowhere else. They are the only - // reliable source of "how many fingers are down right now": the touch set - // on a mouse event is an accident of how the click was produced, and an - // empty one is indistinguishable from one finger. - override func touchesBegan(with event: NSEvent) { countTouches(event) } - override func touchesMoved(with event: NSEvent) { countTouches(event) } - override func touchesEnded(with event: NSEvent) { countTouches(event) } - override func touchesCancelled(with event: NSEvent) { countTouches(event) } - - private func countTouches(_ event: NSEvent) { - restingFingers = event.touches(matching: .touching, in: nil).count - trace("touch: resting=\(restingFingers)") - } - - // MARK: - mouse - - // All three button streams land in the same three functions, because which - // stream a trackpad click arrives on is not something the app gets to know - // in advance: with macOS's secondary click on, two AND three fingers both - // come in as rightMouseDown. The button is therefore decided once, at the - // press, from the fingers plus the stream, and then LATCHED — the core is - // tracking a drag keyed by button, and answering a press of 3 with a - // release of 1 leaves it holding a sweep nothing will ever end. - // - // The count itself is maintained by the touchesXxx callbacks above; see - // beginClick for why it can only come from there. - private func beginClick(_ stream: pardes_mouse_button_e, _ event: NSEvent) { - guard let at = cell(for: event) else { - leftGrid() - return - } - pressureStage = 0 - // The count comes from the touch stream and NEVER from the mouse event. - // Asking a mouse event for its touches is not merely unreliable, it - // raises: -[NSEvent touchesMatchingPhase:inView:] is defined for - // gesture and touch events, and on anything else AppKit throws, catches - // it inside its own event dispatch, and abandons the rest of this - // method. Nothing crashes and nothing is logged — every click just - // silently stops working, a plain drag included, while rotation and - // scrolling carry on as if the backend were fine. That is exactly how - // this presented, and it is why restingFingers exists. - let button = Trackpad.button(stream: stream, fingers: restingFingers) - trace("press: stream=\(stream.rawValue) fingers=\(restingFingers) -> button=\(button.rawValue)") - latchedButton = button - latchedCell = at - press(button, at: at, mods: modifiers(event.modifierFlags)) - } - - private func continueClick(_ event: NSEvent) { - guard let button = latchedButton else { return } - guard let at = cell(for: event) else { - // The drag is still latched, but the curved CRT edge displays no - // source cell here. Keep its last real endpoint for mouseUp and - // clear hover/seam state without clamping into the grid. - leftGrid() - return - } - latchedCell = at - drag(button, to: at, mods: modifiers(event.modifierFlags)) - } - - private func endClick(_ event: NSEvent) { - pressureStage = 0 - // Already nil when the force click below converted this press: it - // released the button itself and there is nothing left to end. - guard let button = latchedButton else { return } - latchedButton = nil - if let at = cell(for: event) { - latchedCell = nil - release(button, at: at, mods: modifiers(event.modifierFlags)) - return - } - // A release must balance its press even when the hand ends in a black - // CRT corner. The last mapped drag point is an observed source cell, - // not a clamp of the unmappable release point. Send both state changes - // before one pump notification so no frame can observe a held button - // whose pointer is already outside the displayed scene. - if let last = latchedCell { - sendMouse(button, PARDES_MOUSE_RELEASE, last.col, last.row, - modifiers(event.modifierFlags)) - } - latchedCell = nil - pardes_pointer_leave() - fed() - } - - override func mouseDown(with event: NSEvent) { beginClick(PARDES_MOUSE_LEFT, event) } - override func mouseDragged(with event: NSEvent) { continueClick(event) } - override func mouseUp(with event: NSEvent) { endClick(event) } - // Where a two-finger click lands with macOS's own secondary click on, and - // where a three-finger one lands too — hence the finger count in - // Trackpad.button rather than a hardcoded RIGHT here. - override func rightMouseDown(with event: NSEvent) { beginClick(PARDES_MOUSE_RIGHT, event) } - override func rightMouseDragged(with event: NSEvent) { continueClick(event) } - override func rightMouseUp(with event: NSEvent) { endClick(event) } - // Thumb navigation has its own stream so it cannot replace a held - // selection button or inherit a resting trackpad's finger count. - override func otherMouseDown(with event: NSEvent) { - if event.buttonNumber == 2 { beginClick(PARDES_MOUSE_MIDDLE, event); return } - guard event.buttonNumber == 3 || event.buttonNumber == 4, - let at = cell(for: event) else { return } - press(event.buttonNumber == 3 ? PARDES_MOUSE_BACK : PARDES_MOUSE_FORWARD, - at: at, mods: pointerModifiers) - } - override func otherMouseDragged(with event: NSEvent) { - if event.buttonNumber == 2 { continueClick(event) } - } - override func otherMouseUp(with event: NSEvent) { - if event.buttonNumber == 2 { endClick(event); return } - guard event.buttonNumber == 3 || event.buttonNumber == 4, - let at = cell(for: event) else { return } - release(event.buttonNumber == 3 ? PARDES_MOUSE_BACK : PARDES_MOUSE_FORWARD, - at: at, mods: pointerModifiers) - } - - /// A deep press, which is a second gesture layered on the click already in - /// flight. AppKit keeps sending stage-2 events while the finger stays down, - /// so only the transition counts. - /// - /// Whatever button is in flight is released before the look one goes out: - /// a right press arriving while the core holds a left select-drag is - /// acme's 1-3 chord, which is Paste. Releasing first costs a cursor move - /// at the click point — which is what clicking there would have done - /// anyway; a multi-finger press released this way fires its own Exec, - /// which is what the fingers already asked for. - /// - /// Not gated on the press being a LEFT one, which is what stopped this - /// working: on a Force Touch trackpad the deep press is just as likely to - /// have arrived on the right stream, and an in-flight Exec upgraded by - /// pressing harder is precisely the gesture. Already-Look is the only case - /// with nothing to do. - override func pressureChange(with event: NSEvent) { - trace("pressure: stage=\(event.stage) latched=\(String(describing: latchedButton?.rawValue))") - guard pressureStage < 2 else { return } - pressureStage = event.stage - guard event.stage == 2 else { return } - guard let at = latchedCell, let current = latchedButton, - current != Trackpad.forceClickButton else { return } - latchedButton = nil - latchedCell = nil - release(current, at: at, mods: modifiers(event.modifierFlags)) - click(Trackpad.forceClickButton, at: at, mods: modifiers(event.modifierFlags)) - } - - override func mouseMoved(with event: NSEvent) { - guard let at = cell(for: event) else { - leftGrid() - return - } - motion(to: at, mods: modifiers(event.modifierFlags)) - } - - override func mouseExited(with event: NSEvent) { - pointerPoint = nil - pointerMapped = false - leftGrid() - } - - override func scrollWheel(with event: NSEvent) { - guard let at = cell(for: event) else { - leftGrid() - return - } - if event.hasPreciseScrollingDeltas { - // Phases first: a finger back on the pad has to catch a coast before - // its own travel is spent, or the first millimetre of the new swipe - // would be added to the old fling instead of replacing it. - // - // Momentum events carry `phase == .none` and a momentumPhase - // instead, so neither branch here fires for them — they are just - // more travel, and libpardes lets them take the gesture over. That - // is deliberate: AppKit's fling is the one the rest of the system - // uses, and a second fling of our own underneath it would scroll - // everything at double speed. `pardes_scroll_end` exists for the - // devices AppKit does NOT fling for. - if event.phase == .began { scrollBegin() } - // The core scrolls a cell at a time, so libpardes accumulates the - // sub-cell travel and spends it as wheel presses — which is why the - // cell has to travel with the delta. - scroll(rows: -event.scrollingDeltaY / cellHeight, - cols: -event.scrollingDeltaX / cellWidth, - at: at) - switch event.phase { - case .ended: scrollEnd() - // A gesture the system took away should not be thrown. scrollBegin - // is the catching half of the pair — coast stopped, bank and - // velocity cleared — which is exactly what a cancellation means. - case .cancelled: scrollBegin() - default: break - } - } else { - // AppKit's sign is the opposite of the DOM's: positive deltaY means the - // content moved down, which is a scroll back through history. - if event.scrollingDeltaY != 0 { - wheel(event.scrollingDeltaY > 0 ? PARDES_MOUSE_WHEEL_UP : PARDES_MOUSE_WHEEL_DOWN, - at: at, mods: modifiers(event.modifierFlags)) - } - if event.scrollingDeltaX != 0 { - wheel(event.scrollingDeltaX > 0 ? PARDES_MOUSE_WHEEL_LEFT : PARDES_MOUSE_WHEEL_RIGHT, - at: at, mods: modifiers(event.modifierFlags)) - } - } - } - - /// Two fingers twisted on the trackpad are the search-step keys: clockwise - /// walks forward through the matches, counterclockwise back. It is a dial, - /// and n/N is what a dial over a list of hits means. libpardes owns the - /// quantizing and the momentum, exactly as it owns the scroll accumulator. - /// - /// AppKit gives rotation no momentum phase of its own — `momentumPhase` is - /// scroll's alone — so the fling is measured from the release speed on the - /// Zig side rather than handed to us. All this has to get right is telling - /// it where the gesture starts and stops. - override func rotate(with event: NSEvent) { - trace("rotate: degrees=\(event.rotation) phase=\(event.phase.rawValue)") - // A gesture starting drops whatever the last one left banked, so the - // first degree of a new twist cannot inherit a nearly-complete notch — - // and stops a fling still coasting, because a finger back down is how - // a hand catches a dial. - if event.phase == .began { pardes_rotate(0) } - rotate(degrees: CGFloat(event.rotation)) - // .cancelled too: a gesture the system took away should not fling. - if event.phase == .ended || event.phase == .cancelled { rotateEnd() } - } - - /// What the trackpad actually delivered, under PARDES_LOG — the same - /// variable the Zig side gates its logger on (src/macos.zig). - /// - /// This is not scaffolding left behind. Which events a trackpad produces is - /// decided by the hardware and by four different System Settings switches - /// (secondary click, three-finger drag, force click, "look up"), none of - /// which this process can read, and every one of which turns a gesture into - /// a different NSEvent or into none at all. When someone reports that - /// two-finger Exec does nothing, this is the only thing that can answer - /// whether AppKit saw two fingers, one, or no click at all. - private func trace(_ message: @autoclosure () -> String) { - guard PardesView.tracing else { return } - FileHandle.standardError.write(Data(("pardes: " + message() + "\n").utf8)) - } - - private static let tracing = ProcessInfo.processInfo.environment["PARDES_LOG"] != nil - - private func cell(for event: NSEvent) -> GridPoint? { - let point = convert(event.locationInWindow, from: nil) - pointerPoint = point - pointerModifiers = modifiers(event.modifierFlags) - let at = cellAt(point) - pointerMapped = at != nil - if let at { pointerCell = at } - return at - } - - func cellAt(_ point: CGPoint) -> GridPoint? { - // Clamp against the frame the core last rendered, not against our own - // metrics: a window that has been resized but not yet ticked would - // otherwise report a column the core has no cell for. Before the first - // frame there is no grid to point at and the event is meaningless. - let cols = Int(pardes_frame_cols()) - let rows = Int(pardes_frame_rows()) - guard cols > 0, rows > 0 else { return nil } - let sampled: CGPoint - if let scene = lastPresentedScene { - guard let mapped = ScenePostprocessor.sourcePoint(point, size: bounds.size, scene: scene) - else { return nil } - sampled = mapped - } else { - sampled = point - } - sampledBodyPointer = sampled - let row = min(max(Int(sampled.y / cellHeight), 0), rows - 1) - let col = min(max(Int(sampled.x / cellWidth), 0), cols - 1) - return GridPoint(col: UInt16(col), row: UInt16(row)) - } - - // MARK: - files dropped on the grid - - /// A drop is a CLICK followed by `Look`, and that is the whole definition. - /// - /// The core has no notion of a drop and is not being given one: the pointer - /// lands where it landed, which focuses that pane exactly as a left click - /// there would, and then the ordinary `Look` builtin runs in it — so the - /// document opens beside the pane you pointed at rather than beside - /// whichever one happened to be focused. Drop on a tag and you clicked a - /// tag; there is no case to special-case, and nothing here the hand could - /// not have done itself. - override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { - // AppKit reuses this answer for draggingUpdated when that is not - // implemented, so the cursor stays right for the whole drag. - droppedFiles(sender).isEmpty ? [] : .copy - } - - override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { - let paths = droppedFiles(sender) - guard !paths.isEmpty else { return false } - drop(paths, at: cellAt(convert(sender.draggingLocation, from: nil))) - return true - } - - /// The drop, decoded: paths and a cell, nothing AppKit left in it. - /// - /// Split out for the reason every gesture here is — `NSDraggingInfo` is a - /// protocol with a dozen members and no public conformer, so a test that - /// had to build one would be testing its own stub. The decision lives one - /// call below the event, and `drop` in test/macos_e2e.swift drives exactly - /// this. - /// - /// A nil cell is a drop before the first frame, which has no grid to point - /// at: the files still open, they just open where focus already was. - func drop(_ paths: [String], at target: GridPoint?) { - if let target { - press(PARDES_MOUSE_LEFT, at: target) - release(PARDES_MOUSE_LEFT, at: target) - } - // Whole tail, unquoted: executeBuiltinLine takes everything after the - // first word as the argument, so a path with spaces in it needs no - // escaping and would in fact break under any. - for path in paths { - let line = "Look \(path)" - line.withCString { pardes_command($0, line.utf8.count) } - } - fed() - } - - /// File paths on the drag pasteboard, in order. Empty for anything else, - /// which is also how draggingEntered decides whether to accept at all. - private func droppedFiles(_ sender: NSDraggingInfo) -> [String] { - let options: [NSPasteboard.ReadingOptionKey: Any] = [.urlReadingFileURLsOnly: true] - guard let urls = sender.draggingPasteboard.readObjects( - forClasses: [NSURL.self], options: options) as? [URL] - else { return [] } - return urls.map(\.path) - } - - // MARK: - geometry - - override func updateTrackingAreas() { - super.updateTrackingAreas() - for area in trackingAreas { removeTrackingArea(area) } - // .inVisibleRect keeps the area correct across resizes on its own, which - // is why the rect argument can be anything. - addTrackingArea(NSTrackingArea(rect: .zero, - options: [.mouseMoved, .mouseEnteredAndExited, .inVisibleRect, .activeInKeyWindow], - owner: self, - userInfo: nil)) - } - - private enum Pointer: Equatable { case text, link, target } - private var pointer: Pointer = .text - - /// The core's pointer_shape, in this shell's cursor vocabulary: a link - /// is a PDF hyperlink (the hand), a target is a word the core's own - /// Look-hover plumbing validated as a real Look or Exec operand, and - /// anything else is text — the I-beam. - private func pointerShape() -> Pointer { - switch pardes_pointer_shape() { - case 1: return .link - case 2: return .target - default: return .text - } - } - - private func cursorFor(_ shape: Pointer) -> NSCursor { - switch shape { - case .link: return .pointingHand - case .target: return .arrow - case .text: return .iBeam - } - } - - override func resetCursorRects() { - // Every cell in this view is text, including the tags. An arrow over - // plain text is the wrong affordance — but a word the core has - // validated as a Look or Exec target earns it: middle- and - // right-clicking there acts, and the cursor says so before it does. - addCursorRect(bounds, cursor: cursorFor(pointer)) - } - - override func setFrameSize(_ newSize: NSSize) { - super.setFrameSize(newSize) - // AppKit resizes a view many times over one drag and almost all of those - // land inside the same cell. Only a changed grid is news, and the core - // reflows every pty on a resize, so the no-ops are not free. - let grid = gridSize - guard grid.cols != reportedCols || grid.rows != reportedRows else { return } - reportedCols = grid.cols - reportedRows = grid.rows - delegate?.pardesViewDidResize(self) - } - - // Dragging the window between a Retina display and a 1x one changes the - // backing scale without moving a single bound, so setFrameSize above never - // fires. This is the only notification of it. (Ghostty hooks the same one, - // and additionally re-fires from the window's didChangeScreen - // notification, which AppKit does not always pair with it.) - // - // TWO things depend on the scale: the physical cell metrics the core uses - // to place PDF pages, and the cell itself, which is snapped to whole - // DEVICE pixels (see Metrics) and is therefore aligned to the display it - // was measured on. Re-measuring reports the resize on its own, so the - // delegate call is the else-branch and not an extra one. - override func viewDidChangeBackingProperties() { - super.viewDidChangeBackingProperties() - if let scale = window?.backingScaleFactor, scale != metricsScale { - wear(size: fontSize, path: fontPath) - } else { - delegate?.pardesViewDidResize(self) - } - } -} - -// ponytail: no NSTextInputClient, so dead keys and IME composition never reach -// the core — keyDown reads `characters` and that is the whole story. Adopting -// the protocol and routing through interpretKeyEvents is the upgrade when -// someone needs to type Japanese, and it needs the core to be able to render an -// underlined preedit run first. diff --git a/src/macos/Sources/ScenePostprocessor.swift b/src/macos/Sources/ScenePostprocessor.swift deleted file mode 100644 index 41d54e34..00000000 --- a/src/macos/Sources/ScenePostprocessor.swift +++ /dev/null @@ -1,321 +0,0 @@ -// The one GPU owner for panel transitions and persistent scene effects. -// CoreText remains the renderer: while either exists PardesView draws its -// complete ordinary frame into this retained bitmap, then Core Image runs the -// standalone shaders/crt.ci.metal kernels over it. With neither, the view -// bypasses this object entirely. - -import CoreGraphics -import CoreImage -import Darwin -import Metal - -final class ScenePostprocessor { - enum CompositeOutcome { - case presented - case retry - case unavailable - } - - private let colorSpace: CGColorSpace - private let sceneKernel: CIKernel - private let panelClearKernel: CIKernel - private let panelKernel: CIKernel - private let context: CIContext - private var raster: CGContext? - private var previousRaster: CGContext? - private var rasterWidth = 0 - private var rasterHeight = 0 - private var rasterScale: CGFloat = 0 - - init?() { - let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) - ?? CGColorSpaceCreateDeviceRGB() - guard let source = ScenePostprocessor.kernelSource(), - let device = MTLCreateSystemDefaultDevice(), - let made = try? CIKernel.kernels(withMetalString: source), - let sceneKernel = made.first(where: { $0.name == "pardesScene" }), - let panelClearKernel = made.first(where: { $0.name == "pardesPanelClear" }), - let panelKernel = made.first(where: { $0.name == "pardesPanel" }) - else { return nil } - self.colorSpace = colorSpace - self.sceneKernel = sceneKernel - self.panelClearKernel = panelClearKernel - self.panelKernel = panelKernel - self.context = CIContext(mtlDevice: device, options: [ - .workingColorSpace: colorSpace, - .outputColorSpace: colorSpace, - .cacheIntermediates: false, - ]) - } - - private static func kernelSource() -> String? { - var candidates: [URL] = [] - if let resources = Bundle.main.resourceURL { - candidates.append(resources.appendingPathComponent("crt.ci.metal")) - } - // An unbundled e2e executable has no Contents/Resources. Its build - // puts the asset next to the binary, and this explicit candidate keeps - // that dev loop independent of Bundle's treatment of command tools. - if let executable = Bundle.main.executableURL { - candidates.append(executable.deletingLastPathComponent() - .appendingPathComponent("crt.ci.metal")) - } - for url in candidates { - if let source = try? String(contentsOf: url, encoding: .utf8) { - return source - } - } - return nil - } - - /// A body-font-sized, top-left-origin CGContext matching the view's own - /// coordinate system. It is retained across frames; only a resize or a - /// backing-scale move reallocates the pixel storage. - func renderContext(size: CGSize, scale: CGFloat) -> CGContext? { - let scale = max(1, scale) - let width = max(1, Int((size.width * scale).rounded(.up))) - let height = max(1, Int((size.height * scale).rounded(.up))) - if raster == nil || width != rasterWidth || height != rasterHeight || scale != rasterScale { - let info = CGBitmapInfo.byteOrder32Big.rawValue - | CGImageAlphaInfo.premultipliedLast.rawValue - guard let next = CGContext( - data: nil, width: width, height: height, - bitsPerComponent: 8, bytesPerRow: width * 4, - space: colorSpace, bitmapInfo: info) - else { return nil } - next.translateBy(x: 0, y: CGFloat(height)) - next.scaleBy(x: scale, y: -scale) - raster = next - // The old and new snapshots must have identical extents. Lazily - // rebuild the old owner only if an effect actually needs it. - previousRaster = nil - rasterWidth = width - rasterHeight = height - rasterScale = scale - } - return raster - } - - /// A second complete CoreText raster for the frozen old grid. It is - /// intentionally a peer of `raster`, not a collection of per-pane image - /// pointers: deleted PDF/image panes have already released their core - /// bytes, while PardesView's frozen CGImages remain safe to draw here. - func previousRenderContext(size: CGSize, scale: CGFloat) -> CGContext? { - guard renderContext(size: size, scale: scale) != nil else { return nil } - if previousRaster == nil { - let info = CGBitmapInfo.byteOrder32Big.rawValue - | CGImageAlphaInfo.premultipliedLast.rawValue - guard let next = CGContext( - data: nil, width: rasterWidth, height: rasterHeight, - bitsPerComponent: 8, bytesPerRow: rasterWidth * 4, - space: colorSpace, bitmapInfo: info) - else { return nil } - next.translateBy(x: 0, y: CGFloat(rasterHeight)) - next.scaleBy(x: rasterScale, y: -rasterScale) - previousRaster = next - } - return previousRaster - } - - /// Run the one scene kernel and copy its result into the flipped NSView - /// context. Allocation/device failures may be retried briefly. A kernel - /// rejecting its fixed argument layout is permanent for this executable, - /// so the caller can turn the advertised effects back off instead of - /// silently spinning a display clock forever. - func composite( - scene: pardes_scene_s, - tracks: UnsafeBufferPointer, - changedCells: UnsafePointer?, - changedAttachmentRects: [CGRect], - gridSize: (cols: Int, rows: Int), - cellSize: CGSize, - ground: UInt32?, - size: CGSize, - into destination: CGContext - ) -> CompositeOutcome { - guard let raster, let sourceImage = raster.makeImage() else { return .retry } - let extent = CGRect(x: 0, y: 0, width: rasterWidth, height: rasterHeight) - let current = CIImage(cgImage: sourceImage, options: [.colorSpace: colorSpace]) - let old: CIImage - if let previousImage = previousRaster?.makeImage() { - old = CIImage(cgImage: previousImage, options: [.colorSpace: colorSpace]) - } else { - old = current - } - let mask = changeMask( - changedCells, attachmentRects: changedAttachmentRects, - gridSize: gridSize, cellSize: cellSize) ?? - CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 1)) - .cropped(to: CGRect(x: 0, y: 0, width: 1, height: 1)) - var filtered = current - - // Geometric targets are prepared before any presented panel is drawn. - // Horizontal slide/zoom use the theme ground; a vertical opener uses - // the exact old frame inside its fixed clip. Data effects and closing - // tombstones leave the canonical current frame untouched underneath. - let clear = ground.map { encoded in - CIColor( - red: CGFloat((encoded >> 16) & 0xFF) / 255, - green: CGFloat((encoded >> 8) & 0xFF) / 255, - blue: CGFloat(encoded & 0xFF) / 255, - alpha: 1) - } ?? CIColor(red: 0, green: 0, blue: 0, alpha: 0) - for track in tracks { - let content = track.phase == UInt8(PARDES_PANEL_CLOSING) ? track.from : track.to - guard let next = panelClearKernel.apply( - extent: extent, - roiCallback: { _, _ in extent }, - arguments: [ - filtered, old, - pixelBox(content, cellSize: cellSize), clear, - Float(track.effect), Float(track.phase), - ]) - else { return .unavailable } - filtered = next - } - - // libpardes orders moving, opening, then closing tombstones. Each pass - // samples immutable old/new rasters and composes over the prior pass, - // so a deleted pane can safely outlive its core Pane allocation. - let pixelCell = CIVector( - x: cellSize.width * rasterScale, - y: cellSize.height * rasterScale) - for track in tracks { - let content = track.phase == UInt8(PARDES_PANEL_CLOSING) ? track.from : track.to - guard let next = panelKernel.apply( - extent: extent, - roiCallback: { _, _ in extent }, - arguments: [ - current, old, mask, filtered, - pixelBox(content, cellSize: cellSize), - pixelBox(track.from, cellSize: cellSize), - pixelBox(track.to, cellSize: cellSize), - Float(track.effect), Float(track.phase), Float(track.frame), - CIVector( - x: CGFloat(track.serial & 0xFFFF), - y: CGFloat(track.serial >> 16)), - pixelCell, - CIVector( - x: 0, - y: extent.height - CGFloat(gridSize.rows) * pixelCell.y), - ]) - else { return .unavailable } - filtered = next - } - - if scene.flags != 0 { - let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 - // SDL samples the scene with CLAMP_TO_EDGE. A finite Core Image - // instead supplies transparent black outside its extent, which - // would tear dark seams at the window edge. - // Clamp the input only; the kernel still emits true black before - // sampling when a destination lies outside the CRT tube. - let sceneInput = filtered.clampedToExtent() - guard let next = sceneKernel.apply( - extent: extent, - roiCallback: { _, _ in extent }, - arguments: [ - sceneInput, scene.time_seconds, Float(scene.frame), - crt, - CIVector(x: extent.width, y: extent.height), - CIVector(x: extent.minX, y: extent.minY), - ]) - else { return .unavailable } - filtered = next - } - - guard let presented = context.createCGImage(filtered, from: extent) else { return .retry } - - destination.clear(CGRect(origin: .zero, size: size)) - destination.saveGState() - destination.translateBy(x: 0, y: size.height) - destination.scaleBy(x: 1, y: -1) - destination.interpolationQuality = .none - destination.draw(presented, in: CGRect(origin: .zero, size: size)) - destination.restoreGState() - return .presented - } - - /// Byte-per-cell mask from the core. Zig expands true to 255 so the image - /// is a literal normalized 0/1 texture; sampling cell centres below keeps - /// adjacent values from interpolating at pane/cell boundaries. - private func changeMask( - _ cells: UnsafePointer?, - attachmentRects: [CGRect], - gridSize: (cols: Int, rows: Int), - cellSize: CGSize - ) -> CIImage? { - let count = gridSize.cols * gridSize.rows - guard count > 0, let cells, cellSize.width > 0, cellSize.height > 0 else { return nil } - var bytes = Array(UnsafeBufferPointer(start: cells, count: count)) - for rect in attachmentRects where !rect.isNull && !rect.isEmpty { - let x0 = max(0, Int((rect.minX / cellSize.width).rounded(.down))) - let x1 = min(gridSize.cols, Int((rect.maxX / cellSize.width).rounded(.up))) - let y0 = max(0, Int((rect.minY / cellSize.height).rounded(.down))) - let y1 = min(gridSize.rows, Int((rect.maxY / cellSize.height).rounded(.up))) - guard x0 < x1, y0 < y1 else { continue } - for row in y0.. CIVector { - let cellW = cellSize.width * rasterScale - let cellH = cellSize.height * rasterScale - let x = CGFloat(box.x) * cellW - let w = CGFloat(box.w) * cellW - let h = CGFloat(box.h) * cellH - let y = CGFloat(rasterHeight) - (CGFloat(box.y) + CGFloat(box.h)) * cellH - return CIVector(x: x, y: y, z: w, w: h) - } - - /// The scene kernel is a destination-to-source mapping. Pointer input must - /// apply that same mapping before the grid and its panel tracks see a cell, - /// otherwise a visible word under the barrel is not the word Look gets. - static func sourcePoint( - _ point: CGPoint, - size: CGSize, - scene: pardes_scene_s - ) -> CGPoint? { - guard size.width > 0, size.height > 0 else { return nil } - if scene.flags == 0 { return point } - - var uvX = Float(point.x / size.width) - var uvY = 1 - Float(point.y / size.height) // Core Image is bottom-up - var ccX = uvX * 2 - 1 - var ccY = uvY * 2 - 1 - let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 - let radius2 = ccX * ccX + ccY * ccY - let barrel = 1 + 0.016 * radius2 * crt - ccX *= barrel - ccY *= barrel - uvX = ccX * 0.5 + 0.5 - uvY = ccY * 0.5 + 0.5 - // The CRT's black tube has no cell under it. - if crt > 0.5 && min(min(uvX, uvY), min(1 - uvX, 1 - uvY)) <= 0 { return nil } - uvX = min(max(uvX, 0), max(0, 1 - 1 / Float(size.width))) - uvY = min(max(uvY, 0), max(0, 1 - 1 / Float(size.height))) - return CGPoint( - x: CGFloat(uvX) * size.width, - y: CGFloat(1 - uvY) * size.height) - } - -} diff --git a/src/macos/Sources/main.swift b/src/macos/Sources/main.swift deleted file mode 100644 index 6cb2646e..00000000 --- a/src/macos/Sources/main.swift +++ /dev/null @@ -1,16 +0,0 @@ -import AppKit - -// Ghostty's ordering lesson: whatever must exist before AppKit boots goes above -// app.run(), because after that call the runloop owns this thread forever. -// pardes has nothing in that class — the core cannot come up until there is a -// window to measure, so pardes_init waits for applicationDidFinishLaunching. - -let app = NSApplication.shared -app.setActivationPolicy(.regular) - -// NSApplication does not own its delegate. This is a global, so it lives as -// long as the process does; the same line inside a function would not. -let delegate = AppDelegate() -app.delegate = delegate - -app.run() diff --git a/src/macos/icon.png b/src/macos/icon.png deleted file mode 100644 index 9889c348..00000000 Binary files a/src/macos/icon.png and /dev/null differ diff --git a/src/macos/icon.swift b/src/macos/icon.swift deleted file mode 100644 index 2f45220f..00000000 --- a/src/macos/icon.swift +++ /dev/null @@ -1,194 +0,0 @@ -// Cuts pardes.app's icon out of a committed drawing and hands the result to -// iconutil. -// -// The mark is still GLENDA, the Plan 9 rabbit — pardes is an acme, and acme is -// Plan 9's, so the bunny is the lineage stated in one shape. What changed is -// where she comes from: she used to be drawn here out of the terminal's own -// palette, four ellipses and a tag bar, and she is now `icon.png` beside this -// file. A drawing is not derivable from a palette, so the old argument for -// generating her ("a checked-in .icns stops matching the app the first time a -// colour moves") no longer applies to the artwork — but it still applies to -// the ICNS, which is why this file did not become a committed binary. What is -// committed is the source picture, in one format, reviewable as an image; what -// is generated is the ten-size container macOS actually reads. -// -// So the work here is no longer drawing. It is the part a designer's PNG never -// has: Apple's icon grid, the rounded-square mask, and ten exact sizes. -// -// build.zig compiles this file alone into a cached binary and runs it with the -// source PNG as argv[1] and the bundle's Resources directory as argv[2]; -// Info.plist's CFBundleIconFile names the pardes.icns that comes out. Compiled -// alone is also what makes top-level code legal here: one file, one module. -// -// Byte-identical output for byte-identical input is a requirement, not a -// nicety — an icns that churns on every build is a bundle that churns on every -// build, and Launch Services notices. Hence a pinned sRGB colour space, -// integer geometry, and nothing read from the clock or the environment. - -import CoreGraphics -import Foundation -import ImageIO -import UniformTypeIdentifiers - -/// Every failure path lands here. A build that ships the generic blank-page -/// icon looks like an app nobody finished, so half-drawn is worse than absent -/// and build.zig has this exit code waiting: a bundle whose icon did not draw -/// should not have built. -func die(_ message: String) -> Never { - fputs("icon.swift: \(message)\n", stderr) - exit(1) -} - -// Apple's icon grid rather than the whole square: the artwork is a rounded -// square floating in a transparent margin, 824 of 1024 with a 185.4 corner -// radius in the template — 80.47% of the canvas, and 22.37% of the SQUARE, not -// of the canvas, which would over-round it by a quarter. Filling the canvas -// edge to edge is the loudest tell that an app was not built on a Mac. -let squareFraction: CGFloat = 0.8047 -let cornerFraction: CGFloat = 0.2237 - -/// Where the crop comes off when the source is not square. -/// -/// The drawing is 1204x1306 — taller than wide — so filling a square throws -/// away 8% of its height, and WHICH 8% is the whole decision. Anchoring the -/// top keeps the sun, which is the only warm thing in the picture and sits in -/// the top-right corner, and spends the loss on the bottom band of grass, -/// which is texture and repeats. Anchoring the centre would clip the sun's -/// rays to buy back grass, which is the trade backwards. 0 is top, 1 is -/// bottom; a square source ignores this entirely. -let cropAnchor: CGFloat = 0 - -/// sRGB in the bitmap, so the paper white in the drawing is the paper white in -/// the icon rather than whatever DeviceRGB would make of it. -func sRGB() -> CGColorSpace { - guard let space = CGColorSpace(name: CGColorSpace.sRGB) else { die("sRGB colour space unavailable") } - return space -} - -func loadSource(_ url: URL) -> CGImage { - guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { - die("cannot read \(url.path)") - } - guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { - die("\(url.lastPathComponent) holds no decodable image") - } - return image -} - -func renderIcon(_ art: CGImage, pixels: Int) -> CGImage { - guard - let ctx = CGContext( - data: nil, width: pixels, height: pixels, - bitsPerComponent: 8, bytesPerRow: 0, space: sRGB(), - bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) - else { die("CGContext \(pixels)x\(pixels) failed") } - - // Round the MARGIN and derive the square from it. Rounding the square - // instead leaves an odd remainder to split, and at 16 pixels the artwork - // lands a pixel off centre. At 1024 this is Apple's 100/824/100 exactly. - let canvas = CGFloat(pixels) - let inset = (canvas * (1 - squareFraction) / 2).rounded() - let side = canvas - 2 * inset - let body = CGRect(x: inset, y: inset, width: side, height: side) - let corner = side * cornerFraction - - ctx.addPath(CGPath(roundedRect: body, cornerWidth: corner, cornerHeight: corner, transform: nil)) - ctx.clip() - - // Aspect FILL, not fit. Fitting would letterbox the rounded square with a - // flat band beside textured paper, and the seam between the two is visible - // at every size the band is wide enough to see. Filling overflows the clip - // instead, and the clip is already exact. - let artWidth = CGFloat(art.width) - let artHeight = CGFloat(art.height) - guard artWidth > 0, artHeight > 0 else { die("source image is empty") } - let scale = max(side / artWidth, side / artHeight) - let drawWidth = artWidth * scale - let drawHeight = artHeight * scale - - // CoreGraphics is bottom-left origin, so `cropAnchor` 0 (the TOP of the - // picture) means the drawing's top edge meets the body's top edge and the - // overflow hangs off the bottom, into the clip. - let overflowY = drawHeight - side - let overflowX = drawWidth - side - ctx.interpolationQuality = .high - ctx.draw( - art, - in: CGRect( - x: body.minX - overflowX / 2, - y: body.maxY - drawHeight + overflowY * cropAnchor, - width: drawWidth, height: drawHeight)) - - guard let image = ctx.makeImage() else { die("CGContext.makeImage failed at \(pixels)") } - return image -} - -func writePNG(_ image: CGImage, to url: URL) { - guard - let sink = CGImageDestinationCreateWithURL( - url as CFURL, UTType.png.identifier as CFString, 1, nil) - else { die("cannot open \(url.path) for writing") } - CGImageDestinationAddImage(sink, image, nil) - guard CGImageDestinationFinalize(sink) else { die("encoding \(url.lastPathComponent) failed") } -} - -// The ten names iconutil demands, spelled out rather than derived: the set is -// fixed by the tool, and a loop that generated them would be a loop to read -// before believing the list. 32, 256 and 512 appear twice under two names and -// are simply drawn twice — a third of a megapixel, against the clarity of not -// caching anything in a build tool. -let variants: [(name: String, pixels: Int)] = [ - ("icon_16x16.png", 16), - ("icon_16x16@2x.png", 32), - ("icon_32x32.png", 32), - ("icon_32x32@2x.png", 64), - ("icon_128x128.png", 128), - ("icon_128x128@2x.png", 256), - ("icon_256x256.png", 256), - ("icon_256x256@2x.png", 512), - ("icon_512x512.png", 512), - ("icon_512x512@2x.png", 1024), -] - -let arguments = CommandLine.arguments -guard arguments.count == 3 else { - die("usage: \(URL(fileURLWithPath: arguments.first ?? "icon").lastPathComponent) ") -} - -let files = FileManager.default -let art = loadSource(URL(fileURLWithPath: arguments[1])) -let outputDir = URL(fileURLWithPath: arguments[2], isDirectory: true) -let output = outputDir.appendingPathComponent("pardes.icns") - -// A fixed scratch path, cleared before use rather than a unique one: a run that -// died half way leaves a partial iconset behind, and iconutil would happily -// fold the stale sizes into the next icns without a word. -let scratch = files.temporaryDirectory.appendingPathComponent("pardes-icon", isDirectory: true) -let iconset = scratch.appendingPathComponent("pardes.iconset", isDirectory: true) - -try? files.removeItem(at: scratch) -do { - try files.createDirectory(at: iconset, withIntermediateDirectories: true) - try files.createDirectory(at: outputDir, withIntermediateDirectories: true) -} catch { - die("cannot create \(iconset.path): \(error.localizedDescription)") -} - -for variant in variants { - writePNG(renderIcon(art, pixels: variant.pixels), to: iconset.appendingPathComponent(variant.name)) -} - -let iconutil = Process() -iconutil.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil") -iconutil.arguments = ["-c", "icns", "-o", output.path, iconset.path] -do { - try iconutil.run() -} catch { - die("cannot run /usr/bin/iconutil: \(error.localizedDescription)") -} -iconutil.waitUntilExit() -guard iconutil.terminationStatus == 0 else { - die("iconutil exited \(iconutil.terminationStatus) over \(iconset.path)") -} - -try? files.removeItem(at: scratch) diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index be85a497..0a1cfc23 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -66,7 +66,7 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { // interpreter is not: refused, and the running shell kept. const bin = pane.shell orelse p.shellBin(); var why: [320]u8 = undefined; - if (pardes.tape.value(.shell, @import("../host_io.zig").Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused| + if (pardes.tape.value(.shell, @import("dev").host_io.Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused| return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused[0..@min(refused.len, 300)]}) catch &p.fs.ename); // cut to ename's 320 }; if (verb(p, id, line, apply)) |why| return tree.failText(req.tag, E.INVAL, why); diff --git a/src/pardes.zig b/src/pardes.zig index 061c0efc..c32ebb59 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4,7 +4,7 @@ pub const layout = @import("layout.zig"); /// `nextWake` answers in whole frames of it. pub const frame_ms: u32 = 16; pub const frame_ns: u64 = frame_ms * std.time.ns_per_ms; -pub const glide = @import("glide.zig"); +pub const glide = @import("dev").glide; pub const FrameStats = @import("FrameStats.zig"); pub const modal = @import("modal.zig"); pub const look = @import("look.zig"); @@ -91,11 +91,8 @@ pub const lsp = @import("lsp/lsp.zig"); /// What the runtime's files name of the core beside the above (9p_io). pub const ctl = @import("ninep/ctl.zig"); pub const edit_cmd = @import("edit_cmd.zig"); -/// The frontends, named by the product's root (runtime/main.zig). -pub const tui = @import("tui/tui.zig"); -pub const gui = @import("gui/gui.zig"); -pub const host_io = @import("host_io.zig"); -pub const file_watch = @import("file_watch.zig"); +pub const host_io = @import("dev").host_io; +pub const file_watch = @import("dev").file_watch; pub const Host = host_io.Host; pub const frameMark = tracy.frameMark; @@ -119,7 +116,7 @@ const Loc = Jump.Loc; pub const can_attach = platform == .tui or platform == .gui; -pub const fonts = if (font_picker) @import("fonts.zig") else struct {}; +pub const fonts = if (font_picker) @import("dev").fonts else struct {}; pub const Pane = panes.Pane; const Text = panes.Text; @@ -399,7 +396,6 @@ test { _ = @import("Core.zig"); _ = @import("Plumb.zig"); _ = @import("lsp/Ask.zig"); - _ = @import("lsp/lsp_client.zig"); _ = @import("Jump.zig"); _ = @import("keys.zig"); _ = @import("Effect.zig"); @@ -427,7 +423,6 @@ test { _ = @import("Pipe.zig"); _ = @import("colors.zig"); _ = @import("surface.zig"); - _ = @import("glide.zig"); _ = @import("body_layer.zig"); _ = @import("draw.zig"); _ = @import("dump.zig"); // its tests ran nowhere before @@ -443,11 +438,8 @@ test { _ = @import("Handover.zig"); _ = @import("walk.zig"); _ = @import("views.zig"); - // The frontends', which main.zig's test block collected: a shell's - // build (shell-test); the core without a terminal never compiled them. - if (comptime @import("term_options").terminal) { - if (comptime platform == .tui) _ = @import("tui/tui.zig"); - if (comptime platform == .gui) _ = @import("gui/gui.zig"); - _ = @import("vaxis_input.zig"); - } + // A window's build links the window's C (font.c over FreeType and + // HarfBuzz) into each of its programs, and their allocator (ui_malloc + // and the rest) is gui.zig's. + if (comptime @import("term_options").terminal and platform == .gui) _ = @import("dev").gui; } diff --git a/src/tape.zig b/src/tape.zig index 9337ff9f..da9de05b 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -20,7 +20,7 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const walk = @import("walk.zig"); -const host_io = @import("host_io.zig"); +const host_io = @import("dev").host_io; const Pardes = pardes.Pardes; const VTable = pardes.Host.VTable; const libc = std.c; diff --git a/src/tui/tui.zig b/src/tui/tui.zig deleted file mode 100644 index cb709ff1..00000000 --- a/src/tui/tui.zig +++ /dev/null @@ -1,3386 +0,0 @@ -const filesystem = @import("../fs.zig"); -const std = @import("std"); -const builtin = @import("builtin"); -const posix = std.posix; -/// libc: termios, signals, kitty shm segments and the fds a terminal hands over. -const libc = std.c; -const vaxis = @import("vaxis"); -const pardes = @import("../pardes.zig"); -const JumpTrail = @import("../jump_trail.zig"); -const Art = @import("../Art.zig"); -const vaxis_input = @import("../vaxis_input.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("runtime").ninep_io; -const daemon = @import("runtime").daemon; -const host_io = @import("../host_io.zig"); -const upgrade = @import("runtime").upgrade; -const replica = @import("../replica.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 the terminal's input reader keeps: its graphemes, the frame it -/// waits on the answer to, and the shm probe. -const Feed = struct { - 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), -}; - -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 {}; -} - -/// What the loop's queue carries: a terminal's input, a pane's output, a -/// worker's answer, a wake. -const Msg = 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, - /// 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, - /// A kind's job done on a worker (host_io.KindJob). - kind_job: *host_io.KindJob, - 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, -}; -const Loop = vaxis.Loop(Msg); - -fn startInput(loop: *Loop, sc: *Screen) !void { - 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)}); - }; - loop.postEvent(.quit) catch {}; -} - -fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void { - try loop.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(loop, vx, &feed.cache, Msg, 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; -} - -/// What a test of a terminal's input needs: vaxis (its capabilities, its -/// parser's allocator), the loop's queue and a feed, set up in place (vaxis -/// keeps the environment's address) and torn down in the order vaxis needs. -const TestInput = struct { - env: std.process.Environ.Map, - vx: vaxis.Vaxis, - out: std.Io.Writer.Allocating, - loop: Loop, - feed: Feed, - - fn init(t: *TestInput) !void { - const gpa = std.testing.allocator; - t.env = try std.testing.environ.createMap(gpa); - errdefer t.env.deinit(); - t.vx = try vaxis.init(std.testing.io, gpa, &t.env, .{ .system_clipboard_allocator = gpa }); - t.out = .init(gpa); - t.loop = .init(std.testing.io, undefined, &t.vx); - t.feed = .{}; - } - - fn deinit(t: *TestInput) void { - t.vx.deinit(std.testing.allocator, &t.out.writer); - t.out.deinit(); - t.env.deinit(); - } -}; - -/// A terminal that hands over `parts`, a read each (an empty one passed -/// over), and says more follows (within `gap_ms`) while some are left. -const TestReader = struct { - parts: []const []const u8, - next: usize = 0, - gap_ms: u32 = 0, - asked: bool = false, - - fn getWinsize(_: *TestReader) !vaxis.Winsize { - return .{ .rows = 24, .cols = 80, .x_pixel = 0, .y_pixel = 0 }; - } - - pub fn inputFollows(r: *TestReader, ms: u32) bool { - r.asked = true; - return r.next < r.parts.len and r.gap_ms <= ms; - } - - fn read(r: *TestReader, buf: []u8) !usize { - while (r.next < r.parts.len) { - const part = r.parts[r.next]; - r.next += 1; - if (part.len == 0) continue; - @memcpy(buf[0..part.len], part); - return part.len; - } - return 0; - } -}; - -const PipeTasks = selection_pipe.Tasks; - -const Pty = struct { - file: std.Io.File, - pid: posix.pid_t, - reader: std.Io.Future(error{OutOfMemory}!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 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 (one cell row): its `src` into its -/// `at`, inside that 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.Placement, - screen_cols: u16, - screen_rows: u16, - screen_pixel_w: u16, - screen_pixel_h: u16, -) ?KittyPlacement { - const g: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at 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.dst.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.dst.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 }, - }, - }; -} - -/// A PDF's page over its body: declared to kitty by its columns where it -/// is as wide as the body (fit to width), else by its rows, and its source -/// cut so the declared cells never run past its clipped bottom. -fn kittyPlacement( - place: pardes.Placement, - screen_cols: u16, - screen_rows: u16, - screen_pixel_w: u16, - screen_pixel_h: u16, -) ?KittyPlacement { - const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); - const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); - const geometry: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null }; - const fit: enum { width, height } = if (geometry.dst.w >= @as(u32, place.dst.w) * cell_w) .width else .height; - - 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 (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, - ); - }, - } - 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.dst.w or cell_y >= place.dst.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.dst.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.dst.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 (fit) { - .width => .{ .cols = std.math.cast(u16, declared_cols) orelse return null }, - .height => .{ .rows = std.math.cast(u16, declared_rows) orelse return null }, - }, - }, - }; -} - -fn kittyImageRepresentable(place: pardes.Placement) bool { - return place.raster.w > 0 and place.raster.h > 0 and - place.raster.w <= std.math.maxInt(u16) and place.raster.h <= std.math.maxInt(u16); -} - -fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool { - for (surface.placements.items) |place| { - if (place.art.glyph or !kittyImageRepresentable(place)) continue; - if (place.key == key) return true; - } - return false; -} - -/// 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, detached 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 }, detached }; - -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) }; - 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)), - .detached => {}, - } - 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 (`runClient`), drawn here. -const Client = 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: *Client, 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 runClient(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; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.Term.start(allocs.image); - pardes.Kind.heap = allocs.addon; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.Term.stop(); - pardes.syntax.stop(); - } - var o = opts; - o.image_allocator = allocs.image; - var joined: replica.Joined = undefined; - var r = replica.join(gpa, &joined, path, session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - - 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) }; - defer screen.kitty.deinit(); - try screen.enter(try vaxis.Tty.init(io, &tty_buf)); - defer screen.leave(); - defer screen.glide.deinit(gpa); - defer screen.art.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 client_link: Client = .{ .link = .{ .r = r, .fd = joined.fd } }; - const link = &client_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, - .own = joined.view, - .screen = &screen, - .client = &client_link, - }; - - pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; - defer pardes.Kind.drawer = null; - 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) { - sh.core = r.core(); - sh.own = joined.view; - link.reset(r, &joined); - 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) { - client_link.draw(&sh); - } else if (sh.moving() and r.core().surface.cells.len != 0) { - // The tty's own motions (its glide, a jump's trail): the last - // frame again, moved on, as the session's terminal draws them - // (`ownFrame`), not rendered again. One the terminal's answer - // holds is skipped (the next tick's moves on): nothing of it - // is written in the core, as `Client.draw` puts it back. - const skipped = r.core().present_skipped; - Shell.present(&sh, &r.core().surface); - r.core().present_skipped = skipped; - link.again += 1; - } - // Idle, its frame drawn: the next key needs no copy taken. - if (loop.tryEvent() catch null) |ev| sh.held = ev else r.ready(); - // The session's own wait: an input drawn at once, the session's - // units and deltas a frame a tick at most, the tty's own motions - // on its grid of ticks; predictions judged a frame at a time. - var wait: u32 = if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) @intCast(pardes.frame_ns / std.time.ns_per_ms) else 0; - if (link.quietCheck()) |ms| wait = if (wait == 0) ms else @min(wait, ms); - Shell.waitInput(&sh, wait); - r.settle(); - // A rollback since it drew (`toConfirmed`): its frame is drawn - // again, never moved on from cells the copy put back. - if (r.moved) { - r.moved = false; - link.dirty = true; - } - 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; - 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, .blob => |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. - r = replica.join(gpa, &joined, path, session, o, have, &why, r) orelse { - screen.leave(); - Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - }; - } -} - -/// 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), its stub `daemon.stub`. One a -/// process: a second terminal on a session is a replica client of it. -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, - feed: Feed = .{}, - thread: ?std.Io.Future(void) = null, - /// The kitty images it holds, by placement key. - kitty: std.AutoHashMap(u64, vaxis.Image), - /// The glyph art of the pictures it shows so (all of them without - /// kitty graphics). - art: Art = .{}, - caps_pending: bool = true, - /// Its size as last taken (`Shell.resized`). - size: ?vaxis.Winsize = null, - /// The view's glide, the GUI's motion drawn at whole rows (anim 12). - glide: pardes.glide.Glide = .{}, - /// The cursor's jump trail (JumpTrail), on the tty's own clock. - trail: JumpTrail = .{}, - - /// `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) { - Killed.arm(sc.tty.fd.handle, sc.tty.termios); - // What a panic puts back (vaxis.recover). - vaxis.tty.global_tty = sc.tty; - } - sc.feed = .{}; - sc.caps_pending = true; - sc.size = null; - sc.on = true; - } - - fn leave(sc: *Screen) void { - if (!sc.on) return; - sc.on = false; - Killed.disarm(); - 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) vaxis.tty.global_tty = null; - sc.tty.deinit(); // restore cooked termios LAST, after vx flushed its resets - } - - /// Its terminal hung up, or the stub that waits on it is gone. - fn hungUp(sc: *const Screen) bool { - // vaxis's test tty off Linux has no fd. - if (comptime !@hasField(@TypeOf(sc.tty), "fd")) return false; - const stub = daemon.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); - } -}; - -/// SIGTERM or SIGHUP: the 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 fd: posix.fd_t = -1; - var cooked: posix.termios = undefined; - const reset = "\x1b[= 0) { - _ = std.c.write(fd, reset, reset.len); - _ = std.c.tcsetattr(fd, .FLUSH, &cooked); - } - // 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.tree_sitter_allocator = allocs.tree_sitter; - options.frame_allocator = allocs.frame; - - host_io.startWorkers(allocs); - defer host_io.stopWorkers(); - options.addons = pardes.Addon.scan(); - - 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.screen = 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); - defer screen.art.deinit(gpa); - 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.list[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); - sh.job_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); - 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), - .kind_job => |j| j.drop(), - .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; - pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; - defer pardes.Kind.drawer = null; - // An upgraded session's terminals, its own again. - if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec); - // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). - sh.setAttended(!sh.detached()); - 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); - - 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); - // Detached, the unit is its clients' frame: its output is paced to - // it as a terminal's frame paces it (waitInput), a unit a frame, not - // a unit and a delta for every read of a flood. - if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - 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: { - const nc = host_io.restoreCore(gpa, core, rp, &sh.peers, sh.inotify_fd, &sh.watches) orelse 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 (0..pardes.MAX_PANES) |pane| Shell.closePty(&sh, @intCast(pane)); - // One view, the terminal's (host_io.restoreCore). - const live = screen; - stopInput(io, &live.thread); - sh.own = 0; - if (live.on) startInput(loop, live) catch {}; - if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); - nc.view().frontend.native_images = live.on and live.vx.caps.kitty_graphics; - nc.unattended = !live.on; - sh.peers.detached = !live.on; - if (fs) |f| f.reset(nc); - core.deinit(); - core = nc; - sh.core = nc; - if (live.on) core.update(.{ .resize = terminalSize(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(u64, 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(); -} - -/// 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.tellStub(a.stub, "r{s}", .{"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, - /// The terminal (none in tests), and the view it shows: a second - /// terminal on the session is a replica client (`pardes --attach`). - screen: ?*Screen = null, - own: 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: host_io.Adoptions = .{}, - 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(void) = null, - lsp_task: ?host_io.Lsp.Task = null, - pipe_tasks: PipeTasks = .{}, - job_tasks: PipeTasks = .{}, - threads_ok: bool = false, - check_files: bool = false, - 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: ?Msg = null, - /// This process a replica client of a session elsewhere (`runClient`): - /// its inputs go to the replica, never straight to the core. - client: ?*Client = null, - - /// 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.client 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 { - return s.screen != null; - } - - /// 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.detached = !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 = ownFrame, - }; - - 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, - .start = host_io.startDetached, - .lsp = lsp, - .pipe = pipe, - .search = search, - .job = job, - }; - - 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.clock.now_ns; - } - return s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - } - - /// The terminal, while its view is live (null in tests, and while a - /// replica client's is: its input the last). - fn term(s: *const Shell) ?*Screen { - return if (s.core.live == s.own) s.screen else null; - } - - /// No terminal of its own (a test's, with none at all, is not detached). - fn detached(s: *const Shell) bool { - const screen = s.screen orelse return false; - return !screen.on; - } - - /// Drawn only while a terminal shows it. - fn watched(ctx: ?*anyopaque) bool { - return !of(ctx).detached(); - } - - /// 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.live)) return; - if (s.detached()) return s.core.reportFailure(s.core.view().active, "Detach: detached already (no terminal of its own)"); - if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)"); - s.leaveTerminal(); - } - - fn leaveTerminal(s: *Shell) void { - const screen = s.screen orelse return; - stopInput(s.io, &screen.thread); - screen.leave(); - s.core.view().frontend.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); - } - daemon.tellStubDetached(); - daemon.setState(true); - } - - /// `pardes --attach`'s terminal, for a detached session: its own again, - /// entered as the first one was, sized, asked what it can do, and drawn - /// whole. One attached already takes no other (the daemon makes a second - /// a replica client). - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { - const screen = s.screen orelse { - _ = libc.close(fd); - return refuse(stub, "that session has no terminal of its own to attach to"); - }; - if (screen.on) { - _ = libc.close(fd); - return refuse(stub, "that session has a terminal: join it as a client, `pardes --attach=:`"); - } - const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { - _ = libc.close(fd); - daemon.setState(true); - return refuse(stub, "that terminal would not go raw"); - }; - screen.enter(tty) catch { - daemon.setState(true); - return refuse(stub, "that terminal would not take the screen"); - }; - daemon.stub = stub; - s.setAttended(true); - startInput(s.loop, screen) catch {}; - screen.vx.queryTerminalSend(screen.tty.writer()) catch {}; - s.core.needs_frame = true; - daemon.setState(false); - } - - /// 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.tellStub(stub, "r{s}", .{why}); - } - - fn adopt(ctx: ?*anyopaque, pane: u8) void { - const s = of(ctx); - s.adoptions.ask(s.core, pane); - } - - /// A client's own build is not the session's to say (its core's host - /// is the session's, through the tape). - fn newerBuild(ctx: ?*anyopaque) bool { - return of(ctx).client == null and upgrade.newer(); - } - - fn upgradeAsked(ctx: ?*anyopaque, 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 {}; - if (s.screen) |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); - if (s.screen) |sc| if (sc.on) rec.addTty(.{ - .view = s.own, - .fd = sc.tty.fd.handle, - .stub = daemon.stub, - .primary = true, - .termios = sc.tty.termios, - }); - var popped = false; - var at_buf: [1024:0]u8 = undefined; - const failed: []const u8 = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse failed: { - // What this process put in its terminals that the next puts in - // again: its images, and its keyboard mode, a stack. - if (s.screen) |sc| if (sc.on) { - clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); - if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[= 0) daemon.tellStub(t.stub, "d{s}", .{daemon.name()}); - } - if (rec.fresh) return; - for (0..pardes.views.max) |k| if (k != s.own and pardes.views.isOpen(core, @intCast(k)) and !pardes.views.isAway(core, @intCast(k))) core.closeView(@intCast(k)); - } - - 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 (pardes.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; - // The tty's own motions (its glide, a jump's trail) wake it a frame at - // a time while they move: on a virtual clock a millisecond's wait - // moves it a frame (waitOnce), on the real one the pace below sets it. - if (s.moving()) wait = 1; - // Detached, nobody's key dismisses a message: they go on the clock - // (the pump's, after this wait), which wakes it. - if (s.detached()) { - 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.moving(); - var tick: u64 = 0; - if (paced) { - const period = pardes.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). - // Detached, its clients' echo is the frame's after an input: what a - // flood says after that goes a unit a frame (their own echo is - // predicted, src/echo.zig), not a unit and a delta a read for a second. - const echo_ns: u64 = if (s.detached()) pardes.frame_ns else std.time.ns_per_s; - 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 < echo_ns) break; - const due = s.drawn_ns + pardes.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 the tty's own - // motions move (the glide), as the real one would. - s.wake_to = s.core.nextWake() orelse if (s.moving()) s.core.clock.now_ns + pardes.frame_ns else 0; - requestWake(s.io, wait); - } - pardes.turn.rest(); - const got = s.loop.nextEvent() catch { - pardes.turn.wake(); - if (s.client) |c| c.link.quit = true; - 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: ?Msg = 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: Msg) 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: Msg) 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; - // The terminal's input goes into its view. - switch (event) { - .key_press, .mouse, .paste, .paste_start, .paste_end, .winsize, .focus_in, .focus_out, .quit => { - if (s.local() and s.client == null) core.toView(s.own); - }, - else => {}, - } - switch (event) { - .nop => {}, - .winched => s.winched(), - // The terminal hung up (its stub passes the hangup on) or its - // stub died (a forked session's death signal): its input has - // ended. - .hangup => if (s.screen) |sc| if (sc.on and sc.hungUp()) { - if (s.apply(.quit)) return true; - }, - .wake => if (s.test_clock) |*virtual| { - virtual.* = @max(virtual.*, s.wake_to); - }, - .quit => { - if (s.client) |c| { - c.link.quit = true; - 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.detached()) s.leaveTerminal(); - return true; - } - core.quit = true; - return true; - }, - .attach => |a| s.attachTerminal(a.tty, a.stub, null), - .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), - .replica => |j| { - s.peers.handed(j.fd, j.view); - s.input_seen = true; - }, - .replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) { - s.input_seen = true; - }, - .said => |said| if (s.client) |c| { - // The session's units and deltas are a client's output - // (waitInput paces it): a terminal's delta, or the unit - // that answers its own input, is its echo, drawn at once. - s.output_seen = true; - const echo = switch (said) { - .screen => true, - .unit => |b| if (replica.parseUnit(b)) |u| u.origin == c.link.r.id else false, - else => false, - }; - if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - c.link.take(said); - if (said == .refused) return true; - } else switch (said) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), - .checked => {}, - }, - .link_gone => if (s.client) |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.detached()) s.resized(s.screen, ws), - .pty_read => |pr| { - tookRead(s.io, pr.id); - s.output_seen = true; - if (pr.id == core.view().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 = vaxis_input.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| if (mouseEvent(m)) |ev| s.feed(ev), - .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.view().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); - }, - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(core); - // A client's draw done: its frame is its own to draw again. - if (s.client) |cl| cl.link.dirty = true; - }, - } - return false; - } - - /// Terminal `screen` (its view live) 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 = terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) }); - } - - /// A SIGWINCH: the terminal, if it changed size, resized in its view - /// (one reporting in band says so as input). - fn winched(s: *Shell) void { - const sc = s.screen orelse return; - if (!sc.on or sc.vx.state.in_band_resize) return; - const ws = sc.tty.getWinsize() catch return; - if (sc.size) |was| if (std.meta.eql(was, ws)) return; - if (s.client == null) s.core.toView(s.own); - 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 {}; - } - - /// The tty's own motions (its glide, a jump's trail) are under way. - fn moving(s: *const Shell) bool { - const sc = s.term() orelse return false; - return sc.glide.moving() or sc.trail.active; - } - - /// The tty's own motions draw their frames themselves: the last frame - /// again, moved on, when the core has none to draw. - fn ownFrame(ctx: ?*anyopaque) void { - const s = of(ctx); - if (s.moving() and !s.core.needs_frame and s.core.surface.cells.len != 0) present(ctx, &s.core.surface); - } - - fn pollFrame(ctx: ?*anyopaque) void { - const s = of(ctx); - defer ownFrame(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.view().frontend.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.view().frontend.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; - // 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 tz_cells = tracy.zone(@src(), "surface->vaxis"); - const win = vx.window(); - // The tty's own motions, on its own clock, from the frame alone. - const now: u64 = s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - // The pictures it shows as glyph art, in a copy of the frame: all - // of them where the terminal has no kitty graphics. - const cell_h = terminalCellPixels(vx.screen.height_pix, vx.screen.height, 16); - const arted = sc.art.frame(s.gpa, s.frame.allocator(), canonical, vx.caps.kitty_graphics, cell_h) catch canonical; - sc.glide.frame(s.gpa, arted, now, null, null); - s.core.frames.scroll = @round(sc.glide.follow.offset); - const glided = glideRows(s.frame.allocator(), arted, &sc.glide) catch arted; - const truecolor = vx.caps.rgb or colortermTruecolor(); - const trail_on = s.core.settings.jump_trail and truecolor; - const shown = trailCells(s.frame.allocator(), glided, &sc.trail, trail_on, now) catch glided; - paintCells(win, shown.cells, shown.cols, shown.rows); - if (s.client) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), shown.cols, shown.rows); - tz_cells.end(); - if (vx.caps.kitty_graphics) for (canonical.placements.items) |place| { - if (place.art.glyph or !kittyImageRepresentable(place)) continue; - const key = place.key; - const rgba = place.raster.bytes(); - if (!sc.kitty.contains(key) 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, rgba)) break :shm; - if (vx.transmitLocalImagePath(s.gpa, sc.tty.writer(), name, @intCast(place.raster.w), @intCast(place.raster.h), .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)) { - const enc = std.base64.standard.Encoder; - if (s.gpa.alloc(u8, enc.calcSize(rgba.len))) |b64| { - defer s.gpa.free(b64); - _ = enc.encode(b64, rgba); - if (vx.transmitPreEncodedImage(sc.tty.writer(), b64, @intCast(place.raster.w), @intCast(place.raster.h), .rgba) catch null) |handle| - sc.kitty.put(key, handle) catch vx.freeImage(sc.tty.writer(), handle.id); - } else |_| {} - } - const cached = sc.kitty.get(key) orelse continue; - const d = place.dst; - if (place.at == null) { - // Fitted: kitty's own contain, at the top left. - const child = win.child(.{ .x_off = d.x, .y_off = d.y, .width = d.w, .height = d.h }); - cached.draw(child, .{ .scale = .contain }) catch {}; - } else if (d.h == 1) { - 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 = d.x + placement.cell_x; - if (win.readCell(x, d.y)) |under| { - var cell = under; - cell.image = .{ .img_id = cached.id, .options = placement.options }; - win.writeCell(x, d.y, cell); - } - } - } 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, d.x) + placement.cell_x, - .y_off = @as(i17, d.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]u64 = undefined; - var stale_len: usize = 0; - var image_iterator = sc.kitty.iterator(); - while (image_iterator.next()) |entry| { - if (surfaceHasKittyKey(canonical, 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 (shown.cursor) |cur| { - win.showCursor(cur.x, cur.y); - win.setCursorShape(if (cur.bar) .beam else .default); - } - 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() != null) s.core.presented(); - tracy.frameMark(); - } - - fn spawn(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { - const s = of(ctx); - if (s.adoptions.take(pane)) |a| 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.view().screen_h, s.core.view().screen_w) 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: host_io.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.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); - if (text.len > 0) sc.vx.copyToSystemClipboard(sc.tty.writer(), text, s.gpa) catch {}; - } - - 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 }); - sc.vx.requestSystemClipboard(sc.tty.writer()) catch {}; - } - - 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.view().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); - } - - /// A draw (api.draw) on a worker, as a job is. - fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { - const s = of(ctx); - return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct { - fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void { - of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop(); - } - }.deliver); - } - - fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { - const s = of(ctx); - if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); - host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { - fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { - of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); - } - }.deliver); - } - - /// 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); - } -}; - -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) 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 (`runClient`): 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: Msg = 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; - } - } - } -} - -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) error{OutOfMemory}!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 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)); -} - -/// A replica client's own line over its frame's last row (`Client.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. -/// The tty's picture of a jump's trail (jump_trail.zig): the cells behind -/// the cursor in its body, on the page's own ground, that ground drawn -/// toward the text's colour; a copy of `shown` while it fades. -fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *JumpTrail, on: bool, now_ns: u64) !*const pardes.Surface { - var at: [5]JumpTrail.Cell = undefined; - const lit = trail.see(if (shown.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); - if (lit.len == 0) return shown; - const cursor = shown.cursor.?; - const body = for (shown.regionList()) |region| { - if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and - cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; - } else return shown; - const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; - const page = shown.chrome.page orelse pardes.colors.null_page; - const out = try arena.create(pardes.Surface); - out.* = shown.*; - out.cells = try arena.dupe(pardes.Cell, shown.cells); - for (lit) |cell| { - if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; - const c = &out.cells[@as(usize, @intCast(cell.y)) * out.cols + @as(usize, @intCast(cell.x))]; - // On the page's own ground alone: never a selection or a match. - const ground: [3]u8 = if (c.default) page else switch (c.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (!std.mem.eql(u8, &ground, &page)) continue; - if (c.default) c.style = .{}; - c.default = false; - c.style.bg = .{ .rgb = pardes.colors.mixOklab(ground, ink, cell.strength) }; - } - return out; -} - -/// Truecolor by COLORTERM (truecolor or 24bit), for a terminal that does -/// not answer vaxis's query. -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"); -} - -/// The tty's picture of the glide (glide.zig, anim 12): the body's rows -/// moved by the offset rounded to whole rows (the position rounded, never -/// the step, so a slowing glide's steps come further apart), the rows that -/// left in the gap it opens, and a caret whose line rode the scroll carried -/// with it; `canonical` itself while the picture is where the core is, else -/// a copy of it in `arena`. The rows are walked from the side they move -/// toward, so each is read before a move writes over it. -fn glideRows(arena: std.mem.Allocator, canonical: *const pardes.Surface, glide: *const pardes.glide.Glide) !*const pardes.Surface { - const k: i32 = @intFromFloat(@round(glide.follow.offset)); - const w = glide.bw(); - const h = glide.body_h; - const x0 = glide.rect.x + pardes.config.GUTTER; - const y0 = glide.body_y; - if (k == 0 or w == 0 or h == 0 or x0 + w > canonical.cols or y0 + h > canonical.rows) return canonical; - const out = try arena.create(pardes.Surface); - out.* = canonical.*; - out.cells = try arena.dupe(pardes.Cell, canonical.cells); - const cols: usize = out.cols; - for (0..h) |i| { - const r = if (k > 0) i else h - 1 - i; - const from = @as(i32, @intCast(r)) + k; - const to = out.cells[(y0 + r) * cols + x0 ..][0..w]; - const kept: ?[]const pardes.Cell = if (from >= 0 and from < h) - out.cells[(y0 + @as(usize, @intCast(from))) * cols + x0 ..][0..w] - else if (from < 0 and -from - 1 < glide.nabove) - glide.above[@as(usize, @intCast(-from - 1)) * w ..][0..w] - else if (from >= h and from - h < glide.nbelow) - glide.below[@as(usize, @intCast(from - h)) * w ..][0..w] - else - null; - if (kept) |cells| @memcpy(to, cells) else @memset(to, .{}); - } - if (out.cursor) |*c| if (glide.caret_rides and c.x >= x0 and c.x < x0 + w and c.y >= y0 and c.y < y0 + h) { - const y = @as(i32, c.y) - k; - if (y >= y0 and y < y0 + h) c.y = @intCast(y) else out.cursor = null; - }; - return out; -} - -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 = vaxis_input.style(cell.style), - }); - } - } -} - -test "terminal input preserves fragmented keys queries paste and text after EOF" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ .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(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(t.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 t.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(t.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" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ - .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(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(t.vx.queries_done.load(.unordered)); - try std.testing.expect(t.vx.caps.kitty_graphics); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - var alt_up = false; - var clicked = false; - while (try t.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" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - // Two reads with `gap_ms` between them, as an ssh link delivers a - // sequence cut across two packets (TestReader). - const Events = struct { - /// What the loop was handed, one line per event. - fn of(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| { - t.vx.caps.kitty_keyboard = case.kitty; - const all = try std.mem.concat(gpa, u8, &.{ "x", case.bytes, "y" }); - defer gpa.free(all); - const whole_parts = [_][]const u8{ all, "" }; - var one: TestReader = .{ .parts = &whole_parts }; - try readInput(&t.loop, &one, &t.vx, &t.feed); - try Events.of(&t.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; - const halves = [_][]const u8{ all[0..cut], all[cut..] }; - var two: TestReader = .{ .parts = &halves, .gap_ms = if (after_esc and !case.kitty) 40 else 60 }; - try readInput(&t.loop, &two, &t.vx, &t.feed); - try Events.of(&t.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; - }; - } - } - t.vx.caps.kitty_keyboard = false; -} - -test "an ESC read by itself is the Escape key at once" { - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - // More always follows at once: a reader that waited on the ESC would - // take `j` for the rest of its sequence (Alt-j). - for ([_]bool{ false, true }) |kitty| { - t.vx.caps.kitty_keyboard = kitty; - var reader: TestReader = .{ .parts = &.{ "\x1b", "j" } }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(!reader.asked); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); - const escape = (try t.loop.tryEvent()).?.key_press; - try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint); - try std.testing.expect(!escape.mods.alt); - const j = (try t.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 t.loop.tryEvent() == null); - } - t.vx.caps.kitty_keyboard = false; -} - -test "a frame's answer is taken wherever the reads cut it, and never typed" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - const all = "x" ++ FrameAck.answer ++ "y"; - defer t.feed.ack.waiting.store(false, .release); - for (0..all.len) |cut| { - t.feed.ack.waiting.store(true, .release); - const halves = [_][]const u8{ all[0..cut], all[cut..] }; - var reader: TestReader = .{ .parts = &halves }; - try readInput(&t.loop, &reader, &t.vx, &t.feed); - try std.testing.expect(!t.feed.ack.waiting.load(.acquire)); - var typed: std.ArrayList(u8) = .empty; - defer typed.deinit(gpa); - var woke = false; - while (try t.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. - t.feed.ack.waiting.store(true, .release); - var glued: TestReader = .{ .parts = &.{ "\x1b" ++ FrameAck.answer, "j" } }; - try readInput(&t.loop, &glued, &t.vx, &t.feed); - try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?)); - try std.testing.expectEqual(.nop, std.meta.activeTag((try t.loop.tryEvent()).?)); - const escape = (try t.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 t.loop.tryEvent()).?.key_press.codepoint); - try std.testing.expect(try t.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" { - const io = std.testing.io; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - 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 loop: Loop = .init(io, undefined, &t.vx); - var feed: Feed = .{}; - var thread: ?std.Io.Future(void) = try io.concurrent(Reader.run, .{ &loop, &reader, &t.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(Msg) = 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); - } -} - -test "a terminal's image fragment goes to kitty cropped to its cells' scale, a full row one row high" { - var place = pardes.Placement{ - .pane = 0, - .raster = .{ .ptr = undefined, .w = 240, .h = 160, .stride = 960 }, - .src = .{ .x = 0, .y = 40, .w = 240, .h = 20 }, - .dst = .{ .x = 99, .y = 4, .w = 24, .h = 1 }, - .at = .{ .x = 0, .y = 0, .w = 240, .h = 20 }, - .key = pardes.Placement.keyOf(3, 7, 0), - }; - // 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.src = .{ .x = 0, .y = 0, .w = 205, .h = 13 }; - place.at = .{ .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.src = .{ .x = 0, .y = 0, .w = 400, .h = 40 }; - place.at = .{ .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" { - // As wide as the body: fit to width. - const base = pardes.Placement{ - .pane = 0, - .raster = .{ .ptr = undefined, .w = 96, .h = 64, .stride = 384 }, - .src = .{ .w = 96, .h = 10 }, - .dst = .{ .x = 0, .y = 0, .w = 38, .h = 14 }, - .at = .{ .y = 195, .w = 304, .h = 29 }, - .key = pardes.Placement.keyOf(1, 0, 1), - }; - 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.at.?.h); - - // Narrower than the body: fit to height. - var height = base; - height.at.?.w = 300; - height.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.at.?.h); - - height.at.?.h = 13; - try std.testing.expect(kittyPlacement(height, 80, 16, 640, 256) == null); -} - -test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } }); - const pane = core.panes[0].?; - pane.body.mode = .tty; - var frame = std.heap.ArenaAllocator.init(gpa); - defer frame.deinit(); - const a = frame.allocator(); - const px = try a.alloc(u8, 64 * 64 * 3); - for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 }; - const enc = try a.alloc(u8, std.base64.standard.Encoder.calcSize(px.len)); - _ = std.base64.standard.Encoder.encode(enc, px); - core.update(.{ .output = .{ .pane = 0, .bytes = try std.fmt.allocPrint(a, "\x1b[H\x1b[2J\r\nANCHOR>\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4;{s}\x1b\\\r\n", .{enc}) } }); - while (core.nextEffect()) |_| {} - const s = try core.render(a); - try std.testing.expectEqual(@as(usize, 4), s.placements.items.len); - var art: Art = .{}; - defer art.deinit(gpa); - try std.testing.expectEqual(@as(*const pardes.Surface, s), try art.frame(gpa, a, s, true, 16)); - const shown = try art.frame(gpa, a, s, false, 16); - const r = core.view().rects[0]; - const x0 = r.x + pardes.config.GUTTER + 7; - const y0 = core.bodyTop(pane, r) + 1; - var painted: usize = 0; - for (0..4) |dy| for (0..8) |dx| { - const cell = @constCast(shown).at(x0 + @as(u16, @intCast(dx)), y0 + @as(u16, @intCast(dy))); - const bg = switch (cell.style.bg) { - .rgb => |rgb| rgb, - else => continue, - }; - for (Art.commodore) |c| { - if (std.mem.eql(u8, &c, &bg)) painted += 1; - } - }; - try std.testing.expectEqual(@as(usize, 32), painted); -} - -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.Term.scrollback(core.panes[0].?.terminal, 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_ask.wait.?.id; - core.lspRequest(0, .status, ""); - const current_id = core.lsp_ask.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_ask.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_ask.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.view().active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_ask.wait.?.id, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = "", - }; - Shell.lsp(&shell, req); - try std.testing.expect(core.lsp_ask.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); - } -} - -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); -} - -test "a terminal pane gets function keys as their sequences and lone modifiers not at all" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - t.vx.queries_done.store(false, .unordered); - var reader: TestReader = .{ - .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(&t.loop, &reader, &t.vx, &t.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 t.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", vaxis_input.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()); - } - } -} - -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); - } -} - -test "a jump's trail tints the ground behind the cursor in its body, and is gone by 120 ms" { - std.testing.refAllDecls(JumpTrail); - 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.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 = .{}; - const ms = std.time.ns_per_ms; - s.cursor = .{ .x = body.x + 2, .y = body.y + 1 }; - _ = try trailCells(arena.allocator(), s, &trail, true, 1000 * ms); - // Ten cells right: a trail back toward where it was. - s.cursor = .{ .x = body.x + 12, .y = body.y + 1 }; - const lit = try trailCells(arena.allocator(), s, &trail, true, 1016 * ms); - var changed: usize = 0; - for (lit.cells, s.cells, 0..) |a, b, i| { - if (std.meta.eql(a, b)) 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); - try std.testing.expect(trail.active); - try std.testing.expect(try trailCells(arena.allocator(), s, &trail, true, 1150 * ms) == s); - try std.testing.expect(!trail.active); -} - -test "a fade sends the text it dims, not the blanks beside it" { - const gpa = std.testing.allocator; - var t: TestInput = undefined; - try t.init(); - defer t.deinit(); - try t.vx.resize(gpa, &t.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 }; - t.out.clearRetainingCapacity(); - paintCells(t.vx.window(), &cells, 32, 1); - try t.vx.render(&t.out.writer); - sent[frame] = try t.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); -} - -test "the tty draws a glide at whole rows: once a flick or a spin slows, its steps a tick never grow and its one-row steps come further apart, to where the core is" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 30, .tty_only = true }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..3000) |i| try text.print(gpa, "{d:0>5} line\n", .{i}); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var glide: pardes.glide.Glide = .{}; - defer glide.deinit(gpa); - var now: u64 = std.time.ns_per_s; - // One tick of the tty: the frame, the picture. - const tick = struct { - fn f(c: *pardes.Pardes, g: *pardes.glide.Glide, a: *std.heap.ArenaAllocator, t: u64) !i32 { - c.advance(t); - _ = a.reset(.retain_capacity); - const s = try c.render(a.allocator()); - g.frame(std.testing.allocator, s, t, null, null); - _ = try glideRows(a.allocator(), s, g); - return @intFromFloat(@round(g.follow.offset)); - } - }.f; - _ = try tick(core, &glide, &arena, now); - for ([_]usize{ 4, 24 }) |notches| { - for (0..notches) |i| { - core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 20, .row = 10 } }); - if (i % 2 == 1) { - now += pardes.frame_ns; - _ = try tick(core, &glide, &arena, now); - } - } - var drawn = try tick(core, &glide, &arena, now + pardes.frame_ns); - now += pardes.frame_ns; - var last_step: i32 = std.math.maxInt(i32); - var last_gap: usize = 0; - var since: usize = 0; - var ticks: usize = 0; - while (glide.moving()) : (ticks += 1) { - try std.testing.expect(ticks < 200); - now += pardes.frame_ns; - const k = try tick(core, &glide, &arena, now); - const step = k - drawn; - drawn = k; - since += 1; - if (step == 0) continue; - // Toward the core, never past it, each step no longer than the last. - try std.testing.expect(step > 0 and k <= 0); - try std.testing.expect(step <= last_step); - if (step == 1 and last_step == 1) try std.testing.expect(since >= last_gap); - if (step == 1) last_gap = since; - last_step = step; - since = 0; - } - try std.testing.expectEqual(@as(i32, 0), drawn); - } - // j held on the bottom row: the text glides a row a key under a caret - // that stays on its cell (it does not ride: its row is kept). - const keys = struct { - fn j(c: *pardes.Pardes) void { - c.update(.{ .key = .{ .cp = 'j', .text = "j" } }); - } - }; - for (0..40) |_| keys.j(core); - now += std.time.ns_per_s; - _ = try tick(core, &glide, &arena, now); - const row = (core.surface.cursor orelse return error.NoCursor).y; - for (0..20) |i| { - if (i % 2 == 0) keys.j(core); - now += pardes.frame_ns; - _ = try tick(core, &glide, &arena, now); - const shown = try glideRows(arena.allocator(), &core.surface, &glide); - try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y); - } -} diff --git a/src/vaxis_input.zig b/src/vaxis_input.zig deleted file mode 100644 index dcad9ef1..00000000 --- a/src/vaxis_input.zig +++ /dev/null @@ -1,147 +0,0 @@ -//! A key as vaxis parses it from a terminal's bytes, as the core's Event: -//! the one map for every shell that reads a terminal (tty, gui's stdin). -//! Three copies had drifted; the gui's had lost the F-keys, -//! Insert and the keypad. And the other way, a cell's style as vaxis draws -//! it. -const std = @import("std"); -const vaxis = @import("vaxis"); -const pardes = @import("pardes.zig"); - -/// The effective codepoint the way vaxis's own `Key.matches` sees it: a -/// single-character `text` wins, the terminal having resolved shift; -/// otherwise the shifted codepoint. -pub fn effCp(key: vaxis.Key) u21 { - if (key.text) |t| { - const view = std.unicode.Utf8View.init(t) catch return key.codepoint; - var it = view.iterator(); - if (it.nextCodepoint()) |c| { - if (it.nextCodepoint() == null) return c; - } - } - return key.shifted_codepoint orelse key.codepoint; -} - -/// vaxis's functional-key codepoints as the core's; the ASCII ones -/// (enter, tab, escape, backspace) already coincide. -pub fn mapKey(cp: u21) u21 { - return switch (cp) { - vaxis.Key.kp_enter => pardes.Key.enter, - vaxis.Key.up => pardes.Key.up, - vaxis.Key.down => pardes.Key.down, - vaxis.Key.left => pardes.Key.left, - vaxis.Key.right => pardes.Key.right, - vaxis.Key.home => pardes.Key.home, - vaxis.Key.end => pardes.Key.end, - vaxis.Key.page_up => pardes.Key.page_up, - vaxis.Key.page_down => pardes.Key.page_down, - vaxis.Key.delete => pardes.Key.delete, - vaxis.Key.insert => pardes.Key.insert, - vaxis.Key.print_screen => pardes.Key.print_screen, - vaxis.Key.scroll_lock => pardes.Key.scroll_lock, - vaxis.Key.pause => pardes.Key.pause, - vaxis.Key.menu => pardes.Key.menu, - vaxis.Key.f1...vaxis.Key.f25 => pardes.Key.f1 + (cp - vaxis.Key.f1), - // The keypad's own keys, which the kitty keyboard protocol tells - // apart, do what the keys they are named for do. - vaxis.Key.kp_left => pardes.Key.left, - vaxis.Key.kp_right => pardes.Key.right, - vaxis.Key.kp_up => pardes.Key.up, - vaxis.Key.kp_down => pardes.Key.down, - vaxis.Key.kp_page_up => pardes.Key.page_up, - vaxis.Key.kp_page_down => pardes.Key.page_down, - vaxis.Key.kp_home => pardes.Key.home, - vaxis.Key.kp_end => pardes.Key.end, - vaxis.Key.kp_insert => pardes.Key.insert, - vaxis.Key.kp_delete => pardes.Key.delete, - else => cp, - }; -} - -/// The key as the core's event, its text the key's own. -pub fn keyEvent(key: vaxis.Key) pardes.Event { - return .{ .key = .{ - .cp = mapKey(effCp(key)), - .text = key.text orelse "", - .ctrl = key.mods.ctrl, - .alt = key.mods.alt, - .shift = key.mods.shift, - } }; -} - -/// What a key typed inside a bracketed paste adds to it: its text, else a -/// tab, or a newline for Enter (the keypad's too) and Ctrl-J. -pub fn pasteBytes(key: vaxis.Key) []const u8 { - const text = key.text orelse ""; - if (text.len > 0) return text; - const cp = mapKey(effCp(key)); - if (cp == pardes.Key.tab) return "\t"; - if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) return "\n"; - return ""; -} - -/// A cell's style as vaxis draws it. -pub fn style(s: pardes.CellStyle) vaxis.Style { - return .{ - .fg = color(s.fg), - .bg = color(s.bg), - .bold = s.bold, - .dim = s.dim, - .italic = s.italic, - .blink = s.blink, - .reverse = s.reverse, - .invisible = s.invisible, - .strikethrough = s.strikethrough, - // The two underline enums name the same six styles. - .ul_style = switch (s.ul) { - inline else => |ul| @field(@FieldType(vaxis.Style, "ul_style"), @tagName(ul)), - }, - }; -} - -pub fn color(c: pardes.Color) vaxis.Color { - return switch (c) { - .default => .default, - .index => |i| .{ .index = i }, - .rgb => |rgb| .{ .rgb = rgb }, - }; -} - -test "F-keys, Insert and the keypad map to the core's keys" { - try std.testing.expectEqual(pardes.Key.f1 + 4, mapKey(vaxis.Key.f5)); - try std.testing.expectEqual(pardes.Key.f1 + 24, mapKey(vaxis.Key.f25)); - try std.testing.expectEqual(pardes.Key.insert, mapKey(vaxis.Key.insert)); - try std.testing.expectEqual(pardes.Key.up, mapKey(vaxis.Key.kp_up)); - try std.testing.expectEqual(pardes.Key.enter, keyEvent(.{ .codepoint = vaxis.Key.kp_enter }).key.cp); - try std.testing.expectEqual(@as(u21, 'a'), mapKey('a')); -} - -test "an event queue emptied in one batch lets every writer it held go on (build.zig's patch)" { - const io = std.testing.io; - const Q = vaxis.Queue(u8, 2); - var q: Q = .init(io); - try q.push(1); - try q.push(2); - const Writer = struct { - fn run(queue: *Q, byte: u8) !void { - try queue.push(byte); - } - }; - // Two writers waiting on the full queue, as a pane's pty reader and - // the frame ack's wake do under `yes`. - var a = try io.concurrent(Writer.run, .{ &q, 3 }); - defer a.cancel(io) catch {}; - var b = try io.concurrent(Writer.run, .{ &q, 4 }); - defer b.cancel(io) catch {}; - try io.sleep(.fromMilliseconds(20), .awake); - // The loop takes both at once: one pop from full, then one more. - try q.lock(); - _ = q.drain().?; - _ = q.drain().?; - q.unlock(); - var got: usize = 0; - var waited: usize = 0; - while (got < 2 and waited < 200) : (waited += 1) { - if (try q.tryPop() != null) got += 1 else try io.sleep(.fromMilliseconds(5), .awake); - } - try std.testing.expectEqual(@as(usize, 2), got); -} diff --git a/test/macos_trackpad.m b/test/macos_trackpad.m index 03c9d311..8f7d9775 100644 --- a/test/macos_trackpad.m +++ b/test/macos_trackpad.m @@ -1,7 +1,7 @@ /* Exercise the real AppKit adapter without a window or a physical trackpad. * Only SDL's event queue and window lookup are replaced with test doubles. */ #import -#include "../src/gui/macos_trackpad.m" +#include "../dev/gui/macos_trackpad.m" #include static id native_window; -- cgit v1.3