diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-05 11:40:11 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-05 12:41:36 -0300 |
| commit | 3f1533813b6692a736251e4d467a7f108229ddee (patch) | |
| tree | 37a32c5ebbf9d3af08923856fd6fa516f3b33a39 | |
| parent | cfd2b993feda1b3f7474225bb32db8cac8edc5ae (diff) | |
| download | pardes-3f1533813b6692a736251e4d467a7f108229ddee.tar.gz pardes-3f1533813b6692a736251e4d467a7f108229ddee.zip | |
targets: the DOM web shell goes (src/web.zig and src/web/, its harnesses web_harness, web_snapshot, web_driver_test and web-snapshots/, tools/web_fixture.py, -Dplatform=web, -Ddump, and the web, web-harness, web-snap, web-e2e and web-driver-test steps), and with it what only a freestanding build needed: `hosted` and every guard on it (every build has a host now), memory's stack-fallback arenas and reduced_target sizes, the emscripten main, the tree-sitter libc shim and the stb stub, lsp's has_client, the web arms of the platform switches (-Dplatform is tui, gui or macos); the macOS files pass zig ast-check; docs/web.md is a paragraph on what it was
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
73 files changed, 221 insertions, 3657 deletions
@@ -25,7 +25,7 @@ const deps_text = blk: { break :blk text; }; -pub const Platform = enum { tui, gui, web, macos }; +pub const Platform = enum { tui, gui, macos }; const PerfBuild = struct { compiler: []const u8, @@ -70,7 +70,7 @@ const gui_shaders = [_][]const u8{ }; pub fn build(b: *std.Build) void { - const requested_platform = b.option(Platform, "platform", "which shell to build (tui, gui, web, macos); absent builds the tui cli and the SDL gui together"); + const requested_platform = b.option(Platform, "platform", "which shell to build (tui, gui, macos); absent builds the tui cli and the SDL gui together"); const platform = requested_platform orelse .tui; const also_gui = requested_platform == null; // A bare `zig build` also copies the binaries into ~/.local/bin. Zig @@ -88,7 +88,7 @@ pub fn build(b: *std.Build) void { .os_tag = .macos, .os_version_min = .{ .semver = macos_min_version }, } else .{}, - .tui, .gui, .web => .{ + .tui, .gui => .{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu, @@ -96,22 +96,17 @@ pub fn build(b: *std.Build) void { }, }, }); - const requested_optimize = b.standardOptimizeOption(.{}); + const optimize = b.standardOptimizeOption(.{}); const static = b.option(bool, "static", "statically link") orelse false; - const dump_path = b.option([]const u8, "dump", "a Dump (a .dump file) embedded into the web shell (-Dplatform=web)"); // one substring, because that is what a dev loop needs: see the unit-test // step for why the whole-binary run is worth narrowing const test_filters: []const []const u8 = if (b.option([]const u8, "test-filter", "run only tests whose name contains this")) |f| &.{f} else &.{}; - const is_web = platform == .web; - const freestanding_core = is_web; - const enable_mupdf = b.option(bool, "mupdf", "native PDF rendering with MuPDF (AGPL/commercial; native default on, web off; -Dmupdf=false disables)") orelse !freestanding_core; + const enable_mupdf = b.option(bool, "mupdf", "PDF rendering with MuPDF (AGPL/commercial; default on; -Dmupdf=false disables)") orelse true; const enable_jpx = b.option(bool, "jpx", "JPEG 2000 in PDFs, for scanned documents (default on; -Djpx=false drops openjpeg)") orelse true; const embed_sources = b.option(bool, "embed-sources", "serve the editor's own sources under /src of its 9P tree (default off)") orelse false; - const is_web_target = target.result.cpu.arch == .wasm32 and target.result.os.tag == .freestanding; - const optimize = if (is_web) .small else requested_optimize; const test_build = b.step("test-build", "compile unit-test programs without running them"); const doc_typ_opts = b.addOptions(); doc_typ_opts.addOptionPathUntracked("dir", b.path("docs/typ")); @@ -154,7 +149,6 @@ pub fn build(b: *std.Build) void { const source = files.add("test_nonce.zig", b.fmt("pub const nonce = {d};\n", .{std.Io.Clock.awake.now(b.graph.io).nanoseconds})); break :blk b.createModule(.{ .root_source_file = source, .target = target, .optimize = optimize }); } else null; - if (freestanding_core) test_build.dependOn(&b.addFail("test-build needs a native platform").step); const unit_profile = b.addExecutable(.{ .name = "pardes-unit-profile", .root_module = b.createModule(.{ @@ -164,16 +158,11 @@ pub fn build(b: *std.Build) void { }), }); const c_optimize: std.lang.Optimize = if (optimize == .debug) .fast else optimize; - const default_grammars: TreeSitterGrammars = if (is_web) .zig else .full; - const requested_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full"); - const tree_sitter_grammars = requested_grammars orelse default_grammars; + const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full; const tracy = b.option([]const u8, "tracy", "enable Tracy profiling; supply the path to a Tracy source checkout"); const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-"; const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed the committed shaders/prebuilt/*.spv instead of running glslc (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui; - // The browser shell is a freestanding wasm core plus ordinary web files. - // JavaScript owns the loop and IO; HTML/CSS own rendering. - const web_step = b.step("web", "build the DOM browser shell into zig-out/web (-Dplatform=web -Dtarget=wasm32-freestanding -Ddump=<file.dump>)"); const mupdf_check = b.step("mupdf-check", "compile, link, render, and search docs/design.pdf with MuPDF"); const pdf_bench_step = b.step("pdf-bench", "benchmark real MuPDF page rendering (-- [--json] [--reps N] [--warmup N] [--path FILE] [--page N] [--pages N])"); const pdf_sections_bench_step = b.step("pdf-sections-bench", "benchmark PDF outline/sections paths in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N])"); @@ -197,13 +186,6 @@ pub fn build(b: *std.Build) void { } shaders_step.dependOn(&update_shaders.step); - snap_build.addWeb(b); - - if (is_web and !is_web_target) return failBuild(b, web_step, "-Dplatform=web requires -Dtarget=wasm32-freestanding"); - if (!is_web and (is_web_target or target.result.os.tag == .emscripten)) return failBuild(b, web_step, "wasm browser targets require -Dplatform=web"); - if (platform == .web and dump_path == null) return failBuild(b, web_step, "-Dplatform=web requires -Ddump=<file.dump> (the browser has no ptys; state replays from an embedded dump)"); - if (enable_mupdf and is_web) return failBuild(b, web_step, "-Dmupdf=true is supported only by the native tui/Kitty and gui/SDL backends"); - // build-time IO: slurps the grammars' highlights.scm queries, and reads // vendor/themes to find the theme sources var threaded: std.Io.Threaded = .init(b.allocator, .{}); @@ -213,14 +195,13 @@ pub fn build(b: *std.Build) void { const root_mod = b.createModule(.{ .target = target, .optimize = optimize, - // The browser and macOS shells are libraries whose host owns main(): - // each roots at its own flat C ABI instead of src/main.zig. + // The macOS shell is a library whose host owns main(): it roots at + // its own flat C ABI instead of src/main.zig. .root_source_file = b.path(switch (platform) { - .web => "src/web.zig", .macos => "src/macos.zig", .tui, .gui => "src/main.zig", }), - .link_libc = !freestanding_core, + .link_libc = true, }); const core_module = b.createModule(.{ .target = target, @@ -342,22 +323,6 @@ pub fn build(b: *std.Build) void { if (tree_sitter_grammars != .disabled) { const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter"); - if (is_web) { - const web_libc_include = b.path("src/web/libc/include"); - for (tree_sitter_mod.link_objects.items) |link_object| switch (link_object) { - .other_step => |lib| { - lib.root_module.link_libc = false; - lib.root_module.addIncludePath(web_libc_include); - lib.root_module.addCMacro("NDEBUG", "1"); - }, - else => {}, - }; - root_mod.addIncludePath(b.path("src/web/libc/include")); - root_mod.addCSourceFile(.{ - .file = b.path("src/web/libc.c"), - .flags = &.{ "-std=c11", "-DNDEBUG=1" }, - }); - } ts_mod = tree_sitter_mod; const ts_queries = b.addOptions(); @@ -376,7 +341,7 @@ pub fn build(b: *std.Build) void { const lib = b.addLibrary(.{ .name = "tree-sitter-" ++ g.name, - .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = !is_web }), + .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }), .linkage = .static, }); // Every allocation a grammar's external scanner makes goes to the @@ -394,19 +359,14 @@ pub fn build(b: *std.Build) void { lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/parser.c"), .flags = &ts_cflags }); if (g.scanner) lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/scanner.c"), .flags = &ts_cflags }); lib.root_module.addIncludePath(dep.path(g.src)); - if (is_web) lib.root_module.addIncludePath(b.path("src/web/libc/include")); ts_libs.append(b.allocator, lib) catch @panic("OOM"); } } ts_queries_opts = ts_queries; } - const zstbi_dep = if (!freestanding_core) b.dependency("zstbi", .{ .target = target, .optimize = c_optimize }) else null; - const zstbi_mod = if (zstbi_dep) |dep| dep.module("root") else b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/web/zstbi.zig"), - }); + const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize }); + const zstbi_mod = zstbi_dep.module("root"); // mvzr backtracks with no bound on its work (its own test "do not make // this test any longer": `a?` n times is 2^n steps), and pardes searches @@ -511,19 +471,16 @@ pub fn build(b: *std.Build) void { // One FreeType in a binary: the gui's glyph atlas links it and MuPDF is // built against it (see mupdf.zig). At c_optimize with the rest of the // vendored C, since MuPDF rasterizes a PDF's text through it. - const freetype_dep: ?*std.Build.Dependency = if (freestanding_core) null else b.dependency("freetype", .{ + const freetype_dep = b.dependency("freetype", .{ .target = target, .optimize = c_optimize, .@"enable-libpng" = false, }); - const freetype: ?*std.Build.Step.Compile = if (freetype_dep) |dep| dep.artifact("freetype") else null; + const freetype = freetype_dep.artifact("freetype"); // ...and one zlib, the one FreeType links for its gzip module. Asked of // FreeType's build with the options it asks with, the dependency cache // hands back that same artifact rather than a second copy. - const zlib: ?*std.Build.Step.Compile = if (freetype_dep) |dep| - dep.builder.dependency("zlib", .{ .target = target, .optimize = c_optimize }).artifact("z") - else - null; + const zlib = freetype_dep.builder.dependency("zlib", .{ .target = target, .optimize = c_optimize }).artifact("z"); if (enable_mupdf) { if (b.lazyDependency("mupdf", .{})) |mupdf_dep| { @@ -531,8 +488,8 @@ pub fn build(b: *std.Build) void { .target = target, .optimize = c_optimize, .jpx = enable_jpx, - .freetype = freetype.?, - .zlib = zlib.?, + .freetype = freetype, + .zlib = zlib, }); // src/pdf.zig over this MuPDF: the core's, and pdf-bench's at // ReleaseFast. @@ -794,7 +751,7 @@ pub fn build(b: *std.Build) void { } var ghostty_vt_for_snap: ?*std.Build.Module = null; - const ghostty_simd = !freestanding_core and (!target.result.os.tag.isDarwin() or b.graph.host.result.os.tag.isDarwin()); + const ghostty_simd = !target.result.os.tag.isDarwin() or b.graph.host.result.os.tag.isDarwin(); const ghostty_optimize: std.lang.Optimize = if (optimize == .debug) .safe else optimize; const ghostty_dep = b.lazyDependency("ghostty", .{ .target = target, .optimize = ghostty_optimize, .simd = ghostty_simd, .@"app-runtime" = .none, .@"emit-xcframework" = false }); if (ghostty_dep) |dep| { @@ -817,12 +774,12 @@ pub fn build(b: *std.Build) void { // applied here, at build time. const wuffs_mod: ?*std.Build.Module = if (ghostty_core_vt) |vt| vt.import_table.get("wuffs") else null; for ([_]?*std.Build.Step.Options{ opts, gui_opts }) |o| if (o) |x| x.addOption(bool, "wuffs_images", wuffs_mod != null); - if (wuffs_mod != null) if (zstbi_dep) |dep| { + if (wuffs_mod != null) { var sources: usize = 0; for (zstbi_mod.link_objects.items) |obj| switch (obj) { .c_source_file => |csf| { sources += 1; - const src = configureRead(b, io, dep.builder.root, "src/zstbi.c", 1 << 20) catch @panic("read zstbi.c"); + const src = configureRead(b, io, zstbi_dep.builder.root, "src/zstbi.c", 1 << 20) catch @panic("read zstbi.c"); const writer = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n"; if (std.mem.count(u8, src, writer) != 1) std.debug.panic("zstbi.c changed at `{s}`: redo its patch in build.zig", .{writer}); // zstbi.deinit still resets the writer's flip flag. @@ -833,7 +790,7 @@ pub fn build(b: *std.Build) void { else => {}, }; if (sources != 1) @panic("zstbi's build no longer compiles one C file: redo its patch in build.zig"); - }; + } // One zstd (docs/shared-libs.md): a far replica's stream, compressed by // its session and read by its client (src/replica.zig). The library's @@ -842,7 +799,7 @@ pub fn build(b: *std.Build) void { // its block compressors only those of levels 3 (dfast) and 6 (lazy), // the two replica.zig asks for, and its unused functions dropped at // link. Zig's std has a decompressor, but no compressor. - if (!freestanding_core) { + { const dep = b.dependency("zstd", .{}); const zstd = b.addLibrary(.{ .name = "zstd", @@ -954,7 +911,7 @@ pub fn build(b: *std.Build) void { gui_c.addIncludePath(b.path("src/gui")); gm.addImport("gui_c", gui_c.createModule()); } - gm.linkLibrary(freetype.?); + gm.linkLibrary(freetype); // HarfBuzz from source, like FreeType: its FreeType integration // (HAVE_FREETYPE, hb-ft) links the freetype artifact above, so the two // share one FreeType. The flags are the ones Ghostty builds it with, @@ -971,7 +928,7 @@ pub fn build(b: *std.Build) void { .link_libcpp = true, }), }); - harfbuzz.root_module.linkLibrary(freetype.?); + harfbuzz.root_module.linkLibrary(freetype); harfbuzz.root_module.addIncludePath(upstream.path("src")); harfbuzz.root_module.addCSourceFile(.{ .file = upstream.path("src/harfbuzz.cc"), @@ -1018,34 +975,7 @@ pub fn build(b: *std.Build) void { if (gui_shell_mod != root_mod) root_mod.addAnonymousImport("post-prefix.glsl", .{ .root_source_file = b.path("shaders/post/prefix.glsl") }); - if (is_web) { - const dp = dump_path.?; - root_mod.addAnonymousImport("embedded.dump", .{ - .root_source_file = if (std.fs.path.isAbsolute(dp)) .{ .cwd_relative = dp } else b.path(dp), - }); - } - - if (platform == .web) { - const wasm = b.addExecutable(.{ .name = "pardes", .root_module = root_mod }); - wasm.entry = .disabled; - wasm.rdynamic = true; - wasm.export_memory = true; - wasm.initial_memory = @as(u64, if (tree_sitter_grammars == .full) 64 else 32) * 1024 * 1024; - wasm.max_memory = 512 * 1024 * 1024; - web_step.dependOn(&b.addInstallFileWithDir(wasm.getEmittedBin(), .{ .custom = "web" }, "pardes.wasm").step); - inline for (.{ - .{ "src/web/index.html", "index.html" }, - .{ "src/web/app.mjs", "app.mjs" }, - .{ "src/web/pardes.css", "pardes.css" }, - .{ "assets/AdwaitaMono-Regular.ttf", "AdwaitaMono-Regular.ttf" }, - }) |file| web_step.dependOn(&b.addInstallFileWithDir(b.path(file[0]), .{ .custom = "web" }, file[1]).step); - - const run_web_harness = b.addSystemCommand(&.{ "node", "test/web_harness.mjs" }); - run_web_harness.addDirectoryArg(installed("web")); - run_web_harness.step.dependOn(web_step); - b.step("web-harness", "run the dependency-free JS/WASM DOM harness").dependOn(&run_web_harness.step); - b.getInstallStep().dependOn(web_step); - } else if (platform == .macos) { + if (platform == .macos) { const header = b.addTranslateC(.{ .root_source_file = b.path("src/macos/pardes.h"), .target = target, @@ -1204,7 +1134,6 @@ pub fn build(b: *std.Build) void { run_unit.has_side_effects = true; unit_step.dependOn(&run_unit.step); if (testMatch(b, unit_profile, test_filters, unit_step)) |check| check.addArtifactArg(unit_tests); - web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=<file.dump>").step); } else { var exe_name: []const u8 = if (platform == .gui) "pardes-gui" else "pardes"; if (target.result.os.tag != .linux or target.result.cpu.arch != .x86_64) @@ -1240,7 +1169,6 @@ pub fn build(b: *std.Build) void { const iso_step = b.step("run-isolated", "descend to a pardes with no host but the terminal"); iso_step.dependOn(&run_iso.step); } - web_step.dependOn(&b.addFail("web needs -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=<file.dump>").step); snap_build.addTty(b, .{ .exe = exe, @@ -1950,13 +1878,6 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. return o; } -// a bad -D combination: fail both `zig build` and `zig build web` with the why -fn failBuild(b: *std.Build, web_step: *std.Build.Step, msg: []const u8) void { - const fail = &b.addFail(msg).step; - web_step.dependOn(fail); - b.getInstallStep().dependOn(fail); -} - fn fatArchive(b: *std.Build, lib: *std.Build.Step.Compile) std.Build.LazyPath { const run = std.Build.Step.Run.create(b, "libtool libpardes.a"); run.addArgs(&.{ "libtool", "-static", "-o" }); diff --git a/build/snap.zig b/build/snap.zig index e82bf1ef..01316966 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -156,35 +156,3 @@ pub fn addTty(b: *std.Build, opts: struct { run_driver_test.has_side_effects = true; b.step("snap-driver-test", "test snapshot retry evidence and failure reporting").dependOn(&run_driver_test.step); } - -pub fn addWeb(b: *std.Build) void { - const driver_test = b.addSystemCommand(&.{ "node", "--test", "test/web_driver_test.mjs" }); - driver_test.setCwd(b.path(".")); - driver_test.has_side_effects = true; - b.step("web-driver-test", "test browser driver deadlines and cleanup").dependOn(&driver_test.step); - const build_web_snap = b.addSystemCommand(&.{ - b.graph.zig_exe, - "build", - "web", - "-Dplatform=web", - "-Dtarget=wasm32-freestanding", - "-Dtree-sitter=zig", - "-Ddump=test/web-snapshots/touch.dump", - "-p", - "zig-out/web-snap-test", - }); - build_web_snap.setCwd(b.path(".")); - const run_web_snap = b.addSystemCommand(&.{ - "node", - "test/web_snapshot.mjs", - "zig-out/web-snap-test/web", - "test/web-snapshots/touch.mjs", - }); - run_web_snap.setCwd(b.path(".")); - run_web_snap.step.dependOn(&build_web_snap.step); - run_web_snap.step.dependOn(&driver_test.step); - run_web_snap.has_side_effects = true; - run_web_snap.addPassthruArgs(); - b.step("web-snap", "run browser highlighting, touch, Look, resize and scroll checks").dependOn(&run_web_snap.step); - b.step("web-e2e", "run the Chrome-driven DOM end-to-end suite").dependOn(&run_web_snap.step); -} diff --git a/docs/macos.md b/docs/macos.md index 5542ac14..9b8f82ec 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -6,7 +6,7 @@ hand-written C ABI, `src/macos/pardes.h`, built as a static library that the app links; the Swift half is ordinary AppKit that pumps events in and reads one packed cell buffer out. There is exactly one core per process, so the ABI has no handles — the state is a file-scoped singleton and every function names it -implicitly, exactly like the browser backend. +implicitly. The research this design came out of is written down separately in `docs/ghostty-macos-notes.md` — how ghostty wires Zig to Swift, what its build @@ -53,23 +53,20 @@ cell ABI is unchanged, but shader effects draw that same frame into a retained bitmap and feed it through Core Image kernels on one Metal context. There is no second glyph atlas, pane renderer, or view pointer in the ABI. -## Why the ABI mirrors src/web.zig +## Why the ABI is flat -The browser and a Cocoa app are the same host, and the browser proved the shape -first. In both, someone else owns the clock and the event loop; events arrive +The browser shell (gone since 2026-11-05, `docs/web.md`) proved the shape +first: someone else owns the clock and the event loop; events arrive through flat functions that take scalars and borrowed byte ranges; one call renders, and the result is one contiguous array of packed cells the host walks -linearly. `pardes_cell_s` is byte-for-byte `WebCell`: seven UTF-8 bytes of +linearly. `pardes_cell_s` is the browser's `WebCell` as it was: seven UTF-8 bytes of grapheme plus a guaranteed zero, tagged `fg`/`bg` words (`0x01000000` default, `0x02000000 | index` for the palette, otherwise `0x00RRGGBB`), an attribute bitfield with the underline style in the high bits, and a `flags` bit meaning "the core never painted this cell" so a host can draw background only and skip -the glyph. Two hosts spelling the same encoding is not duplication worth -removing; it is the encoding being right. +the glyph. -The one real difference is IO. The browser has no ptys, so `src/web.zig` -forwards every effect out to JavaScript as a numbered code plus a byte payload, -and JavaScript performs it. macOS has `forkpty`, `read` and `write` right +IO stays on the Zig side: macOS has `forkpty`, `read` and `write` right there, so almost no effect crosses the boundary at all: `pardes_tick` runs `while (core.nextEffect()) |e| core.perform(e)` (`src/macos.zig:1154`) and each effect lands on this host's own `Host.VTable`, of whose twenty-one methods @@ -116,12 +113,12 @@ confused with a real codepoint arriving as text. `pardes_mouse` speaks acme's vocabulary: three buttons, where 1 selects, 2 executes and 3 looks, with wheel directions as ordinary buttons rather than a separate axis. Ctrl is the only modifier the core consults (a left press with ctrl is goto-definition), but the -full mask is passed anyway to keep the signature identical to the web one. +full mask is passed anyway to keep the signature whole. `pardes_scroll` carries fractional row and column deltas from a trackpad; the Zig side accumulates each axis separately and synthesizes whole `wheel_up`/`wheel_down`/`wheel_left`/`wheel_right` presses, because the core -scrolls on button events. `src/gui/gui.zig` (`takeScrollTicks`) and -`src/web/app.mjs` both do exactly this already. A real mouse notch skips the +scrolls on button events. `src/gui/gui.zig` (`takeScrollTicks`) does +exactly this already. A real mouse notch skips the smoothing and goes through `pardes_mouse`. `pardes_rotate` is the same shape for a two-finger twist, spent as `n`/`N` — see the trackpad section. `pardes_command` runs one builtin command line through the core's own `command` @@ -165,7 +162,7 @@ to input. An unintegrated shell has no reliable readiness signal, so it skips the cosmetic greeting; an explicit command still releases after its successful fork. Setting `Options.cols`/`rows` alone never bumps that counter, so init must turn its arguments into an actual resize -event the way `src/web.zig` does immediately after construction — and the size +event immediately after construction — and the size must be true, because the first `forkpty` takes its winsize from the core's current grid and a shell booted at a placeholder draws its first prompt at the wrong width. **Call `pardes_tick` after every input function.** The input calls @@ -827,7 +824,7 @@ directory the benchmark binaries install into likewise never appears in this backend; nothing here is a dev binary. `-Dplatform=macos` is the one platform that overrides the repo's default -target. The tty, SDL and web shells default to the Steam Deck (x86_64 linux-gnu, glibc +target. The tty and SDL shells default to the Steam Deck (x86_64 linux-gnu, glibc pinned to 2.38), and that default is not survivable here: swiftc links this archive, so a Steam Deck build hands ld64 ELF objects inside a GNU archive and the app link dies with `archive member '/SYM64/' not a mach-o file`. On a Mac @@ -1128,9 +1125,9 @@ used for the table and is not folded into the direct-path claim. - **The `pipe` effect.** Selection filters need `pipeRequest(id)` copied into a job, a worker to run the command, and a `pipe_resp` event back. Same shape as `lsp`, one more response type. -- **Detached sessions.** `Attach` (`SPC s a`) and `Detach` (`SPC s D`) exist on - every hosted platform, this one included, because `Builtin.enabled` is - `pardes.hosted`. Neither works here. `Detach` emits `Effect.detach`, this +- **Detached sessions.** `Attach` (`SPC s a`) and `Detach` (`SPC s D`) are + the tui's and the window's alone (`Builtin.enabled` is `pardes.can_attach`); + were they built here, neither would work. `Detach` emits `Effect.detach`, this host fills in no `detach`, and `Pardes.perform` therefore reports `error.NotAttached` on the pane's message row (`src/pardes.zig:6837`). `Attach` emits `Effect.attach`, which `perform` turns into an `attach_req` diff --git a/docs/shared-libs.md b/docs/shared-libs.md index 412c2474..662579ea 100644 --- a/docs/shared-libs.md +++ b/docs/shared-libs.md @@ -58,8 +58,8 @@ Text section: tty 61,369,343 → 61,294,855 bytes (**−74,488**); gui - **PNG and JPEG are wuffs's**, the decoders ghostty itself uses. image.zig calls them wherever ghostty-vt is in the build (`wuffs_images`). Each image - is sized from its header first: PNG's IHDR, JPEG's first SOF. Other formats, - and builds without ghostty-vt (web), stay on stb_image. + is sized from its header first: PNG's IHDR, JPEG's first SOF. Other formats + stay on stb_image. - **zstbi is compiled with `-DSTBI_NO_PNG -DSTBI_NO_JPEG`.** That also drops stb's inflate, which only PNG used. Its `stb_image_write` include is patched out (one count-checked anchor), with a no-op `stbi_flip_vertically_on_write` @@ -81,8 +81,8 @@ Text section: tty 61,369,343 → 61,294,855 bytes (**−74,488**); gui - **Two JPEG decoders: MuPDF's libjpeg and wuffs.** MuPDF's `DCTDecode` filter (`filter-dct.c`) is written against libjpeg's streaming source-manager API. Moving PDFs onto wuffs means a new DCT filter for fitz. Moving image panes - onto libjpeg instead would leave the build without MuPDF (web) - with no JPEG decoder. + onto libjpeg instead would leave a `-Dmupdf=false` build with no JPEG + decoder. - **MuPDF's fitz image loaders** (`fz_load_png`, `_jpeg`, `_gif`, `_bmp`, `_tiff`, `_pnm`, `_psd`; 16.7 KiB together). They are compiled because mupdf.zig builds all of `source/fitz`. They are reachable only through diff --git a/docs/typ/building.typ b/docs/typ/building.typ index da704fe8..972b8a97 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -18,7 +18,6 @@ builds MuPDF and is on by default (`-Dmupdf=false` drops it). [`zig build`], [the terminal shell and the SDL window together, *installed into `~/.local/bin`* (`pardes` and `pardes-gui`)], [`zig build -Dplatform=tui`], [the terminal shell alone], [`zig build -Dplatform=gui`], [the SDL3 window alone], - [`zig build web -Dplatform=web -Dtarget=wasm32-freestanding -Ddump=<file>`], [a freestanding wasm core plus vanilla JavaScript (`docs/web.md`)], [`zig build -Dplatform=macos`], [an AppKit and CoreText app over a static `libpardes.a` (`docs/macos.md`)], ) @@ -37,11 +36,11 @@ must share with its session; `pardes --help` lists every flag. `zig build --help` lists the options for the selected platform. #pairs( - [`-Dplatform`], [`tui`, `gui`, `web`, `macos`; absent: the tui and SDL shells together, installed into `~/.local`], + [`-Dplatform`], [`tui`, `gui`, `macos`; absent: the tui and SDL shells together, installed into `~/.local`], [`-Dstatic`], [bool, `false`], - [`-Dmupdf`], [bool; on natively, off for web], + [`-Dmupdf`], [bool, `true`], [`-Djpx`], [bool, `true`: JPEG 2000, and with it scanned PDFs], - [`-Dtree-sitter`], [`disabled`, `zig`, `minimal`, `full`; `full` natively, `zig` for web], + [`-Dtree-sitter`], [`disabled`, `zig`, `minimal`, `full`; `full`], [`-Dembed-sources`], [bool, `false`: serve the sources under #file("/src")], [`-Dhome-install`], [bool: a bare `zig build` also copies the binaries into `~/.local/bin`; default true], [`-Dstamp-commit`], [bool: the git commit in `--version` and crash records; on for release builds and the `~/.local` install], @@ -50,7 +49,6 @@ must share with its session; `pardes --help` lists every flag. [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; `zig build shaders` refreshes it with glslc], [`-Dtracy`], [path to a Tracy checkout; off], [`-Dmacos-identity`], [codesigning identity for `pardes.app`; `-` (ad hoc)], - [`-Ddump`], [a Dump to embed in the web shell], [`-Dtest-filter`], [run only tests whose name contains it; a filter that matches nothing fails], [`-Dtest-rebuild`], [bool: fresh Zig test compilation], [`-Dhelix-harness`], [reference executable for live differential tests; `HX_HARNESS`, else `hx-harness` on `PATH`], @@ -84,8 +82,6 @@ zig build hxparity file-pane vs pty-pane editing parity zig build hxgolf every helix-golf example, step by step, against helix zig build perf-gate a gesture on the 50k-line file over 3x its baseline fails zig build mupdf-check compile, link, render and search docs/design.pdf -zig build web-snap browser highlighting and touch interactions -zig build web-e2e Chrome-driven DOM end-to-end suite zig build cheatsheet render the cheatsheet PDF (needs typst) ``` @@ -121,7 +117,7 @@ zig build cheatsheet render the cheatsheet PDF (needs typst) A release passes all of these first: `unit-test` with `-Dplatform=tui` and with `-Dplatform=gui`, `core-test`, `behaviour-test`, `process-test`, `snap`, the GUI goldens (`zig build gui-golden -Dplatform=gui`, a hidden window; `PARDES_GUI_GOLDEN=update` rewrites them), -`web`, and the ReleaseSafe tui and ReleaseFast gui builds. The committed +and the ReleaseSafe tui and ReleaseFast gui builds. The committed `docs/typ/cheatsheet-a4.pdf` is rendered again when the docs change. = Sending patches <patches> @@ -134,7 +130,7 @@ Mail patches to the list `~gbrls/[email protected]`; it is the preferred way to = The core and its shells -One core, four shells (tui, gui, web, macos). The core owns +One core, three shells (tui, gui, macos). The core owns editing, layout, rendering and the virtual filesystem it serves over 9P; a shell turns native input into `pardes.Event`, presents `pardes.Surface`, and performs host effects such as spawning processes. @@ -155,15 +151,14 @@ effects such as spawning processes. - `host_io.Host` is a context pointer and a vtable of optional callbacks; a null method is not an error, and `Host{}` is a complete in-process pardes that the tests use. Comptime decides what a build has (`pardes.platform`, - `hosted`, `can_attach`, `pdf_enabled`); the vtable + `can_attach`, `pdf_enabled`); the vtable decides who serves it. - The root module is chosen by platform: `main.zig` (tui, gui), - `web.zig`, `macos.zig`. The web and macOS shells are - libraries whose host owns `main()`. + `macos.zig`. The macOS shell is a library whose host owns `main()`. - `memory.limits` is the one home for the core's capacities (selections, the tag's bytes, undo, the arenas' regions). Each core - allocator is a thread-safe stack-fallback allocator, under a - DebugAllocator in Debug builds. + allocator is a DebugAllocator over its arena's reserved region, thread + safe, its checks in Debug builds only. Code map: `src/panes.zig` and the pane kinds it names (`src/File.zig`, `src/Terminal.zig`, ...), `src/layout.zig`, `src/fs.zig` (host access, @@ -188,7 +183,7 @@ selection-pipe workers post completions through a bounded mailbox; a `host_io.Lsp.Job` owns copies of the source, path and arguments, never reading the live core, and a request id, the pane's serial and (for an edit) the file's revision reject a stale reply. A process that never calls -`turn.start` (the tests, the browser) has no second thread. +`turn.start` (the tests) has no second thread. == The daemon and detached sessions @@ -310,7 +305,7 @@ the hint. = Other notes `docs/` keeps the platform and design notes beside this book: -`web.md` and `macos.md` (the browser and macOS shells), `effects.md` and +`macos.md` (the macOS shell; `web.md` says what the browser shell was), `effects.md` and `render-pipeline.md` (visual effects), `helix-keys.md` and `selections.md` (helix parity), `lsp-evaluation.md`, `ui-review.md`, `divergences.md` (bookmarks off `main`) and `open-questions.md`. `next-steps.txt` is a wishlist and diff --git a/docs/web.md b/docs/web.md index 26646a38..9e064d6e 100644 --- a/docs/web.md +++ b/docs/web.md @@ -1,144 +1,15 @@ -# DOM web backend +# The DOM web shell (gone) -The web backend keeps the existing Pardes core and replaces the old -Emscripten/SDL/WebGL shell. Zig produces a `wasm32-freestanding` module whose -only imports are the four browser capabilities listed below — no libc, no WASI, -no runtime. JavaScript owns `requestAnimationFrame`, browser input and window -sizing; the CORE owns the loop and JavaScript calls one iteration of it per -frame. HTML and CSS render selectable, accessible text. There is no canvas. - -The default web build links Tree-sitter's C runtime and the Zig grammar inside -that same import-free module. A small freestanding compatibility layer supplies -the C ABI locally, so source panes retain the core's Tree-sitter highlighting -without Emscripten, WASI, or browser libc imports. Other grammar tiers remain -selectable with `-Dtree-sitter=minimal` or `-Dtree-sitter=full`. - -`src/web.zig` is the narrow WASM ABI. Events enter through exported functions -that hand them straight to `Pardes.update`. `pardes_tick` is one -`Pardes.pump` — queued input, effects, render, present — and the host's -`present` packs the canonical `Surface` into a 20-byte cell array that -`pardes_frame`/`_ptr`/`_cols`/`_rows` describe. `src/web/app.mjs` reads that -array in one linear pass and patches stable DOM nodes. - -Animated time is JavaScript's alone. `pardes_animation_tick` spends one fixed -60 Hz step and is the only entry that advances a transition, exactly as the -AppKit shell keeps its display clock apart from its pumps: if every input pump -also advanced a fade, a burst of keys would collapse ten frames into one. -`pardes_tick` never advances animated time itself, and no longer has to undo -anything to avoid it: `Pardes.pump` does not post a tick for its caller, since -only the host knows when a real frame interval has passed. - -Cell attribute bit 7 carries the core's tagline font role. The DOM keeps every -cell at the body grid's fixed width and height, but scales and centres the -tagline glyph using the build-time `gui_tagline_font_percent`; the percentage is -exported by the module rather than duplicated in JavaScript. Animation time is -also host-independent: `requestAnimationFrame` time is accumulated into 60 Hz -core ticks, so 120/144 Hz displays do not accelerate frame-count transitions -and a returning background tab has bounded catch-up work. - -The `web` platform is deliberately not one of the shader-capable native GUI -shells, and two comptime capability flags say so once each. It exposes no -`Panel*` transition builtins (`PanelSlide`, `PanelZoom`, `PanelDissolve`, -`PanelAscii`, `PanelVertical`, `PanelEdges`, `PanelFall`, `PanelWave`, -`PanelCurtain`, `PanelScramble`, `PanelType`) because -`capabilities.panel_transitions` is `pardes.hosted`, and no -`Crt` or `Shader` because `capabilities.scene_shaders` is -`platform == .gui or platform == .macos` (`builtins.capabilities`; the words -themselves carry those availabilities in `config.Runtime.settings`). -Applying either faithfully would require a second canvas renderer and give up -the DOM renderer's selectable/accessibility contract. Theme fades and the -delayed, side-effect-free Look hover remain grid animations and continue to use -the fixed 60 Hz ticks above. - -Build a replay from a dump: - -```sh -zig build web \ - -Dplatform=web \ - -Dtarget=wasm32-freestanding \ - -Dtree-sitter=zig \ - -Ddump=test/web-snapshots/touch.dump -``` - -The output is in `zig-out/web`. Serve that directory over HTTP; browsers do not -allow a useful WASM module load from `file:` URLs. - -The browser shell has no argv: every command-line flag `src/main.zig` parses — -`--tty`, `--tty-toggle`, `-n`, `-l`, `--9p=<name>`, `--mount=<name>=<dial>`, `--nested`, -`--detach[=<name>]`, `--attach[=<name>]`, `-h`/`--help`, `--version`, and the -positional file-or-directory — is native-only, because the wasm module roots at -`src/web.zig` and never links `main.zig`. State comes from the embedded dump -instead, and there is nothing here to answer `--version` with even though -`pardes.version` and `pardes.commit` are compiled in like everywhere else. - -Web LOOK's source archive follows Git's working-tree view: tracked `.zig` files -plus new, nonignored ones, sorted by path. The checked-in browser replay is a -real native TTY dump of that same selection; its top and bottom launcher -snapshots jointly cover the complete list before opening `build.zig`. - -What is genuinely absent is narrower than "no IO". The module has no threads -and no host filesystem, so there is no startup config directory, init file, -ThemeFile, or DumpThemes; LOOK resolves -against the build-generated source archive rather than disk, and no language -BACKEND is compiled in (there is none for wasm — which also means -`lsp.supports` is empty, so the core never even raises a language query there, -and the host leaves `lsp` null). - -Replay terminals retain the same core shape but use Zig's failing IO value; -this keeps the module freestanding without instantiating POSIX threaded IO that -the browser can never call. - -`Attach` and `Detach` are absent for the same structural reason and behind the -same gate: both are `enabled = pardes.hosted` (`src/builtins.zig`, and -`pardes.hosted` is `tty or gui or macos`), because a detached session is a unix -socket and a page has none. Nothing in this shell speaks -`src/wire.zig`, and `detach` is one of the null vtable methods -below. - -`src/web.zig` fills in six methods of `Host.VTable` and leaves the rest null, -and a null method is answered by the core itself rather than forwarded to a -page that could not honour it. The six are `present`, `write_file`, -`write_dump`, `set_clipboard`, `read_clipboard` and `open_link`; the last five -are backed by four imports from the module `pardes` that JavaScript supplies at -instantiation, because a written file and a written dump are both a download: - -| import | effect behind it | -|---|---| -| `host_open_link(url, len)` | `open_link` — `window.open` | -| `host_set_clipboard(text, len)` | `set_clipboard` — `navigator.clipboard.writeText` | -| `host_read_clipboard()` | `read_clipboard` — answered later, or never, by `pardes_paste` | -| `host_download(path, path_len, bytes, len)` | `save_file`, `save_text` and `write_dump`: a file a page writes is a download | - -What the core answers instead of asking: `spawn`, `pty_write` and `pty_resize` -land in the per-instance fallback, so a pane with no child is SILENT rather -than synthetic; `tty_taken` is never taken; any save the page declines resolves -against the core's virtual filesystem, which is also where every read comes -from — the core reads files itself and never asks a host; `watch_file` records -the request; `lsp` answers an empty row set at once (no backend is built for -wasm, so the core never raises a query there anyway) and `pipe` answers -failure; `wait_input` is null because wasm must never block, and `watch_theme` -and `dump_themes` are not reachable without a config directory. Of the -remaining nulls, `post_present` and `poll_frame` are per-frame host bookkeeping -a page has none of, `detach` has no session to leave, `gpio_toggle` belongs to -the ESP32-P4 board, and native filesystem replies are delivered by the 9P -listener. `quit` sets the -core's flag, which `pardes_should_quit` reports so the page can stop its frame -loop. - -Two dependency-free test layers cover the boundary: - -```sh -# Real WASM in Node plus a small DOM double. -zig build web-harness \ - -Dplatform=web \ - -Dtarget=wasm32-freestanding \ - -Dtree-sitter=zig \ - -Ddump=test/web-snapshots/touch.dump - -# Real headless Chrome, DOM rendering, and browser touch input. -zig build web-e2e -``` - -Set `PARDES_CHROME` when Chrome/Chromium is not on `PATH`, in a normal -Playwright/Puppeteer cache, or — on macOS, where a browser's executable lives -inside an application bundle and never on `PATH` — under `/Applications`. +pardes had a browser shell until 2026-11-05: the core built as a +`wasm32-freestanding` module rooted at `src/web.zig` (a handful of exports, +four imports, no libc, a C shim for tree-sitter), `src/web/app.mjs` +patching DOM cells from one packed cell array each `requestAnimationFrame`, +and a replay of an embedded dump with no ptys, no host filesystem, no +threads and no language server, under its own steps (`web`, `web-harness`, +`web-snap`, `web-e2e`, `web-driver-test`) that no gate ran. It went with +the ESP32-P4 board (`.scratch/clean-room/architecture.md` §9.3, §9.4 step +10): nothing used it, it rotted between fixes, and every build carried its +`hosted` guards, its freestanding arenas and its stb shim. The arch base +`qkvytkrn` is the last change with it, the place to start again from if +the website wants a replay viewer, or a freestanding build to prove the +core imports no I/O. diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 90b93efb..2719717b 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- The DOM web shell is gone: `-Dplatform=web` and `-Ddump`, the `web`, + `web-harness`, `web-snap`, `web-e2e` and `web-driver-test` steps, and + `src/web/`; every build has a host now, so what only a freestanding + build needed (the `hosted` guards, its arenas, the emscripten main) went + with it. `docs/web.md` says what it was. - The ESP32-P4 board port is gone: `-Dplatform=esp32p4` with its `-Desp32p4-cols` and `-rows`, the `Peek`, `Poke`, `Hexdump` and `Gpio` words, and every limit and guard only the board needed; the desktop diff --git a/src/Dir.zig b/src/Dir.zig index f43c6e02..ae96d816 100644 --- a/src/Dir.zig +++ b/src/Dir.zig @@ -349,7 +349,6 @@ fn named(p: *Pardes, name: []const u8) struct { id: ?usize, count: usize } { } test "a look at a directory opens a pane named for it with a /, its entries in columns, never dirty, its directory its own" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -378,7 +377,6 @@ test "a look at a directory opens a pane named for it with a /, its entries in c } test "a look at an entry is a look from the directory, .. goes up to the open pane, and Get or a look again reads it again" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -413,7 +411,6 @@ test "a look at an entry is a look from the directory, .. goes up to the open pa } test "an exec in a directory pane runs in its directory, and its +Errors goes there" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -434,7 +431,6 @@ test "an exec in a directory pane runs in its directory, and its +Errors goes th } test "over 9P a directory pane is a text pane whose name ends in /, its body the listing, ctl's isdir 1, and get reads it again" { - if (comptime !pardes.hosted) return; const th = @import("ninep/testing.zig"); const tree = @import("ninep/tree.zig"); var tmp = testing.tmpDir(.{}); @@ -461,7 +457,6 @@ test "over 9P a directory pane is a text pane whose name ends in /, its body the } test "a directory pane lays its entries out again when its width changes, unless its text was edited" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; diff --git a/src/FrameStats.zig b/src/FrameStats.zig index 680987fb..623acd24 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -137,7 +137,6 @@ pub fn zone(stats: *FrameStats, which: Zone, from_ns: u64) void { } pub fn nowNs() u64 { - if (comptime !pardes.hosted) return 0; var ts: std.c.timespec = undefined; if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; return @as(u64, @intCast(ts.sec)) *| std.time.ns_per_s +| @as(u64, @intCast(ts.nsec)); @@ -181,9 +180,9 @@ pub fn record(stats: *FrameStats, end_ns: u64, moving: bool, skipped: bool) void if (stats.armed and @as(u64, gap) * std.time.ns_per_us * 2 > stats.period_ns * 3) stats.jank += 1; if (@as(u64, frame.update_us + frame.render_us + frame.present_us) * std.time.ns_per_us > stats.period_ns) stats.over_budget += 1; if (skipped) stats.skipped += 1; - if (comptime pardes.hosted) if (stats.count == 0 and std.c.getenv("PARDES_FRAMES") != null) { + if (stats.count == 0 and std.c.getenv("PARDES_FRAMES") != null) { stats.long = std.heap.page_allocator.create([long_capacity]Frame) catch null; - }; + } const ring: []Frame = if (stats.long) |long| long else &stats.ring; ring[@intCast(stats.count % ring.len)] = frame; stats.count += 1; @@ -263,7 +262,6 @@ pub fn summary(stats: *const FrameStats, buf: []u8) []const u8 { /// Writes the summary and every frame the ring holds to `path`: a header /// of `# ` lines, then one tab-separated line a frame. The long ring goes. pub fn dump(stats: *FrameStats, path: [:0]const u8) void { - if (comptime !pardes.hosted) return; defer if (stats.long) |long| { std.heap.page_allocator.destroy(long); stats.long = null; diff --git a/src/Layer.zig b/src/Layer.zig index 96250ce4..c5125a81 100644 --- a/src/Layer.zig +++ b/src/Layer.zig @@ -124,7 +124,7 @@ fn pointIn(kind: Kind, layer: Place, x: f32, y: f32, body_w: f32, body_h: f32, t if (layer.rows == 0 or !std.math.isFinite(x) or !std.math.isFinite(y)) return null; // A band's hit is refused outright on metrics no host could have; a // body's has always been floored to a pixel instead, and both refuse - // what is no number or past a u16 (a host's floats: web's exports). + // what is no number or past a u16 (a host's floats). for ([_]f32{ body_w, body_h, tagline_w, tagline_h }) |metric| { if (!std.math.isFinite(metric) or metric > std.math.maxInt(u16)) return null; if (kind != .body and metric < 1) return null; diff --git a/src/Messages.zig b/src/Messages.zig index 63650be5..98e005be 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -218,7 +218,6 @@ fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void { /// ponytail: a pane's older lines go with its newest, not each on its own /// clock; the render pipeline's clock will give every line its own. fn nowMs() i64 { - if (comptime !pardes.hosted) return 0; var ts: std.c.timespec = undefined; if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000); @@ -928,7 +927,6 @@ test "messages stack, oldest on top, each on its own timing" { } test "a builtin announces itself on the message row, and Verbose silences it" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[p.active].?; @@ -980,7 +978,6 @@ test "a builtin announces itself on the message row, and Verbose silences it" { } test "notices stack over the body's top rows without moving them" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const id = p.active; diff --git a/src/Output.zig b/src/Output.zig index 990032be..5a774d33 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -717,7 +717,7 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { const own = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // Its directory gone (or never there, a name not yet saved): the list // goes in the session's, where a look from it can still resolve. - const dir = if (comptime pardes.hosted) (if (pardes.filesystem.localPath(own)) |local| (if (exec.kindOf(local) == .directory) own else p.sessionDir()) else own) else own; + const dir = if (pardes.filesystem.localPath(own)) |local| (if (exec.kindOf(local) == .directory) own else p.sessionDir()) else own; const free = p.freeSlot() orelse return p.gpa.free(content); _ = open(p, free, dir, .unsaved, "", content) catch return; exec.placeNew(p, id, id, free, .doc); @@ -974,13 +974,12 @@ pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var dir_buf: [1024]u8 = undefined; - const host_fs = comptime (pardes.platform != .web); var located: std.Io.Writer.Allocating = .init(p.gpa); defer located.deinit(); try p.locations_config.write(&located.writer); try config.Runtime.writeReport(&out.writer, .{ .locations = located.written(), - .default_dump_dir = if (host_fs) pardes.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}) else "", + .default_dump_dir = pardes.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}), .startup_config_path = p.startupPath(), .platform = builtins.viewPlatform(p), .theme_name = p.theme().name, diff --git a/src/Pipe.zig b/src/Pipe.zig index 276f9967..1f0ee5fc 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -193,8 +193,8 @@ fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Fai /// +Errors says of a `|` and of an Edit's `< | >`. pub fn writeFailure(w: *std.Io.Writer, failure: ?selection_pipe.Failure) !void { const fail = failure orelse { - // No diagnosis at all: nobody ran it. The detached daemon, the - // browser leave `pipe` null on purpose. + // No diagnosis at all: nobody ran it. The detached daemon leaves + // `pipe` null on purpose. return w.writeAll("this session cannot run filters\n"); }; switch (fail.kind) { diff --git a/src/Places.zig b/src/Places.zig index 037b50be..0ed64ae7 100644 --- a/src/Places.zig +++ b/src/Places.zig @@ -49,7 +49,7 @@ pub const max_hits = 1 << 20; /// What one frame spends finding places: about 4 ms on the clock, checked /// between pieces of the text; mvzr's steps (Regex.budget is about 300 ms /// of them, so this is about 5 ms), which bound one slow piece; and bytes -/// read, the bound where there is no clock (the web). +/// read, the bound where there is no clock. pub const frame_ns: u64 = 4 * std.time.ns_per_ms; pub const frame_steps: u64 = regexp.Regex.budget / 64; pub const frame_bytes: usize = 8 << 20; diff --git a/src/Store.zig b/src/Store.zig index 02e5f83f..b1e8abd9 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -121,7 +121,6 @@ pub fn clone(s: *const Store, gpa: std.mem.Allocator) Store { /// Recent read at start: the file, and the store it replaced. pub fn load(s: *Store, p: *Pardes) void { const path = s.path orelse return; - if (comptime !pardes.hosted) return; s.loaded = true; s.refresh(p); // ponytail: the store this file replaced (until 2026-11-05), a log @@ -151,7 +150,6 @@ pub fn load(s: *Store, p: *Pardes) void { /// the file, read. One stat when nothing changed. pub fn refresh(s: *Store, p: *Pardes) void { const path = s.path orelse return; - if (comptime !pardes.hosted) return; if (!s.loaded) return; const io = ioOf(); const st = host(Dir.statFile, .{ cwd(), io, path, Dir.StatFileOptions{} }) catch return; @@ -181,11 +179,11 @@ fn read(s: *Store, p: *Pardes, file: File) void { /// end (`wait`: the lock is waited for there, never in a step). pub fn flush(s: *Store, p: *Pardes, wait: bool) void { if (!p.recent.dirty) return; - if (s.path) |path| if (comptime pardes.hosted) { + if (s.path) |path| { if (!s.loaded) return; // Another session's lock: the next step tries again. if (!s.write(p, path, wait)) return; - }; + } // Written, or nowhere to write it (or the disk refused it: kept for // no one, as before). for (p.recent.entries.items) |*e| e.changed = false; @@ -421,7 +419,6 @@ fn fileSize(path: []const u8) u64 { } test "store: two windows share Recent, each reading the other's writes on use; a busy lock delays, never loses" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const path = try testPath(&tmp); @@ -467,7 +464,6 @@ test "store: two windows share Recent, each reading the other's writes on use; a } test "store: Recent's file holds the newest 200, the newest first, and a window started on it reads them so" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const path = try testPath(&tmp); @@ -494,7 +490,6 @@ test "store: Recent's file holds the newest 200, the newest first, and a window } test "store: a foreign file never stops pardes: its lines that are Recent's are read, the next write mends it" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const path = try testPath(&tmp); @@ -512,7 +507,6 @@ test "store: a foreign file never stops pardes: its lines that are Recent's are } test "store: the store Recent's file replaced is read once, its newest records first, over the file's list" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const path = try testPath(&tmp); @@ -545,7 +539,6 @@ test "store: the store Recent's file replaced is read once, its newest records f } test "store: this session keeps its newest 64 closed panes" { - if (comptime !pardes.hosted) return; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); defer p.deinit(); var serial: u32 = 0; @@ -566,7 +559,6 @@ test "store: this session keeps its newest 64 closed panes" { } test "store: a closed pane comes back where it was, its rows from the pane that took them, nothing else moving; Panes lists it, marked" { - if (comptime !pardes.hosted) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const path = try testPath(&tmp); diff --git a/src/Stream.zig b/src/Stream.zig index 7f5e9162..dabc283c 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -458,7 +458,7 @@ pub fn parseFor(p: *Pardes, id: usize) void { // Here and now: a small text, a host with no workers. var got: Collect = .{ .gpa = p.gpa }; defer got.batches.deinit(p.gpa); - parseWork(if (comptime pardes.hosted) std.Io.Threaded.global_single_threaded.io() else std.Io.failing, job, &got, Collect.take); + parseWork(std.Io.Threaded.global_single_threaded.io(), job, &got, Collect.take); for (got.batches.items) |*b| { receive(p, b); b.deinit(p.gpa); diff --git a/src/builtins.zig b/src/builtins.zig index 5dae567a..2f51d81b 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -17,7 +17,7 @@ const limits = @import("memory.zig").limits; /// What this build's own frontend draws and its host does: the render's. pub const frontend: config.Runtime.Capabilities = .{ .font_picker = pardes.font_picker, - .panel_transitions = pardes.hosted, + .panel_transitions = true, .scene_shaders = pardes.platform == .gui or pardes.platform == .macos, // The tty's font belongs to its emulator. .tagline_font_size = pardes.platform != .tui, @@ -727,12 +727,12 @@ pub const Restore = struct { // The file it reads, whole (`~`, the DumpDir, the directory it runs // in): what the log's `restore` record and every message name. var full_buf: [4096]u8 = undefined; - const path = if (comptime pardes.hosted) @import("fs.zig").restorePath(typed, c.p.settings.dump_dir.get(), &full_buf) else typed; + const path = @import("fs.zig").restorePath(typed, c.p.settings.dump_dir.get(), &full_buf); if (path.len > c.p.restore_buf.len) return c.p.reportFailure(c.id, "Restore: that name is too long"); // A dump that cannot be read is said now, and fails a ctl write: the // host reads it only after this step, where nobody hears. First, // so a Restore that could never happen spends no warning. - if (comptime pardes.hosted) { + { const bytes = @import("fs.zig").readRestore(c.p.gpa, path, c.p.settings.dump_dir.get()) catch |err| { var buf: [limits.host_path_cap + 64]u8 = undefined; var words: [128]u8 = undefined; @@ -799,7 +799,6 @@ pub const Mount = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub const requires_arg = true; - pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { var args = std.mem.tokenizeAny(u8, c.arg orelse "", " \t"); const e_args = "wrong #args in control message \"Mount\": Mount name dial"; @@ -841,7 +840,6 @@ pub const Unmount = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub const requires_arg = true; - pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { var args = std.mem.tokenizeAny(u8, c.arg orelse "", " \t"); const name = args.next() orelse return c.p.reportError(c.id, "Unmount name", error.MissingArgument); @@ -894,7 +892,6 @@ pub const ThemeFile = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub const requires_arg = true; - pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { var home_buf: [4096]u8 = undefined; const arg = pardes.filesystem.expandHome(std.mem.trim(u8, c.arg orelse return, " \t\r\n"), &home_buf); @@ -910,7 +907,6 @@ pub const ThemeFile = struct { /// Write the bundled themes into the config directory's themes, to edit. pub const DumpThemes = struct { pub const scope: Scope = .session; - pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (c.p.configDir() == null) { c.p.reportError(c.id, "dump themes", error.NoConfigDirectory); @@ -1116,7 +1112,7 @@ pub const Get = struct { const path = if (typed.len == 0) c.pane.file.?.path else std.fs.path.resolvePosix(c.p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), @import("fs.zig").expandHome(typed, &home_buf) }) catch return; // A file that is not there, or a directory, is said before unsaved // edits are asked about: there would be nothing to load over them. - if (comptime pardes.hosted) if (typed.len > 0) if (@import("fs.zig").localPath(path)) |local| { + if (typed.len > 0) if (@import("fs.zig").localPath(path)) |local| { var said: [320]u8 = undefined; const kind = exec.kindOf(local); if (kind == null or kind.? == .directory) @@ -1177,7 +1173,7 @@ pub const Incl = struct { return p.reportFailure(c.id, std.fmt.bufPrint(&said, "Incl: invalid directory: {s} is relative", .{shown}) catch "Incl: invalid directory"); var home_buf: [4096]u8 = undefined; const expanded = @import("fs.zig").expandHome(dir_word, &home_buf); - if (comptime pardes.hosted) if (@import("fs.zig").localPath(expanded)) |local| if (exec.kindOf(local) != .directory) + if (@import("fs.zig").localPath(expanded)) |local| if (exec.kindOf(local) != .directory) return p.reportFailure(c.id, if (exec.kindOf(local) != null) std.fmt.bufPrint(&said, "Incl: not a directory: {s}", .{shown}) catch "Incl: not a directory" else @@ -1431,14 +1427,14 @@ pub const Term = struct { const arg = std.mem.trim(u8, c.arg orelse "", " \t"); // A shell that is not there is said, where the host would quietly // start its fallback in its place. - if (comptime pardes.hosted) if (arg.len > 0) { + 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| { var said: [340]u8 = undefined; return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Term: {s}", .{refused}) catch "Term: no such shell"); } - }; + } const pane = exec.spawnTty(c.p, c.id) orelse return; if (arg.len > 0) pane.shell = c.p.gpa.dupe(u8, arg) catch null; } diff --git a/src/colors.zig b/src/colors.zig index 47af08b4..90ed7b76 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -11,7 +11,6 @@ const config = @import("config.zig"); const pdf_enabled = panes.Pdf.enabled; const platform = pardes.platform; const theme_animation = @import("pardes_config").theme_animation; -const hosted = pardes.hosted; const MAX_PANES = pardes.MAX_PANES; const BOX_H = pardes.BOX_H; const Pardes = pardes.Pardes; @@ -723,7 +722,6 @@ fn nextThemeFileGeneration(p: *Pardes) u32 { } pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { - if (comptime !hosted) return; const input = std.mem.trim(u8, argument, " \t\r\n"); if (input.len == 0 or !std.mem.endsWith(u8, input, ".zon")) { p.reportError(id, "theme file", error.InvalidThemePath); @@ -970,7 +968,6 @@ pub fn setThemeIndex(p: *Pardes, index: usize) void { } test "a theme file that cannot be read is named in the failure" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); requestThemeFile(p, 0, "/nowhere/mine.zon"); @@ -980,7 +977,6 @@ test "a theme file that cannot be read is named in the failure" { } test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .config_dir = "/tmp/pardes-config", diff --git a/src/config.zig b/src/config.zig index f84f438c..b12630e9 100644 --- a/src/config.zig +++ b/src/config.zig @@ -203,12 +203,10 @@ pub const leader_path = paths: { } if (builtins.EffectCode.enabled) table.set(.EffectCode, null); if (builtins.TreeContext.enabled) table.set(.TreeContext, null); - if (pardes.hosted) { - table.set(.ThemeFile, null); - table.set(.DumpThemes, null); - table.set(.Mount, null); - table.set(.Unmount, null); - } + table.set(.ThemeFile, null); + table.set(.DumpThemes, null); + table.set(.Mount, null); + table.set(.Unmount, null); if (pardes.can_attach) { table.set(.Detach, "sD"); table.set(.Adopt, null); @@ -448,11 +446,11 @@ pub fn defaultShell() []const u8 { } fn defaultShellHost() []const u8 { - if (comptime pardes.hosted) if (std.c.getenv("SHELL")) |s| { + if (std.c.getenv("SHELL")) |s| { const shell = std.mem.span(s); // One that is not there, or not executable, is no shell: /bin/sh. if (shell.len > 0 and std.c.access(s, std.c.X_OK) == 0) return shell; - }; + } return "/bin/sh"; } @@ -1504,8 +1502,6 @@ pub const Runtime = struct { } if (find("WindowOpacity").?.enabled(context.capabilities)) try out.print("# Window opacity change pending: {s}\n", .{onOff(state.window_opacity_pending)}); - if (context.capabilities.tagline_font_size and !find("TaglineSize").?.enabled(context.capabilities)) - try out.writeAll("# Tagline size: build-time only\n"); if (context.startup_config_path) |path| try out.print("# Startup config: {s}\n", .{path}) else @@ -1811,15 +1807,6 @@ pub const Runtime = struct { // ...and every one after it a `#` line, which runs as nothing. var info = std.mem.splitScalar(u8, std.mem.trimEnd(u8, defaults_report[words.len + 2 ..], "\n"), '\n'); while (info.next()) |each| try std.testing.expect(std.mem.startsWith(u8, each, "# ")); - - defaults_context.platform = "web"; - defaults_context.capabilities.panel_transitions = false; - defaults_context.capabilities.tagline_font_size = true; - out = .fixed(&storage); - try writeReport(&out, defaults_context); - const web_report = storage[0..out.end]; - try std.testing.expect(std.mem.indexOf(u8, web_report, "# PanelSlide unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, web_report, "# Tagline size: build-time only\n") != null); } }; diff --git a/src/draw.zig b/src/draw.zig index e28c9f9d..a7498cab 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -699,7 +699,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { // The probe's last second (FrameStats); under a virtual clock its // real-time numbers would make every golden of this box differ. var frames_buf: [96]u8 = undefined; - const virtual = !pardes.hosted or std.c.getenv("PARDES_TEST_CLOCK") != null; + const virtual = std.c.getenv("PARDES_TEST_CLOCK") != null; const timings = if (virtual) "frame virtual clock\n" else p.frames.summary(&frames_buf); const text = std.fmt.bufPrint( &ov_buf, diff --git a/src/dump.zig b/src/dump.zig index 6bdfb7d4..a35a9fab 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -54,7 +54,6 @@ fn uniqueIn(buf: *[1024:0]u8, dir: []const u8, base: []const u8) ?[:0]const u8 { std.fmt.bufPrintSentinel(buf, "{s}/{s}.dump", .{ dir, base }, 0) else std.fmt.bufPrintSentinel(buf, "{s}/{s}-{d}.dump", .{ dir, base, n }, 0)) catch return null; - if (comptime !pardes.hosted) return path; if (std.c.access(path.ptr, std.c.F_OK) != 0) return path; } return null; @@ -72,10 +71,8 @@ test "two dumps in one second get names of their own" { try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-x.dump", .data = "" }); try std.testing.expect(std.mem.endsWith(u8, uniqueIn(&buf, dir, "pardes-x").?, "/pardes-x-2.dump")); } -/// The host's environment; a freestanding core (the web's) has none -/// and no libc to ask, so only a DumpDir with no `~/` names a directory there. +/// The host's environment. fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { - if (builtin.os.tag == .freestanding) return null; return std.c.getenv(name); } @@ -90,8 +87,7 @@ pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { var fba_buf: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&fba_buf); var cwd_buf: [1024]u8 = undefined; - // No libc on the web: there a relative one is from `/`. - const cwd: []const u8 = if (comptime !pardes.hosted) "/" else if (std.fs.path.isAbsolute(raw)) "/" else if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]const u8, @ptrCast(c))) else "/"; + const cwd: []const u8 = if (std.fs.path.isAbsolute(raw)) "/" else if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]const u8, @ptrCast(c))) else "/"; const resolved = std.fs.path.resolvePosix(fba.allocator(), &.{ cwd, raw }) catch return null; return std.fmt.bufPrint(buf, "{s}", .{resolved}) catch null; } @@ -157,7 +153,6 @@ const SessionLoad = walk.Load(&.{ Pardes, []const filesystem.Mount, OnDisk, []co const OnDisk = [MAX_PANES]bool; fn onDisk(pane: *const pardes.panes.Pane) bool { - if (comptime !pardes.hosted) return false; const f = pane.file orelse return false; if (f.output != null) return false; const local = filesystem.localPath(f.path) orelse return false; @@ -464,13 +459,13 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool if (pane.terminal != null) { // A command pane comes back finished, showing what it said: its // command is not run again. A host that runs shells starts one - // under the history in the old one's directory; the web shell and - // an isolated build only show it. + // under the history in the old one's directory; an isolated build + // only shows it. if (pane.command != null) { pane.command_done = true; return; } - if (comptime platform == .web or isolated) return; + if (comptime isolated) return; if (pane.cwdSlice().len > effect_path_cap) return; pardes.panes.terminal.reviveShell(pane); p.emitSpawn(id, pane.serial, pane.cwdSlice()); @@ -489,8 +484,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool // Its file gone from disk since the dump: its text is nowhere else, so // it is said deleted, and Del, Exit and Restore ask first. One never on // disk (a name not yet saved) comes back as it was. - // (A host with no disk of its own, the web's, asks nothing.) - if (comptime pardes.hosted) if (was_on_disk and !onDisk(pane)) pardes.panes.File.deleted(p, @intCast(id)); + if (was_on_disk and !onDisk(pane)) pardes.panes.File.deleted(p, @intCast(id)); } // ---- one pane to and from a dump: the store's, a handover's ---- diff --git a/src/edit.zig b/src/edit.zig index 99c6d306..84db62c0 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -2013,7 +2013,6 @@ test "flat text replacement preserves a terminal fragment origin and direction" } test "only the SPC clipboard commands cross to the system clipboard" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index 8bde605b..517f2e8d 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -76,7 +76,6 @@ const World = struct { const f = ninep_pane.fileOf(pane) orelse continue; if (std.mem.eql(u8, f.path, path)) return true; } - if (comptime !pardes.hosted) return true; const local = filesystem.localPath(path) orelse return true; if (@import("exec.zig").kindOf(local) == .directory) return said(bool, why, "B: {s} is a directory", .{path}) orelse false; var buf: [4096]u8 = undefined; @@ -93,7 +92,7 @@ const World = struct { fn open(ctx: *anyopaque, path: []const u8, why: *sam.Why) ?sam.File { const w: *World = @ptrCast(@alignCast(ctx)); const p = w.p; - if (comptime pardes.hosted) if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(local) == .directory) + if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(local) == .directory) return said(sam.File, why, "B: {s} is a directory", .{path}); // A look opens it, or finds it open, where a look would; the // keyboard stays where the Edit ran. @@ -113,7 +112,7 @@ const World = struct { fn read(ctx: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *sam.Why) ?[]const u8 { const w: *World = @ptrCast(@alignCast(ctx)); - if (comptime pardes.hosted) if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(local) == .directory) + if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(local) == .directory) return said([]const u8, why, "{s} is a directory", .{path}); const bytes = filesystem.read(w.p, path) catch |err| { // In the words Get says them (builtins.Get). @@ -237,7 +236,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 = if (comptime pardes.hosted) @import("host_io.zig").commandEnv(arena, pane.serial, !p.opts.nested) catch &.{} else &.{}, + .env = @import("host_io.zig").commandEnv(arena, pane.serial, !p.opts.nested) catch &.{}, }; keep = true; p.pipe.edit_run = pd; @@ -559,7 +558,6 @@ test "the held write asked again is parked again, then answered once, and a flus } test "Edit's < | and > with a real shell: a command per address, > printed to +Errors" { - if (comptime !pardes.hosted) return error.SkipZigTest; const p = try th.withFile(testing.allocator, "one two\nthree\n"); defer p.deinit(); const ctl = tree.Node.of(th.serialOf(p), .ctl); @@ -580,7 +578,6 @@ test "Edit's < | and > with a real shell: a command per address, > printed to +E } test "a failing command changes nothing and says why, its stderr in +Errors" { - if (comptime !pardes.hosted) return error.SkipZigTest; const p = try th.withFile(testing.allocator, "keep\n"); defer p.deinit(); const ctl = tree.Node.of(th.serialOf(p), .ctl); @@ -609,7 +606,7 @@ test "an Edit whose file is edited while its commands run is refused whole" { } test "X over open files, w, e, r, f, B and D on panes and the disk" { - if (comptime !pardes.hosted or !filesystem.platform_has_fs) return error.SkipZigTest; + if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; const gpa = testing.allocator; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); @@ -686,7 +683,7 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" { } test "an Edit's w to a file changed on disk is refused once, as Save is, and the others are written" { - if (comptime !pardes.hosted or !filesystem.platform_has_fs) return error.SkipZigTest; + if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "a\n" }); @@ -722,7 +719,7 @@ test "an Edit's w to a file changed on disk is refused once, as Save is, and the } test "an Edit with no command runs beside one whose commands run, unless it touches what that one changes" { - if (comptime !pardes.hosted or !filesystem.platform_has_fs) return error.SkipZigTest; + if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(testing.io, .{ .sub_path = "other.txt", .data = "x\n" }); @@ -783,7 +780,7 @@ test "a session that ends while an Edit's commands run lets the Edit go" { } test "e and r say a file that cannot be read as Get says it" { - if (comptime !pardes.hosted or !filesystem.platform_has_fs) return error.SkipZigTest; + if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const ctl = tree.Node.of(th.serialOf(p), .ctl); diff --git a/src/effect_sources.zig b/src/effect_sources.zig index 02d1f87d..39d86a1d 100644 --- a/src/effect_sources.zig +++ b/src/effect_sources.zig @@ -44,7 +44,6 @@ pub const files = switch (backend) { .{ .path = "src/macos/Sources/ScenePostprocessor.swift", .contents = @embedFile("macos/Sources/ScenePostprocessor.swift") }, .{ .path = "shaders/crt.ci.metal", .contents = @embedFile("effect-source-crt.ci.metal") }, }, - .web => [_]filesystem.Source{}, }; pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { @@ -53,7 +52,6 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { .tui => &.{ "src/layout.zig", "src/pardes.zig", "src/tui/panel_compositor.zig" }, .gui => &.{ "src/layout.zig", "src/pardes.zig", "src/gui/gui.zig", ui_vertex_path, ui_fragment_path, image_vertex_path, image_fragment_path }, .macos => &.{ "src/layout.zig", "src/pardes.zig", "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, - .web => null, }, .scene => |effect| switch (backend) { .gui => switch (effect) { @@ -63,7 +61,7 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { .grain => &.{ "src/gui/Post.zig", "src/gui/gui.zig", post_vertex_path, post_grain_path }, }, .macos => &.{ "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, - .tui, .web => null, + .tui => null, }, else => null, }; diff --git a/src/exec.zig b/src/exec.zig index ee9e8ddf..0c559382 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -22,7 +22,6 @@ const python_lang = blk: { }; const pdf_enabled = panes.Pdf.enabled; const font_picker = pardes.font_picker; -const hosted = pardes.hosted; const fonts = pardes.fonts; const Pane = panes.Pane; const MAX_COLS = pardes.MAX_COLS; @@ -436,7 +435,6 @@ fn refusedPlacement(p: *Pardes, id: usize) bool { /// Whether a shell would be started in `dir` and `dir` is not there: asked /// only of a host that starts shells, and only of a local path. pub fn missingDir(p: *Pardes, dir: []const u8) bool { - if (comptime !hosted) return false; if (p.host.vtable.spawn == null) return false; // A peer's directory (`/n/peer/x`) is no directory on this host, where // the shell would start: no command or terminal runs there, and none @@ -448,8 +446,6 @@ pub fn missingDir(p: *Pardes, dir: []const u8) bool { /// What `path` is on this host, null when it is not there; the turn out /// while it asks (it may be inside a mount this editor serves). pub fn kindOf(path: []const u8) ?std.Io.File.Kind { - // A freestanding build has no host to ask. - if (comptime !pardes.hosted) return null; var buf: [4096]u8 = undefined; const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null; return pardes.tape.site(.kind, null, kindHost, .{z}); @@ -721,12 +717,6 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi /// A pane reused keeps what it showed: the new command runs below a line /// naming it, as acme appends to +Errors and never clears it (util.c:213). fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { - // The web page starts no processes: a command pane there - // would say running for ever, and fill the slots. - if (comptime !hosted) { - p.reportFailure(from, "exec: not a builtin, and this build runs no commands"); - return null; - } if (line.len > command_max) { p.reportFailure(from, "exec: a command line is at most 1024 bytes"); return null; @@ -1059,12 +1049,10 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] var said: [320]u8 = undefined; return p.setMessage(p.active, std.fmt.bufPrint(&said, "Shell: the default again, {s} ($SHELL, else /bin/sh)", .{config.defaultShell()}) catch "Shell: the default again"); } - if (comptime pardes.hosted) { - var why: [320]u8 = undefined; - if (pardes.tape.value(.shell, @import("host_io.zig").Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { - var text: [340]u8 = undefined; - return p.reportFailure(p.active, std.fmt.bufPrint(&text, "Shell: {s}", .{refused}) catch "Shell: no such shell"); - } + var why: [320]u8 = undefined; + if (pardes.tape.value(.shell, @import("host_io.zig").Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { + var text: [340]u8 = undefined; + return p.reportFailure(p.active, std.fmt.bufPrint(&text, "Shell: {s}", .{refused}) catch "Shell: no such shell"); } if (!p.settings.apply(setting, want)) p.reportFailure(p.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); }, diff --git a/src/file_watch.zig b/src/file_watch.zig index e8155bb9..ea8115bc 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -828,7 +828,7 @@ test "file identity changes for in-place and rename-over writes" { } test "theme watch reloads valid ZON and keeps the last theme across a bad save" { - if (comptime !supported or pardes.platform == .web) return; + if (comptime !supported) return; const io = std.testing.io; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); @@ -293,7 +293,6 @@ pub fn validMountName(name: []const u8) bool { } test "/os refuses a rename or a mode change as not permitted, in words, and still truncates to zero" { - if (comptime !pardes.hosted) return error.SkipZigTest; const p = try th.withFile(std.testing.allocator, "x\n"); defer p.deinit(); var tmp = std.testing.tmpDir(.{}); @@ -815,7 +814,6 @@ pub fn dotRelative(word: []const u8) bool { /// Restore, a forwarded `pardes ~/x`. The path itself when there is no /// `~` to expand, or no home for it. pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { - if (comptime !pardes.hosted) return path; if (path.len == 0 or path[0] != '~') return path; // Home as the session that recorded found it (src/tape.zig). return pardes.tape.value(.env, expandHomeHost, .{ path, out }); @@ -1096,10 +1094,7 @@ fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source { return null; } -pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { - .tui, .gui, .macos => true, - .web => false, -}; +pub const platform_has_fs = !pardes.isolated; pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", @@ -1445,7 +1440,7 @@ pub const Namespace = struct { pub fn mount(st: *Namespace, gpa: std.mem.Allocator, name: []const u8, dial: []const u8) !void { if (!validMountName(name)) return error.BadMountName; - if (comptime pardes.hosted) try ninep_io.Client.validateDial(dial); + try ninep_io.Client.validateDial(dial); if (dial.len == 0 or std.mem.indexOfScalar(u8, dial, 0) != null) return error.BadDial; for (st.mounts.items) |entry| if (std.mem.eql(u8, name, entry.name)) return error.AlreadyMounted; if (st.mounts.items.len == max_mounts) return error.TooManyMounts; @@ -1487,7 +1482,7 @@ pub fn unmount(p: *Pardes, name: []const u8) !void { (path.len == prefix.len or path[prefix.len] == '/')) return error.MountInUse; } const removed = p.fs.mounts.orderedRemove(index); - if (comptime pardes.hosted) ninep_io.Client.forget(removed.dial); + ninep_io.Client.forget(removed.dial); p.gpa.free(removed.name); p.gpa.free(removed.dial); return; @@ -1504,7 +1499,7 @@ test "the tree's README lists src/ only when the build serves it" { } test "a write open(2) refuses says its errno in words" { - if (comptime @import("builtin").os.tag != .linux or !pardes.hosted) return error.SkipZigTest; + if (comptime @import("builtin").os.tag != .linux) return error.SkipZigTest; // /proc takes no new file: ENOENT, which used to read "open failed". try std.testing.expectError(error.NoSuchFileOrDirectory, writeFile("/proc/pardes-no-such-file", "x")); var words: [128]u8 = undefined; diff --git a/src/image.zig b/src/image.zig index 09522612..aeb0423a 100644 --- a/src/image.zig +++ b/src/image.zig @@ -726,10 +726,8 @@ var started = false; extern fn stbi_info_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int) c_int; -/// stb_image's header reader; a freestanding build has no stb_image (its -/// decoder is the shim in src/web/zstbi.zig), so no header reads as one. +/// stb_image's header reader. fn stbiInfo(bytes: []const u8, w: *c_int, h: *c_int, c: *c_int) bool { - if (comptime !pardes.hosted) return false; return stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), w, h, c) == 1; } @@ -907,9 +905,6 @@ const GridKey = struct { ascii: bool = true, }; -/// A host's thread; a freestanding build has none to have. -const Decoder = if (pardes.hosted) std.Thread else void; - pub const State = struct { /// What the replay digest leaves out (src/walk.zig): the picture as /// decoded from its bytes, off the loop as the render first wants it, @@ -928,12 +923,12 @@ pub const State = struct { grid: GlyphArt.Grid = .{ .cells = &.{}, .cols = 0, .rows = 0 }, grid_key: GridKey = .{}, /// The decode under way off the loop (ensureDecoded), and its answer. - decoder: ?Decoder = null, + decoder: ?std.Thread = null, decoded: std.atomic.Value(bool) = .init(false), answer: ?Decoded = null, pub fn deinit(state: *State, gpa: std.mem.Allocator) void { - if (comptime pardes.hosted) if (state.decoder) |t| t.join(); + if (state.decoder) |t| t.join(); if (state.answer) |a| gpa.free(a.rgba); gpa.free(state.path); if (state.rgba.len > 0) gpa.free(state.rgba); @@ -995,11 +990,11 @@ pub fn tagPrefix(arena: std.mem.Allocator, state: *const State, glyphs: bool) ![ /// docs' screenshot: all of it once on the frame before). /// ponytail: a thread a picture; a pool if many open at once. fn ensureDecoded(p: *pardes.Pardes, state: *State) void { - if (comptime pardes.hosted) if (state.decoder) |t| { + if (state.decoder) |t| { if (!state.decoded.load(.acquire)) return; t.join(); state.decoder = null; - }; + } if (state.answer) |decoded| { state.answer = null; state.rgba = decoded.rgba; @@ -1015,7 +1010,7 @@ fn ensureDecoded(p: *pardes.Pardes, state: *State) void { st.decoded.store(true, .release); } }; - if (comptime pardes.hosted and !builtin.is_test) { + if (comptime !builtin.is_test) { if (std.Thread.spawn(.{}, Work.run, .{ p.image_gpa, state })) |t| { state.decoder = t; return; diff --git a/src/look.zig b/src/look.zig index f47f0b15..634310f1 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1223,7 +1223,7 @@ fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void { var cut: [miss_path_cap + "…".len]u8 = undefined; // Not there, on a peer's mount as on this host: a miss, the write // answered, as any path to no file is. - const remote_missing = if (comptime pardes.hosted) err == error.Remote and std.mem.indexOf(u8, @import("9p_io.zig").Client.lastSaid(), "not exist") != null else false; + const remote_missing = err == error.Remote and std.mem.indexOf(u8, @import("9p_io.zig").Client.lastSaid(), "not exist") != null; if (err == error.FileNotFound or err == error.NotFound or remote_missing) return missed(p, id, "{s}: no such file", .{missText(path, &cut)}); var said: [miss_path_cap + 16]u8 = undefined; @@ -1373,7 +1373,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: if (filesystem.dotRelative(trimmed)) { const dir = Pardes.paneDir(pane); var said: [4200]u8 = undefined; - const gone = if (comptime pardes.hosted) if (filesystem.localPath(dir)) |local| exec.kindOf(local) != .directory else false else true; + const gone = if (filesystem.localPath(dir)) |local| exec.kindOf(local) != .directory else false; if (gone) return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); // A file not there is a miss, as `x` and `/abs/x` are: said and // logged, the write answered with nothing. @@ -1411,7 +1411,6 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: /// goes when it succeeds (exec.commandDone). // ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. fn lookCommit(p: *Pardes, id: usize, pane: *Pane, word: []const u8) bool { - if (comptime !pardes.hosted) return false; if (!isCommitHash(word)) return false; var dir = filesystem.localPath(Pardes.paneDir(pane)) orelse return false; while (true) { @@ -1817,7 +1816,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { .dir => |dir| { // A directory that is not there (the pane's own, gone): said, // ENOENT, no terminal made in it. - if (comptime pardes.hosted) if (filesystem.localPath(dir)) |local| if (exec.kindOf(local) != .directory) { + if (filesystem.localPath(dir)) |local| if (exec.kindOf(local) != .directory) { var said: [4200]u8 = undefined; return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); }; diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index eccd3ac6..e307a40d 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -89,24 +89,19 @@ test "an explain request narrates the query named in its arg, a definition by de } /// Every language, Zig's (zls) included, through the protocol client, which -/// runs its server as a child process. None on the web. -const has_client = switch (@import("pardes_config").platform) { - .web => false, - else => true, -}; -const client = if (has_client) @import("lsp_client.zig") else void; +/// runs its server as a child process. +const client = @import("lsp_client.zig"); -pub const supports: std.EnumSet(Kind) = if (has_client) client.supports else .empty; +pub const supports: std.EnumSet(Kind) = client.supports; pub fn speaks(path: []const u8) bool { - return has_client and client.speaks(path); + return client.speaks(path); } /// Every question, a file no server speaks for included: the client says /// why it asked nothing, where an empty answer would read as nothing found. pub fn query(io: std.Io, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { - if (has_client) return client.query(io, arena, req, out); - try none(out, "no language server here", .{}); + return client.query(io, arena, req, out); } /// The one line the client answers with when it cannot answer at all, and @@ -117,7 +112,7 @@ pub fn none(out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) std.Io // Called on server reader threads; the sink must copy text before returning. pub fn setStatusSink(ctx: ?*anyopaque, cb: ?*const fn (ctx: ?*anyopaque, text: []const u8) void) void { - if (has_client) client.setStatusSink(ctx, cb); + client.setStatusSink(ctx, cb); } pub fn rel(base: []const u8, path: []const u8) []const u8 { @@ -199,7 +194,6 @@ test "LSP encoders report every insufficient output capacity" { } test "a question for a file no language server speaks for says why rather than find nothing" { - if (!has_client) return; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var buf: [256]u8 = undefined; diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 4ea4475a..23cd0f78 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -79,8 +79,8 @@ enum Trackpad { static let forceClickButton: pardes_mouse_button_e = PARDES_MOUSE_RIGHT } -// Matches bg_default/fg_default in src/gui/gui.zig and DEFAULT_FG/DEFAULT_BG in -// src/web/app.mjs. Three shells render the same core; if these drift, comparing +// 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 diff --git a/src/macos/pardes.h b/src/macos/pardes.h index 33db3bb5..62ae5218 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -10,7 +10,7 @@ // Swift owns NSApplication, the window, input translation, and drawing. // // There is exactly one core per process, so there are no handles: the state is -// a file-scoped singleton, same as src/web.zig. Every function below must be +// a file-scoped singleton. Every function below must be // called from the main thread. The one exception is the `wakeup` callback, // which fires from a pty reader thread. @@ -28,8 +28,7 @@ extern "C" { // ---------------------------------------------------------------- frame // One rendered cell. Mirrors pardes.Cell (src/pardes.zig) flattened for the -// wire; the identical encoding is spelled a second time for the browser in -// src/web.zig as WebCell. +// wire. typedef struct { // UTF-8 grapheme, `len` bytes. The core caps graphemes at seven bytes; the // eighth is always zero so a debugger prints something sensible. diff --git a/src/main.zig b/src/main.zig index a79a9716..4a3fbe8d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5,18 +5,8 @@ const ninep_io = @import("9p_io.zig"); const daemon = @import("daemon.zig"); const upgrade = @import("upgrade.zig"); -const is_emscripten = builtin.os.tag == .emscripten; - -extern "c" fn emscripten_console_error(utf8: [*:0]const u8) void; - -pub const std_options_debug_threaded_io: ?*std.Io.Threaded = if (is_emscripten) - null -else - std.Io.Threaded.global_single_threaded; -pub const std_options_debug_io: std.Io = if (is_emscripten) - std.Io.failing -else - std_options_debug_threaded_io.?.io(); +pub const std_options_debug_threaded_io: ?*std.Io.Threaded = std.Io.Threaded.global_single_threaded; +pub const std_options_debug_io: std.Io = std_options_debug_threaded_io.?.io(); // Every thread's alternate signal stack is a threadlocal that libc zeroes as // the thread starts, so std's 256 KiB made each 9P connection's thread cost @@ -42,7 +32,7 @@ fn logFn( std.log.defaultLog(level, scope, format, args); } -pub const panic = if (is_emscripten) std.debug.FullPanic(std.debug.defaultPanic) else std.debug.FullPanic(struct { +pub const panic = std.debug.FullPanic(struct { fn call(msg: []const u8, ret_addr: ?usize) noreturn { if (!recovering.swap(true, .seq_cst)) { pardes.replica.dying(); @@ -55,7 +45,7 @@ pub const panic = if (is_emscripten) std.debug.FullPanic(std.debug.defaultPanic) var recovering: std.atomic.Value(bool) = .init(false); -pub const debug = if (is_emscripten) struct {} else struct { +pub const debug = struct { pub fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: anytype) noreturn { if (!recovering.swap(true, .seq_cst)) { pardes.replica.dying(); @@ -327,9 +317,7 @@ const nested_text = \\ ; -// The browser runtime calls a C main (exported below); everything else keeps -// the std.process.Init entry. -pub const main = if (is_emscripten) webMain else nativeMain; +pub const main = nativeMain; // glibc's struct termios is 60 bytes, Zig 0.17's std.c.termios the kernel's // 44: libc's tcgetattr wrote 16 bytes past every Zig caller's (vaxis's @@ -372,28 +360,6 @@ test "tcgetattr writes nothing past a Zig termios" { try std.testing.expectEqual(-1, std.c.tcgetattr(-1, &s.t)); } -comptime { - if (is_emscripten) @export(&emscriptenMain, .{ .name = "main" }); -} - -fn emscriptenMain(argc: c_int, argv: [*]?[*:0]u8) callconv(.c) c_int { - _ = argc; - _ = argv; - webMain() catch |err| { - var buf: [128]u8 = undefined; - const msg = std.fmt.bufPrintSentinel(&buf, "pardes web init failed: {t}", .{err}, 0) catch "pardes web init failed"; - emscripten_console_error(msg.ptr); - return 1; - }; - return 0; -} - -// no argv in the browser: options stay default, state comes from the dump, and -// there is no session to attach to — a browser tab has no unix socket. -fn webMain() !void { - try @import("gui/gui.zig").run(.{}, .{}, false); -} - // init.gpa, what the tui, gui and detached shells allocate from, is their // own fixed arena (memory.host) in a release build, spilling to libc's // malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start @@ -850,7 +816,7 @@ fn nativeMain(std_init: std.process.Init) !void { else => return err, }, .gui => try @import("gui/gui.zig").run(init, opts, headless), - .web, .macos => unreachable, + .macos => unreachable, } daemon.tellStubExit(0); } diff --git a/src/memory.zig b/src/memory.zig index c4e0e6fd..6f6c6191 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -3,7 +3,6 @@ const builtin = @import("builtin"); const walk = @import("walk.zig"); const config = @import("pardes_config"); -const reduced_target = builtin.os.tag == .freestanding; const KiB = 1024; const MiB = 1024 * KiB; @@ -47,19 +46,19 @@ pub const limits = struct { /// they are sized for the worst case: the core holds a 256 MiB file, its /// edit's copy and its undo. pub const arena = struct { - pub const pardes = if (reduced_target) 8 * MiB else 1024 * MiB; - pub const frame = if (reduced_target) 4 * MiB else 64 * MiB; - pub const lsp = if (reduced_target) 0 else 512 * MiB; + pub const pardes = 1024 * MiB; + pub const frame = 64 * MiB; + pub const lsp = 512 * MiB; /// What a native shell allocates itself (`host`): its screen, the /// bytes its ptys read, its 9P connections, its pipe jobs. - pub const host = if (reduced_target) 0 else 512 * MiB; - pub const tree_sitter = if (reduced_target) 4 * MiB else 256 * MiB; - pub const image = if (reduced_target) 64 * KiB else 256 * MiB; - pub const pdf = if (reduced_target or !config.mupdf) 64 * KiB else 512 * MiB; + pub const host = 512 * MiB; + pub const tree_sitter = 256 * MiB; + pub const image = 256 * MiB; + pub const pdf = if (!config.mupdf) 64 * KiB else 512 * MiB; /// One language query's working memory (its parsed answers, the rows /// it writes): a hard bound, nothing spills. Callstack walks until it /// would leave less than its rendering reserve. - pub const lsp_query = if (reduced_target) 0 else 256 * MiB; + pub const lsp_query = 256 * MiB; }; }; @@ -75,50 +74,6 @@ pub const Allocators = struct { pdf: Allocator, }; -/// A freestanding target's arena (the web's): `std.heap.StackFallbackAllocator` -/// with the buffer taken through its lock-free interface. A -/// FixedBufferAllocator frees only its last block, so once a big operation -/// fills the buffer everything after spills; a native target uses `Pages`. The core's allocator is used from two threads: a 9P -/// connection task answers a request while the editor's own thread is out -/// in a syscall that allocates (`readFileLimit`, `grep`; see `pardes.turn`). -/// The buffer is a separate zeroed global, not a field: an `undefined` one is -/// written into a Debug binary as 0xAA filler, 160 MB of file for the five -/// arenas, where a zeroed one is .bss and costs nothing. -const SharedStackFallback = struct { - buffer: []u8, - fallback_allocator: Allocator = undefined, - fixed: std.heap.FixedBufferAllocator = undefined, - - fn get(self: *@This()) Allocator { - self.fixed = .init(self.buffer); - return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; - } - - fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - return self.fixed.threadSafeAllocator().rawAlloc(len, alignment, ra) orelse - self.fallback_allocator.rawAlloc(len, alignment, ra); - } - - fn resize(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) bool { - const self: *@This() = @ptrCast(@alignCast(ctx)); - if (self.fixed.ownsPtr(buf.ptr)) return self.fixed.threadSafeAllocator().rawResize(buf, alignment, new_len, ra); - return self.fallback_allocator.rawResize(buf, alignment, new_len, ra); - } - - fn remap(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, new_len: usize, ra: usize) ?[*]u8 { - const self: *@This() = @ptrCast(@alignCast(ctx)); - if (self.fixed.ownsPtr(buf.ptr)) return self.fixed.threadSafeAllocator().rawRemap(buf, alignment, new_len, ra); - return self.fallback_allocator.rawRemap(buf, alignment, new_len, ra); - } - - fn free(ctx: *anyopaque, buf: []u8, alignment: std.mem.Alignment, ra: usize) void { - const self: *@This() = @ptrCast(@alignCast(ctx)); - if (self.fixed.ownsPtr(buf.ptr)) return self.fixed.threadSafeAllocator().rawFree(buf, alignment, ra); - return self.fallback_allocator.rawFree(buf, alignment, ra); - } -}; - /// One arena's fixed region on a native target, handed out in runs of 4 KiB /// granules to the general allocator above it (`Region.general`). A freed run /// is used again, and big ones go back to the system (`release`; `trim` @@ -285,20 +240,14 @@ const General = std.heap.DebugAllocator(.{ /// One arena: its region, the bitmap of its used granules, and the /// allocator over them. A native region is address space mapped once, at the /// first `init`, not .bss: gigabytes of .bss put static data out of reach of -/// x86-64's 32-bit offsets. A freestanding one is its .bss `buffer`. +/// x86-64's 32-bit offsets. const Region = struct { size: usize, bits: []u64, - buffer: []u8, pages: Pages = .{}, general: General = .init, - fallback: SharedStackFallback = undefined, fn init(r: *Region, spill: Allocator) Allocator { - if (reduced_target) { - r.fallback = .{ .buffer = r.buffer, .fallback_allocator = spill }; - return r.fallback.get(); - } // Without the mapping (an address-space limit) every block spills. const region = if (r.pages.region.len > 0) r.pages.region else if (std.heap.page_allocator.rawAlloc(r.size, .fromByteUnits(64 * KiB), @returnAddress())) |ptr| ptr[0..r.size] else @constCast(&[_]u8{}); sparse(region); @@ -309,7 +258,6 @@ const Region = struct { } fn trim(r: *Region) void { - if (reduced_target) return; std.Io.Threaded.mutexLockUncancelable(&r.general.mutex); defer std.Io.Threaded.mutexUnlock(&r.general.mutex); r.pages.trim(); @@ -318,43 +266,31 @@ const Region = struct { /// A fresh allocator in its place: a Debug deinit leaves 0xAA behind, /// its mutex too, which a later `trim` would wait on for good. fn deinit(r: *Region) bool { - if (reduced_target) return false; const leaked = r.general.deinit() == .leak; r.general = .{ .backing_allocator = r.pages.allocator() }; return leaked; } }; -/// Each arena's bitmap on a native target, its buffer on a freestanding one; -/// spelled out per arena: a generic returning the globals would share them -/// between two arenas of one size. +/// Each arena's bitmap, spelled out per arena: a generic returning the +/// globals would share them between two arenas of one size. fn bitsFor(size: usize) usize { - return if (reduced_target) 0 else size / Pages.granule / 64; -} -fn bufferFor(size: usize) usize { - return if (reduced_target) size else 0; + return size / Pages.granule / 64; } var pardes_bits: [bitsFor(limits.arena.pardes)]u64 = @splat(0); -var pardes_buffer: [bufferFor(limits.arena.pardes)]u8 = @splat(0); -var pardes_region: Region = .{ .size = limits.arena.pardes, .bits = &pardes_bits, .buffer = &pardes_buffer }; +var pardes_region: Region = .{ .size = limits.arena.pardes, .bits = &pardes_bits }; var frame_bits: [bitsFor(limits.arena.frame)]u64 = @splat(0); -var frame_buffer: [bufferFor(limits.arena.frame)]u8 = @splat(0); -var frame_region: Region = .{ .size = limits.arena.frame, .bits = &frame_bits, .buffer = &frame_buffer }; +var frame_region: Region = .{ .size = limits.arena.frame, .bits = &frame_bits }; var lsp_bits: [bitsFor(limits.arena.lsp)]u64 = @splat(0); -var lsp_buffer: [bufferFor(limits.arena.lsp)]u8 = @splat(0); -var lsp_region: Region = .{ .size = limits.arena.lsp, .bits = &lsp_bits, .buffer = &lsp_buffer }; +var lsp_region: Region = .{ .size = limits.arena.lsp, .bits = &lsp_bits }; var tree_sitter_bits: [bitsFor(limits.arena.tree_sitter)]u64 = @splat(0); -var tree_sitter_buffer: [bufferFor(limits.arena.tree_sitter)]u8 = @splat(0); -var tree_sitter_region: Region = .{ .size = limits.arena.tree_sitter, .bits = &tree_sitter_bits, .buffer = &tree_sitter_buffer }; +var tree_sitter_region: Region = .{ .size = limits.arena.tree_sitter, .bits = &tree_sitter_bits }; var image_bits: [bitsFor(limits.arena.image)]u64 = @splat(0); -var image_buffer: [bufferFor(limits.arena.image)]u8 = @splat(0); -var image_region: Region = .{ .size = limits.arena.image, .bits = &image_bits, .buffer = &image_buffer }; +var image_region: Region = .{ .size = limits.arena.image, .bits = &image_bits }; var pdf_bits: [bitsFor(limits.arena.pdf)]u64 = @splat(0); -var pdf_buffer: [bufferFor(limits.arena.pdf)]u8 = @splat(0); -var pdf_region: Region = .{ .size = limits.arena.pdf, .bits = &pdf_bits, .buffer = &pdf_buffer }; +var pdf_region: Region = .{ .size = limits.arena.pdf, .bits = &pdf_bits }; var host_bits: [bitsFor(limits.arena.host)]u64 = @splat(0); -var host_buffer: [bufferFor(limits.arena.host)]u8 = @splat(0); -var host_region: Region = .{ .size = limits.arena.host, .bits = &host_bits, .buffer = &host_buffer }; +var host_region: Region = .{ .size = limits.arena.host, .bits = &host_bits }; /// The allocator a native shell allocates itself from, over its own arena, /// for the life of the process (no `deinit`); what does not fit spills to @@ -546,7 +482,6 @@ pub fn deinit() void { } test "arenas are separate, reuse what is freed, spill, and restart" { - if (reduced_target) return error.SkipZigTest; var allocs = init(std.testing.allocator); const core = try allocs.pardes.alloc(u8, 32); const frame = try allocs.frame.alloc(u8, 32); @@ -594,7 +529,6 @@ test "a region's runs: aligned first fit, growth in place, release" { } test "memory limits preserve desktop capacities" { - if (reduced_target) return error.SkipZigTest; try std.testing.expectEqual(4096, limits.effect_cap); try std.testing.expectEqual(@as(usize, 4 * MiB), limits.pending_write_cap); try std.testing.expectEqual(256, limits.wrap_rows); diff --git a/src/mouse.zig b/src/mouse.zig index 6cec562d..e38d5d5f 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -178,7 +178,6 @@ fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { } test "a pane's last row of text is no resize handle; the rule over the next pane is" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); const seam = seamRowOf(p, 1, 0); @@ -190,7 +189,6 @@ test "a pane's last row of text is no resize handle; the rule over the next pane } test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); const upper = p.col_panes[1][0]; @@ -230,7 +228,7 @@ fn nudgeRightSeam(p: *Pardes, delta: i32) u16 { pub const ChromeTarget = struct { col: u16, row: u16 }; -/// The chrome a press at `col`, `row` takes (web.zig): the tag rows; then, +/// The chrome a press at `col`, `row` takes: the tag rows; then, /// on the cell, a pane's grip, a column's handle or a seam; then a cell /// away, any of a pane's tag, a handle or a seam. pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { @@ -260,7 +258,6 @@ pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { } test "a press near chrome takes it: the tag rows, a column's handle or a seam on its cell or a cell away, a pane's tag; nothing in a body" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); // Column 0's two panes share its rows evenly; column 1's lower one is @@ -1156,8 +1153,8 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { /// second selects what edit.doubleClickRange says, from the caret the click /// left. A plain click still puts the caret on its cell. fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, col: i32) void { - // The host's clock, which every host keeps (a libc clock is no clock on - // the web) and a test's virtual one replaces. + // The host's clock, which every host keeps and a test's virtual one + // replaces. const now: i64 = @intCast(p.now_ns / std.time.ns_per_ms); const prev = p.last_click; p.last_click = .{ .id = id, .on_tag = on_tag, .row = row, .col = col, .ms = now }; @@ -1588,7 +1585,6 @@ test "a corner drag's two axes clamp independently" { } test "a v-handle press at the RIGHT column's seam drags both boundaries" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); try std.testing.expectEqual(@as(usize, 2), p.col_n[1]); @@ -1619,7 +1615,6 @@ test "a v-handle press at the RIGHT column's seam drags both boundaries" { } test "a tie row still moves the LEFT column's pane pair only" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); @@ -1645,7 +1640,6 @@ test "a tie row still moves the LEFT column's pane pair only" { } test "a v-handle press at nobody's seam is still a plain edge drag" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); const right_seam = nudgeRightSeam(p, 3); @@ -1671,7 +1665,6 @@ test "a v-handle press at nobody's seam is still a plain edge drag" { } test "a RIGHT-column corner's two axes clamp independently" { - if (platform == .web) return; const p = try cornerFixture(std.testing.allocator); defer p.deinit(); const right_seam = nudgeRightSeam(p, 3); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index d74c044d..d1ffc3c6 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -417,7 +417,6 @@ test "Help and Find at /tagexec act in the session's directory, not the keyboard } test "a shell command at /tagexec or a column's exec is a command pane in the session's directory, never typed into the keyboard's terminal" { - if (comptime !pardes.hosted) return; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 3b8dae1e..96c44d14 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -382,7 +382,7 @@ pub fn statusText(p: *Pardes) []const u8 { var w: std.Io.Writer.Allocating = .init(p.scratch.allocator()); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); - const pid: u32 = if (comptime pardes.hosted) @intCast(std.c.getpid()) else 0; + const pid: u32 = @intCast(std.c.getpid()); w.writer.print("pid {d}\nversion {s}\npanes {d}\n", .{ pid, pardes.version, count }) catch {}; // Whether the pointer is over this window: what a grip let go past // another window's edge asks of every window, to find the one it was @@ -665,7 +665,7 @@ pub fn writePager(p: *Pardes, req: Req) Reply { var shown: [256]u8 = undefined; return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "pager: invalid directory \"{s}\": must be absolute", .{blanked(dir[0..@min(dir.len, shown.len)], &shown)}) catch "pager: invalid directory: must be absolute"); } - if (comptime pardes.hosted) if (dir.len > 0) if (pardes.filesystem.localPath(dir)) |local| { + if (dir.len > 0) if (pardes.filesystem.localPath(dir)) |local| { // A file there is no directory, ENOTDIR; nothing there, ENOENT. if (exec_line.kindOf(local) != .directory) { if (exec_line.kindOf(local) != null) @@ -1596,7 +1596,6 @@ test "exec Save writes the named file through the host" { } test "a refusal's +Unsaved goes in the session's directory when the active pane's directory is not there" { - if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); @@ -1697,7 +1696,6 @@ test "DumpConfig's whole report writes back to the root ctl, line by line, with } test "a Restore asks again for the ThemeFile the dump names, as a /ctl write of it does" { - if (comptime !pardes.hosted) return; const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); @@ -1726,7 +1724,6 @@ test "a Restore asks again for the ThemeFile the dump names, as a /ctl write of } test "a ThemeFile that fails to load changes nothing: the root ctl still names the one loaded, or none" { - if (comptime !pardes.hosted) return; const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); @@ -1752,7 +1749,6 @@ test "a ThemeFile that fails to load changes nothing: the root ctl still names t } test "after a ThemeFile the root ctl and DumpConfig say ThemeFile and its path, which writes back" { - if (comptime !pardes.hosted) return; const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); @@ -1827,7 +1823,6 @@ test "a look whose pane is refused a place fails with that alone, not a missing } test "a Restore of a file that is no dump fails the write before any warning, and a failed Dump fails its write" { - if (comptime !pardes.hosted) return error.SkipZigTest; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const f = pane_files.fileOf(p.panes[0].?).?; @@ -2286,7 +2281,6 @@ test "with no pane at all, the root look opens its file and the root exec runs i } test "a restored pane whose file is gone from disk comes back dirty, and Del asks first" { - if (comptime !pardes.hosted) return error.SkipZigTest; const p = try withFile(testing.allocator, "kept text\n"); defer p.deinit(); // On disk when dumped, gone by the Restore. @@ -2336,7 +2330,6 @@ test "a focus moved over 9P tells the programs that asked for focus reports, as } test "a Restore of a name in the DumpDir asks for, and logs, the whole path it reads" { - if (comptime !pardes.hosted) return error.SkipZigTest; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); try pardes.dump.dumpState(p); @@ -2853,7 +2846,6 @@ test "a Rename the server answered for this file alone, with other open files sa } test "Find says what it skipped under its names, and a script's Find that finds nothing is told so" { - if (comptime !pardes.hosted) return; const gpa = testing.allocator; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2896,7 +2888,6 @@ test "Lspinfo's answer is the +Lsp pane it fills, as a Rename preview's is its + test "DumpDir refuses a relative directory and one that may not be written, up front; a Dump there says permission denied" { - if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const root_ctl = @backingInt(tree.TopFile.ctl); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 088520e3..d77cc65a 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -21,7 +21,6 @@ pub const queue_cap = 64 * 1024; /// Wall-clock seconds, or zero where the platform has no clock. pub fn now() u32 { - if (comptime !pardes.hosted) return 0; var ts: std.c.timespec = undefined; if (std.c.clock_gettime(.REALTIME, &ts) != 0) return 0; return std.math.cast(u32, ts.sec) orelse 0; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 2faa4466..289639e9 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -899,7 +899,7 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // A directory (`~`, `/`, `foo/`) is no file to name a pane after: a // Save could only fail. Said now, EISDIR. const is_dir = name[name.len - 1] == '/' or std.mem.eql(u8, full, "/") or - (if (comptime pardes.hosted) (if (fs.localPath(full)) |local| exec.kindOf(local) == .directory else false) else false); + (if (fs.localPath(full)) |local| exec.kindOf(local) == .directory else false); if (is_dir) return tree.failText(req.tag, E.ISDIR, std.fmt.bufPrint(&p.fs.ename, "name: {s} is a directory, not a file", .{full[0..@min(full.len, 256)]}) catch "name: is a directory, not a file"); nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) { error.OutOfMemory => E.NOMEM, diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index e212d67d..65e8589f 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -62,12 +62,10 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}: no such directory", .{dir[0..@min(dir.len, 256)]}) catch "exec: no such directory"); // Nor is a shell that is not there, or a script whose // interpreter is not: refused, and the running shell kept. - if (comptime pardes.hosted) { - 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| - return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused}) catch "exec: no such shell"); - } + 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| + return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused}) catch "exec: no such shell"); }; if (verb(p, id, line, apply)) |why| return tree.failText(req.tag, E.INVAL, why); } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 53bec357..66a2c0bb 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1081,7 +1081,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { .screen => screen.readSnapshot(p, req, null), .listeners => window(p, req, screen.listenersText(p)), .sessions => sessions: { - if (comptime !(pardes.hosted and daemon.supported)) break :sessions stagedReply(p, req); + if (comptime !daemon.supported) break :sessions stagedReply(p, req); // Out of the turn: the daemon answers within 2 s, or not at all. const said = pardes.tape.site(.sessions, p.gpa, daemonList, .{p.gpa}) catch |err| break :sessions switch (err) { error.OutOfMemory => Reply.fail(req.tag, E.NOMEM), diff --git a/src/pardes.zig b/src/pardes.zig index c3d12932..db5c0c25 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -80,8 +80,6 @@ pub const isolated = @import("pardes_isolation").isolated; pub const font_picker = platform == .gui or platform == .macos; -pub const hosted = platform == .tui or platform == .gui or platform == .macos; - /// Whose turn it is with the core. The core is single-threaded: the editor's /// thread has it, and lets go of it in two kinds of gap -- while it waits for /// input (`rest`, `wake`), and while it is out in the host filesystem in the @@ -102,7 +100,7 @@ pub const hosted = platform == .tui or platform == .gui or platform == .macos; /// is never the syscall's own. /// /// One per process, like the editor it belongs to. A process that never -/// starts it -- a test, the browser -- has no second thread, and +/// starts it -- a test -- has no second thread, and /// every yield is a no-op. pub var turn: Turn = .{}; @@ -248,9 +246,6 @@ pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) { // Both pixel shells rasterize for a real display and can afford it; the // wire-bandwidth argument that shapes the Kitty policy does not apply. .gui, .macos => sdl_pdf_raster_policy, - // The web rasterizes no PDF at all (mupdf is compiled out), so the - // cheaper policy is the honest placeholder. - .web => kitty_pdf_raster_policy, }; pub const Pane = panes.Pane; @@ -395,7 +390,6 @@ fn colFromSpan(x: f32, span: f32) u16 { } test "a compact tagline anchors at its own pane, and both shells step from the same origin" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 24 }); defer p.deinit(); _ = try p.newShell(1, ""); @@ -2388,7 +2382,7 @@ test "a host with no methods at all is a complete in-process pardes" { } test "Font keeps requested and acknowledged faces as separate plain state" { - if (comptime !font_picker) return; // there is no Font builtin on tty or web + if (comptime !font_picker) return; // there is no Font builtin on the tty const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -2495,7 +2489,6 @@ test "startup config overrides restored styling before initFromDump returns" { } test "restored sessions animate layout changes after bootstrap" { - if (platform == .web) return; const source = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 16 }); defer source.deinit(); try dump.dumpState(source); @@ -3113,7 +3106,6 @@ comptime { } test "a new column takes width only from the column that created it" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 124, .rows = 24 }); defer p.deinit(); @@ -3181,7 +3173,6 @@ test "a new column takes width only from the column that created it" { } test "Newcol refuses an unsplittable restored weight before spawning" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 200, .rows = 20 }); defer p.deinit(); @@ -3578,7 +3569,6 @@ test "core composes character motion out of the new grid, not a fade" { } test "repeated non-dyadic column splits preserve every unrelated boundary" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 979, .rows = 20 }); defer p.deinit(); @@ -4264,9 +4254,9 @@ pub const Pardes = struct { /// remembered for want of memory is no failure of what opened it), so /// on a host it takes from the process heap, not the editor's, whose /// every failure must be answered. - // ponytail: a host heap for a best-effort list; the browser's gpa there. - pub fn recentGpa(p: *const Pardes) std.mem.Allocator { - return if (comptime hosted) std.heap.smp_allocator else p.gpa; + // ponytail: a host heap for a best-effort list. + pub fn recentGpa(_: *const Pardes) std.mem.Allocator { + return std.heap.smp_allocator; } /// Recent's file read once at start: a new session's. @@ -4286,7 +4276,6 @@ pub const Pardes = struct { /// the served tree's (`/virtual/`) nor a name never saved. pub fn recentKeeps(path: []const u8) bool { const local = filesystem.localPath(path) orelse return false; - if (comptime !hosted) return true; return exec.kindOf(local) == .file; } @@ -4372,7 +4361,7 @@ pub const Pardes = struct { const taped = tape.enter(p, .{ .deinit = tape.current(p) }); tape.forget(p); defer tape.leave(null, taped); - if (comptime hosted) if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path)); + if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path)); // Every file open now is closed with its dot, and the list kept. for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); p.store.flush(p, true); @@ -4896,11 +4885,10 @@ pub const Pardes = struct { } /// A window's font, asked and told (this and the three below): in every - /// hosted build, not only a window's, as only a window's host calls + /// build, not only a window's, as only a window's host calls /// them and a terminal's replica of a window's session must step as /// the window does. pub fn takeFontRequest(p: *Pardes) ?[]const u8 { - if (comptime !hosted) return null; const taped = tape.enter(p, .take_font_request); defer tape.leave(p, taped); if (!p.settings.font.pending or p.font_request_taken) return null; @@ -4916,7 +4904,6 @@ pub const Pardes = struct { effective_size_hundredths: u16, unit: config.Runtime.FontSizeUnit, ) bool { - if (comptime !hosted) return false; const taped = tape.enter(p, .{ .observe_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); defer tape.leave(p, taped); if (!p.settings.font.effective_name.set(effective_name)) return false; @@ -4933,7 +4920,6 @@ pub const Pardes = struct { effective_size_hundredths: u16, unit: config.Runtime.FontSizeUnit, ) bool { - if (comptime !hosted) return false; const taped = tape.enter(p, .{ .acknowledge_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); defer tape.leave(p, taped); if (!p.settings.font.pending or !p.font_request_taken) return false; @@ -4951,7 +4937,6 @@ pub const Pardes = struct { } pub fn rejectFont(p: *Pardes) void { - if (comptime !hosted) return; const taped = tape.enter(p, .reject_font); defer tape.leave(p, taped); if (!p.settings.font.pending or !p.font_request_taken) return; @@ -5179,7 +5164,7 @@ pub const Pardes = struct { // A Save makes the directories its file goes in, and any above them, // first: one rule, for the pane's own name and `Save path` alike. A // directory it cannot make leaves the write to fail and say why. - if (comptime hosted) if (filesystem.localPath(path)) |local| filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); + if (filesystem.localPath(path)) |local| filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); // The in-process filesystem reports the same way a real host does, // so an OOM there leaves the pane dirty rather than looking saved. if (p.host.vtable.write_file) |f| f(p.host.ctx, id, path, bytes) else if (!p.fallback.writeFile(path, bytes)) p.saveFailed(id, path, error.OutOfMemory); @@ -5255,7 +5240,7 @@ pub const Pardes = struct { // The script is there; the program its `#!` names is not. var said: [320]u8 = undefined; var interp: [256]u8 = undefined; - const name: ?[]const u8 = if (comptime hosted) tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }) else null; + const name = tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }); p.reportFailure(id, if (name) |n| std.fmt.bufPrint(&said, "shell: interpreter {s} not found", .{n}) catch "shell: interpreter not found" else "shell: interpreter not found"); } else { p.reportError(id, "shell", err); @@ -5277,10 +5262,10 @@ pub const Pardes = struct { /// missing, and whether that is because one above refuses (EACCES). fn parentTrouble(path: []const u8, err: anyerror) struct { dir: []const u8, kind: ?std.Io.File.Kind, missing: bool, denied: bool } { const dir = std.fs.path.dirname(path) orelse "/"; - const local = if (comptime hosted) filesystem.localPath(dir) else null; - const kind: ?std.Io.File.Kind = if (comptime hosted) (if (local) |l| exec.kindOf(l) else .directory) else .directory; + const local = filesystem.localPath(dir); + const kind: ?std.Io.File.Kind = if (local) |l| exec.kindOf(l) else .directory; const missing = err == error.FileNotFound or err == error.NotDir or kind != .directory; - const denied = missing and (if (comptime hosted) (if (local) |l| tape.value(.denied, filesystem.deniedAbove, .{l}) else false) else false); + const denied = missing and (if (local) |l| tape.value(.denied, filesystem.deniedAbove, .{l}) else false); return .{ .dir = dir, .kind = kind, .missing = missing, .denied = denied }; } @@ -6241,7 +6226,6 @@ pub const Pardes = struct { /// Where pardes started: the directory of what runs from a header. pub fn sessionDir(p: *Pardes) []const u8 { if (p.session_dir_len) |n| return p.session_dir[0..n]; - if (comptime !hosted) return "/"; // The directory the session that recorded was started in. const dir = tape.value(.cwd, processDir, .{&p.session_dir}) orelse return "/"; std.mem.copyForwards(u8, &p.session_dir, dir); @@ -7499,7 +7483,6 @@ pub const Pardes = struct { }; test "a boot file that will not open boots an errors pane rather than failing the launch" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, @@ -7625,7 +7608,6 @@ test "raw terminal cursor follows its active row only while that row is visible" } test "Esc back into a tty leaves its view at the prompt" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -7665,7 +7647,6 @@ test "Esc back into a tty leaves its view at the prompt" { } test "a prompt chip is a band with its caret, still on the grid, and only the chip swallows a click" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const id = p.active; @@ -7722,7 +7703,6 @@ test "a prompt chip is a band with its caret, still on the grid, and only the ch } test "a prompt is typed on its own line in the notice band and leaves the tag row alone" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("one two\n"); @@ -7761,7 +7741,6 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro } test "Del from a key asks which neighbour takes the rows; nothing else asks" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 40 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); @@ -7878,7 +7857,6 @@ test "Del from a key asks which neighbour takes the rows; nothing else asks" { } test "the bare tty startup opens a text pane under the shell, unfocused" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .boot = .tty }); defer p.deinit(); try std.testing.expectEqual(Boot.tty, p.boot); @@ -7904,7 +7882,6 @@ test "the bare tty startup opens a text pane under the shell, unfocused" { } test "tty output follows only from the bottom" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); @@ -7947,7 +7924,6 @@ test "tty output follows only from the bottom" { } test "raw tty Esc backs out and Shift-Esc is the program's Esc" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); _ = exec.spawnTty(p, 0); @@ -7972,7 +7948,6 @@ test "raw tty Esc backs out and Shift-Esc is the program's Esc" { } test "with ProgramEsc raw tty Escape only leaves at a shell prompt" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); p.settings.program_esc = true; @@ -8004,7 +7979,6 @@ test "with ProgramEsc raw tty Escape only leaves at a shell prompt" { } test "the Del question shows only once its delay is up: a quick SPC d j never sees it" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 40 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); @@ -8053,7 +8027,6 @@ test "the Del question shows only once its delay is up: a quick SPC d j never se } test "raw tty Ctrl-B switches to editor mode without sending child input" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .file = "mise.toml" }); defer p.deinit(); _ = exec.spawnTty(p, 0); @@ -8150,7 +8123,6 @@ test "a Rename the language server finds nothing for says so, and changes nothin } test "raw tty forwards Ctrl letters and former global shortcuts to the child" { - if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); var buf: [256]u8 = undefined; @@ -8198,7 +8170,6 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { } test "an unasked desktop paste reaches a tty pane's program, not its buffer" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8217,7 +8188,6 @@ test "an unasked desktop paste reaches a tty pane's program, not its buffer" { } test "a paste larger than the effect ring reaches the program whole and in order" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8237,7 +8207,6 @@ test "a paste larger than the effect ring reaches the program whole and in order } test "a bracketed paste larger than the ring still closes its bracket" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8260,7 +8229,6 @@ test "a bracketed paste larger than the ring still closes its bracket" { } test "a terminal's answer to its program waits behind the paste still queued for its pty" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8287,7 +8255,6 @@ test "a terminal's answer to its program waits behind the paste still queued for } test "pasted bytes still queued at shutdown are freed, not leaked" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8305,7 +8272,6 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { } test "leaving tty hides the prompt and keeps the command typed at it" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); @@ -8371,7 +8337,6 @@ test "leaving tty hides the prompt and keeps the command typed at it" { } test "entering tty walks the shell cursor to the column clicked past the prompt" { - if (platform == .web) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer p.deinit(); diff --git a/src/tape.zig b/src/tape.zig index 0e8bbfe6..3723537e 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -150,8 +150,8 @@ pub const results = .{ /// taped by its name, and `anyerror` keeps no list of names to look one up /// in. ponytail: kept by hand, the sets of what a host reports from; one /// outside them is a Debug build's panic as it is taped (walk.encode) and a -/// release build's divergence (the replica joins again). No host, none. -pub const Failure = if (!pardes.hosted) error{} else ErrorOf(host_io.forkShell) || ErrorOf(pardes.filesystem.write) || +/// release build's divergence (the replica joins again). +pub const Failure = ErrorOf(host_io.forkShell) || ErrorOf(pardes.filesystem.write) || ErrorOf(pardes.filesystem.readRestore) || ErrorOf(pardes.dump.restore) || @typeInfo(@TypeOf(pardes.config.User.dumpThemes(undefined, undefined, undefined, pardes.themes))).error_union.error_set || ErrorOf(host_io.Lsp.snapshot) || @@ -279,7 +279,6 @@ pub const Tape = struct { } fn flush(t: *Tape) void { - if (comptime !pardes.hosted) return; // A tape in memory (a replica's, an authority's stream) is taken // by whoever holds it. if (t.fd < 0) return; @@ -894,7 +893,6 @@ fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anyt } else @compileError("tape: the site ." ++ @tagName(s) ++ " returns " ++ @typeName(R) ++ ", which tape.results does not list"); } // No tape where there is no host to record or replay one. - if (comptime !pardes.hosted) return if (yields) out(f, args) else @call(.auto, f, args); const t = on orelse return if (yields) out(f, args) else @call(.auto, f, args); const id: u16 = @as(u16, host_fns.len) + @backingInt(s); if (t.replay) { @@ -1201,7 +1199,6 @@ pub fn digestOf(p: *const Pardes) u64 { /// PARDES_RECORD set: the tape is written from the session's first call. pub fn startFromEnv() void { - if (comptime !pardes.hosted) return; if (on != null) return; const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return); if (prefix.len == 0) return; @@ -1257,7 +1254,6 @@ pub fn replayMain(io: std.Io, path: []const u8) u8 { } test "a syscall that is no site, made replaying, diverges the replay and poisons a speculation" { - if (comptime !pardes.hosted) return; const gpa = std.testing.allocator; var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) }; defer t.scratch.deinit(); @@ -1276,7 +1272,6 @@ test "a syscall that is no site, made replaying, diverges the replay and poisons } test "a replay that finds no answer where its core reads one diverges, and the read goes on harmless" { - if (comptime !pardes.hosted) return; const gpa = std.testing.allocator; var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) }; defer t.scratch.deinit(); diff --git a/src/terminal.zig b/src/terminal.zig index 9aa97f71..c041ae22 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -496,17 +496,13 @@ pub fn deinitPendingCommand(pane: *Pane) void { /// (which ghostty accepts whatever this says). The environment block lives /// as long as the process and pardes never edits it (ChildEnv.exportVar). fn tempDir() []const u8 { - if (comptime !pardes.hosted) return "/tmp"; const dir = std.c.getenv("TMPDIR") orelse return "/tmp"; const path = std.mem.span(dir); return if (path.len > 0 and path[0] == '/') path else "/tmp"; } pub fn terminalIo() std.Io { - return if (comptime !pardes.hosted) - std.Io.failing - else - std.Io.Threaded.global_single_threaded.io(); + return std.Io.Threaded.global_single_threaded.io(); } /// The three numbers ghostty's scrollbar reports; all zero without an emulator. @@ -598,9 +594,9 @@ pub const emulator_gpa = std.heap.c_allocator; /// What a terminal's emulator is made with, by `create` or a pane's load /// (dump.loadPane, a closed terminal brought back): `gpa`, but on a screen- -/// state replica `emulator_gpa`. A hosted build's: the web has no C heap. +/// state replica `emulator_gpa`. pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator { - return if (comptime pardes.hosted) (if (pardes.tape.screenReplica()) emulator_gpa else gpa) else gpa; + return if (pardes.tape.screenReplica()) emulator_gpa else gpa; } /// A replica's speculation leaves an emulator be: it is the authority's diff --git a/src/walk.zig b/src/walk.zig index 53d4b82c..426408c8 100644 --- a/src/walk.zig +++ b/src/walk.zig @@ -108,7 +108,7 @@ fn hashBlob(comptime E: type, items: []const E, h: *Hasher) void { break :kept if (b.len == items.len) b.word else null; } else null; // The lists are the C heap's (a replica client's, a session's join), - // which a build with no libc (the web) has neither of. + // which a build with no libc has neither of. if (comptime builtin.link_libc) if (blobs_out) |list| { list.append(std.heap.c_allocator, std.mem.sliceAsBytes(items)) catch {}; break :word 0; diff --git a/src/web.zig b/src/web.zig deleted file mode 100644 index 27a74289..00000000 --- a/src/web.zig +++ /dev/null @@ -1,520 +0,0 @@ -//! Freestanding WebAssembly boundary for the DOM backend. -//! -//! JavaScript owns the clock and nothing else: it calls `pardes_tick` (one -//! `Pardes.pump`, at requestAnimationFrame's timestamp) and reads the packed cell buffer `present` left behind. The -//! host vtable below is only what a page genuinely has — pixels, the -//! clipboard, links, downloads. Processes, a real filesystem, a language -//! backend and subprocess pipes are left null, so the core answers them itself -//! with a virtual filesystem, a virtual clipboard and silent ptys instead of -//! forwarding effects that JavaScript cannot honour anyway. - -const std = @import("std"); -const pardes = @import("pardes.zig"); -const mouse = @import("mouse.zig"); - -const gpa = std.heap.wasm_allocator; -const embedded_dump = @embedFile("embedded.dump"); -const input_capacity = 64 * 1024; -const attr_tagline: u16 = 1 << 7; - -/// Tree-sitter's C runtime is linked into this module: its malloc, calloc, -/// realloc and free are the wasm allocator's, as the Zig core's are. A var, -/// as c_heap compares the allocator it is at run time (wasm_allocator's -/// `ptr` is undefined, which comptime refuses to compare). -var c_allocator: std.mem.Allocator = gpa; -const c_heap = @import("c_heap").Heap(&c_allocator); -comptime { - @export(&c_heap.malloc, .{ .name = "malloc" }); - @export(&c_heap.calloc, .{ .name = "calloc" }); - @export(&c_heap.realloc, .{ .name = "realloc" }); - @export(&c_heap.free, .{ .name = "free" }); -} - -pub const std_options: std.Options = .{ .logFn = logFn }; -pub const panic = std.debug.FullPanic(panicImpl); - -fn logFn( - comptime _: std.log.Level, - comptime _: @EnumLiteral(), - comptime _: []const u8, - _: anytype, -) void {} - -fn panicImpl(_: []const u8, _: ?usize) noreturn { - @trap(); -} - -const WebCell = extern struct { - // UTF-8 graphemes in the core are at most seven bytes. The eighth byte is - // always zero, which also makes a debugger's memory view pleasant. - text: [8]u8, - fg: u32, - bg: u32, - attrs: u16, - len: u8, - flags: u8, -}; - -comptime { - if (@sizeOf(WebCell) != 20) @compileError("the JS frame ABI changed"); -} - -const State = struct { - core: *pardes.Pardes, - tag_cells: [pardes.MAX_TAG_LAYERS][]WebCell = @splat(&.{}), - layer_cells: [pardes.MAX_PANES][]WebCell = @splat(&.{}), - cells: []WebCell = &.{}, - frame_len: usize = 0, - frame_cols: u16 = 0, - frame_rows: u16 = 0, - /// requestAnimationFrame's timestamp as the last tick gave it, in ns: - /// the core's clock (`Host.now`). - now_ns: u64 = 0, - - fn init(cols: u16, rows: u16) !State { - const allocs = pardes.memory.init(gpa); - errdefer pardes.memory.deinit(); - pardes.image.start(std.Io.failing, allocs.image); - errdefer pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - errdefer if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.start(allocs.tree_sitter); - errdefer pardes.syntax.stop(); - - const core = try pardes.dump.initFromDump(allocs.pardes, .{ - .cols = cols, - .rows = rows, - .frame_allocator = allocs.frame, - .image_allocator = allocs.image, - .pdf_allocator = allocs.pdf, - .tree_sitter_allocator = allocs.tree_sitter, - }, embedded_dump); - return .{ .core = core }; - } - - fn deinit(s: *State) void { - if (s.cells.len > 0) gpa.free(s.cells); - for (s.layer_cells) |cells| gpa.free(cells); - for (s.tag_cells) |cells| gpa.free(cells); - s.core.deinit(); - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); - pardes.syntax.stop(); - pardes.memory.deinit(); - } -}; - -var state: ?State = null; -var input: [input_capacity]u8 = undefined; -var last_error: u32 = 0; - -export fn pardes_init(cols_arg: u32, rows_arg: u32) u32 { - if (state) |*old| old.deinit(); - state = null; - last_error = 0; - - const cols: u16 = @intCast(std.math.clamp(cols_arg, 1, std.math.maxInt(u16))); - const rows: u16 = @intCast(std.math.clamp(rows_arg, 1, std.math.maxInt(u16))); - state = State.init(cols, rows) catch |err| { - last_error = @intFromError(err); - return last_error; - }; - state.?.core.update(.{ .resize = .{ .cols = cols, .rows = rows } }); - return 0; -} - -export fn pardes_deinit() void { - if (state) |*s| s.deinit(); - state = null; -} - -export fn pardes_last_error() u32 { - return last_error; -} - -export fn pardes_input_ptr() u32 { - return @intCast(@intFromPtr(&input)); -} - -export fn pardes_input_capacity() u32 { - return input_capacity; -} - -export fn pardes_gui_tagline_font_percent() u32 { - return pardes.config.gui_tagline_font_percent; -} - -export fn pardes_resize(cols_arg: u32, rows_arg: u32) void { - const s = &(state orelse return); - const cols: u16 = @intCast(std.math.clamp(cols_arg, 1, std.math.maxInt(u16))); - const rows: u16 = @intCast(std.math.clamp(rows_arg, 1, std.math.maxInt(u16))); - if (s.core.screen_w == cols and s.core.screen_h == rows) return; - s.core.update(.{ .resize = .{ .cols = cols, .rows = rows } }); -} - -/// `mods`: bit 0 ctrl, bit 1 alt, bit 2 shift. `len` bytes at input are the -/// browser's composed text for printable keys and zero for functional keys. -export fn pardes_key(cp_arg: u32, len_arg: u32, mods: u32) void { - const s = &(state orelse return); - if (cp_arg > std.math.maxInt(u21)) return; - const len: usize = @min(len_arg, input.len); - s.core.update(.{ .key = .{ - .cp = @intCast(cp_arg), - .text = input[0..len], - .ctrl = mods & 1 != 0, - .alt = mods & 2 != 0, - .shift = mods & 4 != 0, - } }); -} - -export fn pardes_paste(len_arg: u32) void { - const s = &(state orelse return); - const len: usize = @min(len_arg, input.len); - s.core.update(.{ .paste = input[0..len] }); -} - -/// Buttons and kinds are their boundary enum ordinals. Invalid values are -/// ignored rather than reaching an unchecked enum cast inside wasm. -export fn pardes_mouse(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods: u32) void { - mouseWithHit(button_arg, kind_arg, col_arg, row_arg, mods, null, null); -} - -export fn pardes_mouse_pixel(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods: u32, x: f32, y: f32, bw: f32, bh: f32, tw: f32, th: f32) void { - const s = &(state orelse return); - const source = s.core.presentation.pointerFractional(s.core.screen_w, s.core.screen_h, x / @max(1, bw), y / @max(1, bh)); - var hit: ?pardes.Mouse.BodyHit = null; - for (&s.core.surface.body_layers) |*layer| { - const point = source orelse break; - hit = layer.bodyHit(point.x * bw, point.y * bh, bw, bh, tw, th); - if (hit != null) break; - } - var tag_hit: ?pardes.TagHit = null; - for (&s.core.surface.tag_layers) |*layer| { - const point = source orelse break; - tag_hit = layer.tagHit(point.x * bw, point.y * bh, bw, bh, tw, th); - if (tag_hit != null) break; - } - mouseWithHit(button_arg, kind_arg, col_arg, row_arg, mods, hit, tag_hit); -} - -fn mouseWithHit(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods: u32, hit: ?pardes.Mouse.BodyHit, tag_hit: ?pardes.TagHit) void { - const s = &(state orelse return); - const button: pardes.Mouse.Button = switch (button_arg) { - 0 => .left, - 1 => .middle, - 2 => .right, - 3 => .wheel_up, - 4 => .wheel_down, - 5 => .wheel_left, - 6 => .wheel_right, - 7 => .none, - 8 => .back, - 9 => .forward, - else => return, - }; - const kind: pardes.Mouse.Kind = switch (kind_arg) { - 0 => .press, - 1 => .release, - 2 => .motion, - 3 => .drag, - else => return, - }; - s.core.update(.{ - .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = @intCast(@min(col_arg, std.math.maxInt(u16))), - .row = @intCast(@min(row_arg, std.math.maxInt(u16))), - .ctrl = mods & 1 != 0, - // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - }, - }); -} - -export fn pardes_pointer_leave() void { - const s = &(state orelse return); - s.core.update(.pointer_leave); -} - -/// One iteration of the core's own loop: queued input, effects, the frames -/// of animation `timestamp_ms` (requestAnimationFrame's clock) has brought, -/// render, present. JS calls it once per display frame; a call with no -/// timestamp (NaN) leaves the clock where it was. -export fn pardes_tick(timestamp_ms: f64) void { - const s = &(state orelse return); - if (std.math.isFinite(timestamp_ms) and timestamp_ms >= 0) - s.now_ns = @intFromFloat(timestamp_ms * std.time.ns_per_ms); - s.core.pump(host(s)) catch |err| { - last_error = @intFromError(err); - }; -} - -/// The Exit builtin, or the last pane closing. JS stops its frame loop. -export fn pardes_should_quit() u32 { - const s = &(state orelse return 0); - return @intFromBool(s.core.quit); -} - -/// The number of cells in the frame `present` last packed, or zero before the -/// first tick. `pardes_frame_ptr` is valid until the next one. -export fn pardes_frame() u32 { - const s = &(state orelse return 0); - return @intCast(s.frame_len); -} - -export fn pardes_frame_ptr() u32 { - const s = &(state orelse return 0); - return if (s.frame_len == 0) 0 else @intCast(@intFromPtr(s.cells.ptr)); -} - -export fn pardes_frame_cols() u32 { - const s = &(state orelse return 0); - return s.frame_cols; -} - -export fn pardes_frame_rows() u32 { - const s = &(state orelse return 0); - return s.frame_rows; -} - -export fn pardes_cursor_x() i32 { - const s = &(state orelse return -1); - return if (s.core.surface.cursor) |cursor| cursor.x else -1; -} - -export fn pardes_tag_text_inset() u32 { - return pardes.TAG_TEXT_INSET; -} - -export fn pardes_grip_columns() u32 { - return @import("config.zig").GUTTER; -} - -export fn pardes_tag_layer_limit() u32 { - return pardes.MAX_TAG_LAYERS; -} - -export fn pardes_tag_layer_value(index: u32, field: u32) u32 { - const s = &(state orelse return 0); - if (index >= pardes.MAX_TAG_LAYERS) return 0; - const layer = &s.core.surface.tag_layers[index]; - if (layer.rows == 0) return 0; - return switch (field) { - 0 => layer.cols, - 1 => @backingInt(layer.kind), - 2 => layer.id, - 3 => layer.serial, - 4 => layer.viewport.x, - 5 => layer.viewport.y, - 6 => layer.viewport.w, - 7 => layer.viewport.h, - 8 => if (layer.cursor) |c| c.x else 65535, - 9 => if (layer.cursor) |c| @intFromBool(c.bar) else 0, - 10 => @as(u32, layer.bg[0]) << 16 | @as(u32, layer.bg[1]) << 8 | layer.bg[2], - // A band has a row to each line of its tag: `cols * rows` cells. - 11 => layer.rows, - 12 => if (layer.cursor) |c| c.y else 65535, - else => 0, - }; -} - -export fn pardes_tag_layer_cells(index: u32) ?[*]const WebCell { - const s = &(state orelse return null); - if (index >= pardes.MAX_TAG_LAYERS) return null; - const layer = &s.core.surface.tag_layers[index]; - if (layer.rows == 0) return null; - const cells = &s.tag_cells[index]; - if (cells.len != layer.cells.len) cells.* = gpa.realloc(cells.*, layer.cells.len) catch return null; - for (layer.cells, cells.*) |source, *out| out.* = encodeWebCell(source); - return cells.ptr; -} - -export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { - return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h); -} - -export fn pardes_body_layer_value(index: u32, field: u32) u32 { - const s = &(state orelse return 0); - if (index >= pardes.MAX_PANES) return 0; - const layer = &s.core.surface.body_layers[index]; - return switch (field) { - 0 => layer.rows, - 1 => layer.cols, - 2 => layer.context_rows, - 3 => layer.viewport.x, - 4 => layer.viewport.y, - 5 => layer.viewport.w, - 6 => layer.viewport.h, - 7 => layer.serial, - 8 => if (layer.cursor) |c| c.x else 65535, - 9 => if (layer.cursor) |c| c.y else 65535, - 10 => if (layer.cursor) |c| @intFromBool(c.bar) else 0, - else => @intFromBool(layer.hasContextBorderAfter(field - 11)), - }; -} - -export fn pardes_body_layer_cells(index: u32) ?[*]const WebCell { - const s = &(state orelse return null); - if (index >= pardes.MAX_PANES) return null; - const layer = &s.core.surface.body_layers[index]; - if (layer.rows == 0) return null; - const cells = &s.layer_cells[index]; - if (cells.len != layer.cells.len) cells.* = gpa.realloc(cells.*, layer.cells.len) catch return null; - for (layer.cells, cells.*) |cell, *out| out.* = encodeWebCell(cell); - return cells.ptr; -} - -export fn pardes_body_layer_limit() u32 { - return pardes.MAX_PANES; -} - -export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h: u16) void { - const s = &(state orelse return); - s.core.update(.{ .resize = .{ .cols = s.core.screen_w, .rows = s.core.screen_h, .cell_pixels = s.core.cell_pixels, .row_metrics = .{ .body_w = @max(1, body_w), .body_h = @max(1, body_h), .tagline_w = @max(1, tagline_w), .tagline_h = @max(1, tagline_h) } } }); -} - -export fn pardes_pointer_shape() u32 { - const s = &(state orelse return 0); - return @backingInt(s.core.surface.pointer_shape); -} - -export fn pardes_cursor_y() i32 { - const s = &(state orelse return -1); - return if (s.core.surface.cursor) |cursor| cursor.y else -1; -} - -export fn pardes_cursor_bar() u32 { - const s = &(state orelse return 0); - return @intFromBool(if (s.core.surface.cursor) |cursor| cursor.bar else false); -} - -/// The browser's touch policy asks whether a gesture began on layout chrome. -/// A hit returns row:col packed into u32, including snapping near a separator; -/// 0xffffffff means body text and therefore one-finger scroll/tap-as-LOOK. -export fn pardes_chrome_target(col_arg: u32, row_arg: u32) u32 { - const s = &(state orelse return std.math.maxInt(u32)); - const col: u16 = @intCast(@min(col_arg, std.math.maxInt(u16))); - const row: u16 = @intCast(@min(row_arg, std.math.maxInt(u16))); - const target = mouse.chromeTarget(s.core, col, row) orelse return std.math.maxInt(u32); - return (@as(u32, target.row) << 16) | target.col; -} - -// ---- the host ---- -// -// Four imports, because four things here are the browser's and not the core's. -// Everything else in `Host.VTable` stays null: see the file comment. -extern "pardes" fn host_open_link(url: [*]const u8, url_len: usize) callconv(.c) void; -extern "pardes" fn host_set_clipboard(text: [*]const u8, text_len: usize) callconv(.c) void; -extern "pardes" fn host_read_clipboard() callconv(.c) void; -/// A file a page writes is a download. `path` names it; both slices are -/// borrowed for the length of the call. -extern "pardes" fn host_download( - path: [*]const u8, - path_len: usize, - bytes: [*]const u8, - bytes_len: usize, -) callconv(.c) void; - -fn now(ctx: ?*anyopaque) u64 { - const s: *State = @ptrCast(@alignCast(ctx.?)); - return s.now_ns; -} - -const vtable: pardes.Host.VTable = .{ - .now = now, - .present = present, - .write_file = writeFile, - .write_dump = writeDump, - .set_clipboard = setClipboard, - .read_clipboard = readClipboard, - .open_link = openLink, -}; - -fn host(s: *State) pardes.Host { - return .{ .ctx = s, .vtable = &vtable }; -} - -/// Pack the canonical Surface into the stable, JS-facing cell array. -fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { - const s: *State = @ptrCast(@alignCast(ctx.?)); - s.frame_len = 0; - s.frame_cols = 0; - s.frame_rows = 0; - const count: usize = @as(usize, surface.cols) * surface.rows; - if (count != s.cells.len) { - if (count == 0) { - if (s.cells.len > 0) gpa.free(s.cells); - s.cells = &.{}; - } else { - const resized = if (s.cells.len == 0) - gpa.alloc(WebCell, count) - else - gpa.realloc(s.cells, count); - s.cells = resized catch |err| { - last_error = @intFromError(err); - return; - }; - } - } - s.frame_len = count; - s.frame_cols = surface.cols; - s.frame_rows = surface.rows; - for (surface.cells, s.cells[0..count]) |cell, *out| out.* = encodeWebCell(cell); -} - -fn encodeWebCell(cell: pardes.Cell) WebCell { - var out: WebCell = .{ .text = @splat(0), .fg = encodeColor(cell.style.fg), .bg = encodeColor(cell.style.bg), .attrs = encodeAttrs(cell.style), .len = if (cell.default) 1 else cell.len, .flags = @intFromBool(cell.default) }; - if (cell.default) out.text[0] = ' ' else @memcpy(out.text[0..cell.len], cell.grapheme()); - return out; -} - -fn writeFile(_: ?*anyopaque, _: u8, path: []const u8, bytes: []const u8) void { - // A download the browser has been handed IS the save here: there is no - // filesystem to fail against, so there is no `saveFailed` to report. - host_download(path.ptr, path.len, bytes.ptr, bytes.len); -} - -fn writeDump(_: ?*anyopaque, bytes: []const u8) void { - const name = "pardes.dump"; - host_download(name.ptr, name.len, bytes.ptr, bytes.len); -} - -fn setClipboard(_: ?*anyopaque, text: []const u8) void { - host_set_clipboard(text.ptr, text.len); -} - -/// Asynchronous and permission-gated, unlike everything else here: the answer -/// arrives later as an ordinary `pardes_paste`, or never if the prompt says no. -fn readClipboard(_: ?*anyopaque) void { - host_read_clipboard(); -} - -fn openLink(_: ?*anyopaque, url: []const u8) void { - host_open_link(url.ptr, url.len); -} - -fn encodeColor(color: pardes.Color) u32 { - return switch (color) { - .default => 0x01000000, - .index => |index| 0x02000000 | @as(u32, index), - .rgb => |rgb| (@as(u32, rgb[0]) << 16) | (@as(u32, rgb[1]) << 8) | rgb[2], - }; -} - -fn encodeAttrs(style: pardes.CellStyle) u16 { - var attrs: u16 = 0; - attrs |= @as(u16, @intFromBool(style.bold)) << 0; - attrs |= @as(u16, @intFromBool(style.dim)) << 1; - attrs |= @as(u16, @intFromBool(style.italic)) << 2; - attrs |= @as(u16, @intFromBool(style.blink)) << 3; - attrs |= @as(u16, @intFromBool(style.reverse)) << 4; - attrs |= @as(u16, @intFromBool(style.invisible)) << 5; - attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; - attrs |= @as(u16, @intFromBool(style.font_role == .tagline)) * attr_tagline; - attrs |= @as(u16, @backingInt(style.ul)) << 8; - return attrs; -} diff --git a/src/web/app.mjs b/src/web/app.mjs deleted file mode 100644 index 1a8036c0..00000000 --- a/src/web/app.mjs +++ /dev/null @@ -1,706 +0,0 @@ -const CELL_SIZE = 20; -const ATTR_TAGLINE = 1 << 7; -const DEFAULT_FG = "#cccccc"; -const DEFAULT_BG = "#121212"; -const decoder = new TextDecoder(); -const encoder = new TextEncoder(); - -const BUTTON = Object.freeze({ left: 0, middle: 1, right: 2, wheelUp: 3, wheelDown: 4, wheelLeft: 5, wheelRight: 6, none: 7, back: 8, forward: 9 }); -const MOUSE = Object.freeze({ press: 0, release: 1, motion: 2, drag: 3 }); -const SPECIAL_KEYS = Object.freeze({ - Enter: 0x0d, - Backspace: 0x7f, - Tab: 0x09, - Escape: 0x1b, - ArrowUp: 0xf0001, - ArrowDown: 0xf0002, - ArrowLeft: 0xf0003, - ArrowRight: 0xf0004, - Home: 0xf0005, - End: 0xf0006, - PageUp: 0xf0007, - PageDown: 0xf0008, - Delete: 0xf0009, -}); - -export class DomRenderer { - constructor(root, wasm) { - this.root = root; - this.wasm = wasm; - this.rows = []; - this.cells = []; - this.cols = 0; - this.rowCount = 0; - this.snapshot = null; - this.gripFonts = new Map(); - this.gripMetrics = new Map(); - this.root.ownerDocument.fonts?.addEventListener("loadingdone", () => this.resetGripMetrics()); - const taglinePercent = this.wasm.pardes_gui_tagline_font_percent(); - if (taglinePercent < 1 || taglinePercent > 100) throw new Error(`bad tagline font percentage ${taglinePercent}`); - this.root.style.setProperty("--pardes-tagline-font-size", `${taglinePercent}%`); - } - - render() { - const count = this.wasm.pardes_frame(); - const shape = this.wasm.pardes_pointer_shape(); - this.root.style.cursor = shape === 1 ? "pointer" : shape === 3 ? "move" : "text"; - const cols = this.wasm.pardes_frame_cols(); - const rows = this.wasm.pardes_frame_rows(); - if (count !== cols * rows) throw new Error(`bad frame: ${count} cells for ${cols}x${rows}`); - this.ensureGrid(cols, rows); - - const ptr = this.wasm.pardes_frame_ptr(); - const view = new DataView(this.wasm.memory.buffer, ptr, count * CELL_SIZE); - const bytes = new Uint8Array(this.wasm.memory.buffer); - const cursorX = this.wasm.pardes_cursor_x(); - const cursorY = this.wasm.pardes_cursor_y(); - const cursorBar = this.wasm.pardes_cursor_bar() !== 0; - const raw = new Array(count); - const tagCovered = new Uint8Array(count); - const tagPrefixBands = new Map(); - const paneIndicators = new Set(); - if (this.wasm.pardes_tag_layer_limit) { - for (let i = 0; i < this.wasm.pardes_tag_layer_limit(); i++) { - const val = field => this.wasm.pardes_tag_layer_value(i, field); - if (!val(0)) continue; - const gripCols = this.wasm.pardes_grip_columns?.() ?? 2; - const textInset = this.wasm.pardes_tag_text_inset?.() ?? gripCols; - // A row to each line of a taller tag. - for (let y = val(5); y < val(5) + Math.max(1, val(11)); y++) { - if (val(1) !== 0 && val(4) >= textInset && this.cellHeight) { - const offset = this.wasm.pardes_tagline_band_offset(y,rows*this.cellHeight*256,Math.round(this.cellHeight*256),Math.round(this.taglineHeight*256))/256; - for (let x = val(4)-textInset; x < val(4); x++) tagPrefixBands.set(y*cols+x,offset); - if (val(1) === 2) paneIndicators.add(y*cols+val(4)-textInset); - } - for (let x = val(4); x < Math.min(cols, val(4) + val(6)); x++) { - if (y < rows) tagCovered[y * cols + x] = 1; - } - } - } - } - - for (let index = 0; index < count; index += 1) { - const off = index * CELL_SIZE; - const len = view.getUint8(off + 18); - const fg = view.getUint32(off + 8, true); - const bg = view.getUint32(off + 12, true); - const attrs = view.getUint16(off + 16, true); - const text = decoder.decode(bytes.subarray(ptr + off, ptr + off + len)) || " "; - const x = index % cols; - const y = Math.floor(index / cols); - const cursor = x === cursorX && y === cursorY; - const cell = this.cells[index]; - cell.style.visibility = tagCovered[index] ? "hidden" : ""; - const gripOffset = tagPrefixBands.get(index); - cell.style.height = gripOffset === undefined ? "" : `${this.taglineHeight}px`; - cell.style.lineHeight = gripOffset === undefined ? "" : `${this.taglineHeight}px`; - cell.style.marginTop = gripOffset === undefined ? "" : `${gripOffset}px`; - const displayedText = paneIndicators.has(index) ? " " : text; - if (cell.textContent !== displayedText) cell.textContent = displayedText; - const styleKey = `${fg}:${bg}:${attrs}:${cursor ? 1 : 0}:${cursorBar ? 1 : 0}`; - if (cell.pardesStyle !== styleKey) { - applyStyle(cell, fg, bg, attrs, cursor, cursorBar); - cell.pardesStyle = styleKey; - } - raw[index] = { text, fg, bg, attrs }; - } - this.renderBodyLayers(); - this.renderTagLayers(raw); - this.snapshot = { cols, rows, cells: raw, cursorX, cursorY, cursorBar }; - return this.snapshot; - } - - renderTagLayers(canonical) { - if (!this.wasm.pardes_tag_layer_limit || !this.cellWidth) return; - if (!this.tagRoot?.isConnected) { - this.tagRoot = this.root.ownerDocument.createElement("div"); - this.tagRoot.style.cssText = "position:absolute;inset:0;pointer-events:none;overflow:hidden"; - this.root.style.position = "relative"; - this.root.append(this.tagRoot); - } - this.tagNodes ??= new Map(); - const nodes = []; - const bw = this.cellWidth, bh = this.cellHeight, tw = this.taglineWidth, th = this.taglineHeight; - for (let i = 0; i < this.wasm.pardes_tag_layer_limit(); i++) { - const layerValues = Array.from({length:13}, (_,field) => this.wasm.pardes_tag_layer_value(i,field)); - const cols = layerValues[0]; - if (!cols) continue; - const ptr = this.wasm.pardes_tag_layer_cells(i); - if (!ptr) continue; - // A row to each line of a taller tag, each drawn as a band of its own. - for (let line = 0; line < Math.max(1, layerValues[11]); line++) { - const key = i*64+line; - const values = layerValues.slice(0,11); - values[5] = layerValues[5] + line; - values[7] = 1; - values[8] = layerValues[12] === line ? layerValues[8] : 65535; - const bytes = new Uint8Array(this.wasm.memory.buffer,ptr+line*cols*CELL_SIZE,cols*CELL_SIZE); - const offset = this.wasm.pardes_tagline_band_offset(values[5],this.rowCount*bh*256,Math.round(bh*256),Math.round(th*256))/256; - const gripCols = this.wasm.pardes_grip_columns?.() ?? 2; - const gripX = values[4] - (this.wasm.pardes_tag_text_inset?.() ?? gripCols); - const gripCell = canonical[values[5]*this.cols+gripX]; - const grip = values[1] === 2 && gripX >= 0 && gripCell && th >= 1 && tw >= 1; - const geometry = [bw,bh,tw,th,offset,...values,grip,gripCell?.fg,gripCell?.bg,gripCell?.attrs,gripCell?.text,globalThis.devicePixelRatio].join(":"); - const cached = this.tagNodes.get(key); - if (cached && cached.geometry === geometry && cached.bytes.length === bytes.length && cached.bytes.every((byte,index)=>byte===bytes[index])) { - nodes.push(cached.node); - if (cached.grip) nodes.push(cached.grip); - continue; - } - const view = new DataView(this.wasm.memory.buffer,ptr+line*cols*CELL_SIZE,cols*CELL_SIZE); - const layer = this.root.ownerDocument.createElement("div"); - layer.dataset.tagLayer = String(i); - layer.dataset.tagLine = String(line); - layer.style.cssText = `position:absolute;overflow:hidden;white-space:pre;left:${values[4]*bw}px;top:${values[5]*bh+offset}px;width:${values[6]*bw}px;height:${th}px;background:${color(values[10],DEFAULT_BG)}`; - for (let col = 0; col < cols; col++) { - const off = col*CELL_SIZE; - const cell = this.root.ownerDocument.createElement("span"); - cell.className = "pardes-cell"; - cell.textContent = decoder.decode(bytes.subarray(off,off+view.getUint8(off+18))) || " "; - applyStyle(cell,view.getUint32(off+8,true),view.getUint32(off+12,true),view.getUint16(off+16,true),col===values[8],values[9]!==0); - cell.style.textAlign = "left"; - cell.style.width = `${tw}px`; - cell.style.height = `${th}px`; - cell.style.lineHeight = `${th}px`; - layer.append(cell); - } - let gripNode = null; - if (grip && gripCell.text.trim()) { - const cell = this.cells[values[5]*this.cols+gripX]; - gripNode = this.drawGripGlyph(cell, gripCell, gripCols*bw, th); - gripNode.dataset.tagGrip = String(i); - gripNode.style.left = `${gripX*bw}px`; - gripNode.style.top = `${values[5]*bh+offset}px`; - } else if (grip && th >= 6 && tw >= 3) { - gripNode = this.root.ownerDocument.createElement("div"); - gripNode.dataset.tagGrip = String(i); - const centerX = (gripX+gripCols/2)*bw, centerY = values[5]*bh+offset+th/2; - const half = Math.max(1,Math.min(3,bw-2)); - gripNode.style.cssText = "position:absolute;inset:0;pointer-events:none"; - for (const dy of [-2,1]) { - const mark = this.root.ownerDocument.createElement("div"); - mark.style.cssText = `position:absolute;left:${Math.floor(centerX-half)}px;top:${Math.floor(centerY+dy)}px;width:${2*half}px;height:1px;background:${color(gripCell.fg,DEFAULT_FG)}`; - gripNode.append(mark); - } - } - this.tagNodes.set(key,{geometry,bytes:bytes.slice(),node:layer,grip:gripNode}); - nodes.push(layer); - if (gripNode) nodes.push(gripNode); - } - } - if (nodes.length !== this.tagRoot.childNodes.length || nodes.some((node,index)=>node!==this.tagRoot.childNodes[index])) this.tagRoot.replaceChildren(...nodes); - } - - resetGripMetrics() { - this.gripFonts.clear(); - this.gripMetrics.clear(); - this.tagNodes?.clear(); - } - - drawGripGlyph(cell, glyph, width, height) { - const canvas = this.root.ownerDocument.createElement("canvas"); - const ratio = globalThis.devicePixelRatio || 1; - canvas.width = Math.max(1, Math.ceil(width*ratio)); - canvas.height = Math.max(1, Math.ceil(height*ratio)); - canvas.style.cssText = `position:absolute;pointer-events:none;width:${width}px;height:${height}px`; - canvas.setAttribute("aria-label", glyph.text); - const ctx = canvas.getContext("2d"); - // Resolve a face once per style, then retain its ink bearings for each - // symbol. Font loading and runtime metric changes clear both caches. - let font = this.gripFonts.get(glyph.attrs); - if (!font) { - const style = this.root.ownerDocument.defaultView.getComputedStyle(cell); - font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`; - this.gripFonts.set(glyph.attrs, font); - } - ctx.scale(ratio, ratio); - ctx.font = font; - const key = `${font}:${ratio}:${glyph.text}`; - let ink = this.gripMetrics.get(key); - if (!ink) { - const measured = ctx.measureText(glyph.text); - ink = { left:measured.actualBoundingBoxLeft, right:measured.actualBoundingBoxRight, - ascent:measured.actualBoundingBoxAscent, descent:measured.actualBoundingBoxDescent }; - this.gripMetrics.set(key, ink); - } - ctx.fillStyle = cell.style.color; - ctx.fillText(glyph.text, (width-ink.right+ink.left)/2, (height+ink.ascent-ink.descent)/2); - return canvas; - } - - renderBodyLayers() { - if (!this.wasm.pardes_body_layer_limit || !this.cellWidth) return; - if (!this.layerRoot?.isConnected) { - this.layerRoot = this.root.ownerDocument.createElement("div"); - this.layerRoot.style.cssText = "position:absolute;inset:0;pointer-events:none;overflow:hidden"; - this.root.style.position = "relative"; - this.root.append(this.layerRoot); - } - const nodes = []; - this.layerNodes ??= new Map(); - const bw = this.cellWidth, bh = this.cellHeight; - const tw = this.taglineWidth, th = this.taglineHeight; - for (let i = 0; i < this.wasm.pardes_body_layer_limit(); i++) { - const val = (field) => this.wasm.pardes_body_layer_value(i, field); - const rows = val(0), cols = val(1), contexts = val(2); - if (!rows) continue; - const ptr = this.wasm.pardes_body_layer_cells(i); - if (!ptr) continue; - const view = new DataView(this.wasm.memory.buffer, ptr, rows * cols * CELL_SIZE); - const bytes = new Uint8Array(this.wasm.memory.buffer); - const geometry = [bw,bh,tw,th,...Array.from({length:11+contexts},(_,field)=>val(field))].join(":"); - const encoded = bytes.subarray(ptr,ptr+rows*cols*CELL_SIZE); - const cached = this.layerNodes.get(i); - if (cached && cached.geometry===geometry && cached.bytes.length===encoded.length && cached.bytes.every((byte,index)=>byte===encoded[index])) { - nodes.push(cached.node); - continue; - } - const layer = this.root.ownerDocument.createElement("div"); - layer.style.cssText = `position:absolute;overflow:hidden;left:${val(3)*bw}px;top:${val(4)*bh}px;width:${val(5)*bw}px;height:${val(6)*bh}px;background:${DEFAULT_BG}`; - for (let row = 0; row < rows; row++) { - const compact = row < contexts; - const height = compact ? th : bh, width = compact ? tw : bw; - const top = Math.min(row, contexts)*th + Math.max(0,row-contexts)*bh; - if (top >= val(6)*bh) break; - const line = this.root.ownerDocument.createElement("div"); - line.style.cssText = `position:absolute;left:0;right:0;top:${top}px;height:${height}px;line-height:${height}px;white-space:pre;overflow:hidden`; - line.style.backgroundColor = color(view.getUint32(row*cols*CELL_SIZE+12,true),DEFAULT_BG); - for (let col = 0; col < cols; col++) { - const off = (row*cols+col)*CELL_SIZE; - const cell = this.root.ownerDocument.createElement("span"); - cell.className = "pardes-cell"; - cell.textContent = decoder.decode(bytes.subarray(ptr+off,ptr+off+view.getUint8(off+18))) || " "; - applyStyle(cell, view.getUint32(off+8,true), view.getUint32(off+12,true), view.getUint16(off+16,true), col===val(8)&&row===val(9), val(10)!==0); - cell.style.textAlign = "left"; - cell.style.width = `${width}px`; - cell.style.height = `${height}px`; - cell.style.lineHeight = `${height}px`; - line.append(cell); - } - layer.append(line); - } - for (let row = 0; row < contexts; row++) { - if (!val(11 + row)) continue; - const border = this.root.ownerDocument.createElement("div"); - border.dataset.contextBorder = String(row); - border.style.cssText = `position:absolute;left:0;right:0;top:${(row+1)*th}px;height:1px;background:currentColor;opacity:.45`; - layer.append(border); - } - this.layerNodes.set(i,{geometry,bytes:encoded.slice(),node:layer}); - nodes.push(layer); - } - if (nodes.length!==this.layerRoot.childNodes.length || nodes.some((node,index)=>node!==this.layerRoot.childNodes[index])) this.layerRoot.replaceChildren(...nodes); - } - - ensureGrid(cols, rows) { - if (cols === this.cols && rows === this.rowCount) return; - const document = this.root.ownerDocument; - const rowNodes = []; - const cells = []; - for (let y = 0; y < rows; y += 1) { - const row = document.createElement("div"); - row.className = "pardes-row"; - row.setAttribute("role", "row"); - row.dataset.row = String(y); - const rowCells = []; - for (let x = 0; x < cols; x += 1) { - const cell = document.createElement("span"); - cell.className = "pardes-cell"; - cell.setAttribute("role", "gridcell"); - cell.dataset.col = String(x); - cell.dataset.row = String(y); - cell.textContent = " "; - rowCells.push(cell); - cells.push(cell); - } - row.replaceChildren(...rowCells); - rowNodes.push(row); - } - this.root.replaceChildren(...rowNodes); - this.root.setAttribute("aria-colcount", String(cols)); - this.root.setAttribute("aria-rowcount", String(rows)); - this.rows = rowNodes; - this.cells = cells; - this.cols = cols; - this.rowCount = rows; - } -} - -export class PardesRuntime { - constructor(root, wasm) { - this.root = root; - this.wasm = wasm; - this.renderer = new DomRenderer(root, wasm); - this.cellWidth = 1; - this.cellHeight = 1; - this.running = false; - this.pointer = null; - this.frameHandle = 0; - this.bindEvents(); - } - - start() { - this.measure(); - const { cols, rows } = this.gridSize(); - const error = this.wasm.pardes_init(cols, rows); - if (error) throw new Error(`Pardes wasm init failed (${error})`); - this.resize(); - this.wasm.pardes_tick(); - this.renderer.render(); - this.running = true; - this.frameHandle = requestAnimationFrame((timestamp) => this.frame(timestamp)); - this.root.focus({ preventScroll: true }); - } - - stop() { - this.running = false; - if (this.frameHandle) cancelAnimationFrame(this.frameHandle); - this.wasm.pardes_deinit(); - } - - frame(timestamp) { - if (!this.running) return; - if (this.wasm.pardes_gui_tagline_font_percent() !== this.measuredTaglinePercent) { - this.resize(); - this.root.style.setProperty("--pardes-tagline-font-size", `${this.measuredTaglinePercent}%`); - } - // The core's clock is this timestamp: it steps its own animations - // by it, however fast the display refreshes. - this.wasm.pardes_tick(timestamp); - if (this.wasm.pardes_should_quit()) this.running = false; - this.renderer.render(); - this.frameHandle = requestAnimationFrame((nextTimestamp) => this.frame(nextTimestamp)); - } - - measure() { - const probe = this.root.ownerDocument.createElement("span"); - probe.className = "pardes-probe"; - probe.textContent = "M"; - this.root.ownerDocument.body.append(probe); - const rect = probe.getBoundingClientRect(); - probe.remove(); - this.cellWidth = Math.max(1, rect.width); - this.cellHeight = Math.max(1, rect.height); - const ratio = this.wasm.pardes_gui_tagline_font_percent() / 100; - this.measuredTaglinePercent = this.wasm.pardes_gui_tagline_font_percent(); - this.taglineWidth = this.cellWidth * ratio; - this.taglineHeight = this.cellHeight * ratio; - Object.assign(this.renderer, { cellWidth:this.cellWidth, cellHeight:this.cellHeight, taglineWidth:this.taglineWidth, taglineHeight:this.taglineHeight }); - const style = this.root.ownerDocument.defaultView.getComputedStyle(this.root); - const fontKey = [style.fontFamily,style.fontSize,style.fontWeight,style.fontStyle,ratio,globalThis.devicePixelRatio].join(":"); - if (fontKey !== this.gripFontKey) { - this.renderer.resetGripMetrics(); - this.gripFontKey = fontKey; - } - } - - gridSize() { - return { - cols: Math.max(1, Math.floor(this.root.clientWidth / this.cellWidth)), - rows: Math.max(1, Math.floor(this.root.clientHeight / this.cellHeight)), - }; - } - - resize() { - this.measure(); - const { cols, rows } = this.gridSize(); - this.wasm.pardes_resize(cols, rows); - this.wasm.pardes_row_metrics?.(Math.max(1,Math.round(this.cellWidth)),Math.max(1,Math.round(this.cellHeight)),Math.max(1,Math.round(this.taglineWidth)),Math.max(1,Math.round(this.taglineHeight))); - } - - writeInput(text) { - return putInput(this.wasm, text); - } - - key(event) { - const mods = modifiers(event); - let cp = SPECIAL_KEYS[event.key]; - let text = ""; - if (cp === undefined && event.key.length > 0 && [...event.key].length === 1) { - text = mods & 3 ? "" : event.key; - const shortcut = event.code?.match(/^Key([A-Z])$/); - cp = shortcut && (mods & 3) ? shortcut[1].toLowerCase().codePointAt(0) : event.key.codePointAt(0); - } - if (cp === undefined) return; - event.preventDefault(); - this.wasm.pardes_key(cp, this.writeInput(text), mods); - } - - point(event) { - const rect = this.root.getBoundingClientRect(); - this.sampledPointer = { x:event.clientX-rect.left, y:event.clientY-rect.top }; - return { - col: clamp(Math.floor((event.clientX - rect.left) / this.cellWidth), 0, Math.max(0, this.wasm.pardes_frame_cols() - 1)), - row: clamp(Math.floor((event.clientY - rect.top) / this.cellHeight), 0, Math.max(0, this.wasm.pardes_frame_rows() - 1)), - }; - } - - cellPoint(col, row) { - const rect = this.root.getBoundingClientRect(); - return { x: rect.left + (col + 0.5) * this.cellWidth, y: rect.top + (row + 0.5) * this.cellHeight }; - } - - mouse(button, kind, col, row, mods) { - if (this.wasm.pardes_mouse_pixel && this.sampledPointer) { - this.wasm.pardes_mouse_pixel(button,kind,col,row,mods,this.sampledPointer.x*256,this.sampledPointer.y*256,Math.round(this.cellWidth*256),Math.round(this.cellHeight*256),Math.round(this.taglineWidth*256),Math.round(this.taglineHeight*256)); - } else this.wasm.pardes_mouse(button,kind,col,row,mods); - } - - mouseDown(event) { - event.preventDefault(); - if (event.button !== 3 && event.button !== 4) return; - this.root.focus({ preventScroll: true }); - const point = this.point(event); - this.mouse(pointerButton(event.button), MOUSE.press, point.col, point.row, modifiers(event)); - } - - pointerDown(event) { - // Mouse defaults are cancelled by mousedown. Cancelling pointerdown - // would suppress that stream, including thumb presses while left is held. - if (event.button === 3 || event.button === 4) return; - if (event.pointerType === "touch") event.preventDefault(); - this.root.focus({ preventScroll: true }); - const point = this.point(event); - this.root.setPointerCapture?.(event.pointerId); - if (event.pointerType === "touch") { - const packed = this.wasm.pardes_chrome_target(point.col, point.row) >>> 0; - const chrome = packed !== 0xffffffff; - const snapped = chrome ? { col: packed & 0xffff, row: packed >>> 16 } : point; - this.pointer = { id: event.pointerId, touch: true, chrome, startX: event.clientX, startY: event.clientY, lastX: event.clientX, lastY: event.clientY, point: snapped, scrolling: false, accum: 0 }; - if (chrome) this.mouse(BUTTON.left, MOUSE.press, snapped.col, snapped.row, modifiers(event)); - return; - } - const button = pointerButton(event.button); - this.pointer = { id: event.pointerId, touch: false, button }; - this.mouse(button, MOUSE.press, point.col, point.row, modifiers(event)); - } - - pointerMove(event) { - if (event.button === 3 || event.button === 4) return; - const point = this.point(event); - const active = this.pointer?.id === event.pointerId ? this.pointer : null; - if (!active) { - if (event.pointerType !== "touch") this.mouse(BUTTON.none, MOUSE.motion, point.col, point.row, modifiers(event)); - return; - } - event.preventDefault(); - if (!active.touch) { - this.mouse(active.button, MOUSE.drag, point.col, point.row, modifiers(event)); - return; - } - if (active.chrome) { - this.mouse(BUTTON.left, MOUSE.drag, point.col, point.row, modifiers(event)); - return; - } - const travel = Math.hypot(event.clientX - active.startX, event.clientY - active.startY); - if (travel > 8) active.scrolling = true; - if (active.scrolling) { - const dy = event.clientY - active.lastY; - active.accum += dy / this.cellHeight; - while (active.accum <= -1) { - this.mouse(BUTTON.wheelDown, MOUSE.press, point.col, point.row, 0); - active.accum += 1; - } - while (active.accum >= 1) { - this.mouse(BUTTON.wheelUp, MOUSE.press, point.col, point.row, 0); - active.accum -= 1; - } - } - active.lastX = event.clientX; - active.lastY = event.clientY; - } - - pointerUp(event) { - if (event.button === 3 || event.button === 4) { - event.preventDefault(); - return; - } - const active = this.pointer?.id === event.pointerId ? this.pointer : null; - if (!active) return; - event.preventDefault(); - const point = this.point(event); - if (active.touch) { - if (active.chrome) this.mouse(BUTTON.left, MOUSE.release, point.col, point.row, modifiers(event)); - else if (!active.scrolling) { - this.mouse(BUTTON.right, MOUSE.press, point.col, point.row, 0); - this.mouse(BUTTON.right, MOUSE.release, point.col, point.row, 0); - } - } else { - this.mouse(active.button, MOUSE.release, point.col, point.row, modifiers(event)); - } - if (this.root.hasPointerCapture?.(event.pointerId)) this.root.releasePointerCapture(event.pointerId); - this.pointer = null; - } - - wheel(event) { - event.preventDefault(); - const point = this.point(event); - if (event.deltaY) this.mouse(event.deltaY < 0 ? BUTTON.wheelUp : BUTTON.wheelDown, MOUSE.press, point.col, point.row, modifiers(event)); - if (event.deltaX) this.mouse(event.deltaX < 0 ? BUTTON.wheelLeft : BUTTON.wheelRight, MOUSE.press, point.col, point.row, modifiers(event)); - } - - paste(event) { - const text = event.clipboardData?.getData("text/plain"); - if (text === undefined) return; - event.preventDefault(); - this.wasm.pardes_paste(this.writeInput(text)); - } - - bindEvents() { - this.root.addEventListener("keydown", (event) => this.key(event)); - this.root.addEventListener("paste", (event) => this.paste(event)); - this.root.addEventListener("contextmenu", (event) => event.preventDefault()); - this.root.addEventListener("auxclick", (event) => event.preventDefault()); - // Mouse events retain additional button presses while another button is held. - this.root.addEventListener("mousedown", (event) => this.mouseDown(event)); - this.root.addEventListener("pointerdown", (event) => this.pointerDown(event)); - this.root.addEventListener("pointermove", (event) => this.pointerMove(event)); - this.root.addEventListener("pointerup", (event) => this.pointerUp(event)); - this.root.addEventListener("pointercancel", (event) => this.pointerUp(event)); - this.root.addEventListener("pointerleave", () => this.wasm.pardes_pointer_leave()); - this.root.addEventListener("wheel", (event) => this.wheel(event), { passive: false }); - globalThis.addEventListener?.("resize", () => this.resize()); - } -} - -export function browserHost() { - const host = { wasm: null }; - const view = (ptr, len) => new Uint8Array(host.wasm.memory.buffer, ptr, len); - const text = (ptr, len) => decoder.decode(view(ptr, len)); - host.imports = { - pardes: { - host_open_link: (ptr, len) => { - globalThis.open?.(text(ptr, len), "_blank", "noopener,noreferrer"); - }, - host_set_clipboard: (ptr, len) => { - globalThis.navigator?.clipboard?.writeText(text(ptr, len)).catch(() => {}); - }, - // Async and permission-gated, unlike every other import here: a refused - // or unsupported read is simply a paste that never happens, which is - // what the core already tolerates from an empty clipboard. - host_read_clipboard: () => { - globalThis.navigator?.clipboard?.readText() - .then((clip) => host.wasm.pardes_paste(putInput(host.wasm, clip))) - .catch(() => {}); - }, - // A file a page writes is a download; the core already resolved the path - // and the bytes, and the Blob needs its own copy of them. - host_download: (pathPtr, pathLen, ptr, len) => { - const name = text(pathPtr, pathLen).split("/").pop() || "pardes.txt"; - download(view(ptr, len).slice(), name, "text/plain;charset=utf-8"); - }, - }, - }; - return host; -} - -export async function instantiate(url = "./pardes.wasm") { - const host = browserHost(); - const response = await fetch(url); - if (!response.ok) throw new Error(`fetch ${url}: HTTP ${response.status}`); - if (WebAssembly.instantiateStreaming) { - try { - const { instance } = await WebAssembly.instantiateStreaming(response.clone(), host.imports); - host.wasm = instance.exports; - return host.wasm; - } catch (error) { - if (!/mime|content-type/i.test(String(error))) throw error; - } - } - const { instance } = await WebAssembly.instantiate(await response.arrayBuffer(), host.imports); - host.wasm = instance.exports; - return host.wasm; -} - -export async function boot(root, url = "./pardes.wasm") { - if (!root) throw new Error("Pardes DOM root is missing"); - const wasm = await instantiate(url); - const runtime = new PardesRuntime(root, wasm); - runtime.start(); - const test = { - grid: () => runtime.renderer.snapshot, - cellPoint: (col, row) => runtime.cellPoint(col, row), - }; - globalThis.pardes = { runtime, wasm, test }; - return runtime; -} - -function applyStyle(cell, fgCode, bgCode, attrs, cursor, cursorBar) { - let fg = color(fgCode, DEFAULT_FG); - let bg = color(bgCode, DEFAULT_BG); - if (attrs & (1 << 4)) [fg, bg] = [bg, fg]; - if (attrs & (1 << 5)) fg = bg; - if (attrs & (1 << 1)) fg = dim(fg); - cell.style.color = fg; - cell.style.backgroundColor = bg; - cell.style.fontWeight = attrs & 1 ? "700" : "400"; - cell.style.fontStyle = attrs & (1 << 2) ? "italic" : "normal"; - const underline = (attrs >>> 8) & 7; - cell.style.textDecorationLine = `${underline ? "underline " : ""}${attrs & (1 << 6) ? "line-through" : ""}`.trim() || "none"; - cell.style.textDecorationStyle = ["solid", "solid", "double", "wavy", "dotted", "dashed"][underline] || "solid"; - cell.style.setProperty("--cell-fg", fg); - cell.style.setProperty("--cell-bg", bg); - cell.classList.toggle("is-cursor", cursor); - cell.classList.toggle("is-bar", cursor && cursorBar); - cell.classList.toggle("is-blinking", Boolean(attrs & (1 << 3))); - cell.classList.toggle("is-tagline", Boolean(attrs & ATTR_TAGLINE)); -} - -function color(encoded, fallback) { - if (encoded === 0x01000000) return fallback; - if ((encoded & 0xff000000) === 0x02000000) return indexedColor(encoded & 0xff); - return `#${(encoded & 0xffffff).toString(16).padStart(6, "0")}`; -} - -function indexedColor(index) { - const ansi = [ - "#000000", "#cc0000", "#4e9a06", "#c4a000", "#3465a4", "#75507b", "#06989a", "#d3d7cf", - "#555753", "#ef2929", "#8ae234", "#fce94f", "#729fcf", "#ad7fa8", "#34e2e2", "#eeeeec", - ]; - if (index < 16) return ansi[index]; - if (index >= 232) { - const level = 8 + (index - 232) * 10; - return rgb(level, level, level); - } - const n = index - 16; - const level = (part) => part === 0 ? 0 : 55 + part * 40; - return rgb(level(Math.floor(n / 36)), level(Math.floor(n / 6) % 6), level(n % 6)); -} - -function dim(value) { - const n = Number.parseInt(value.slice(1), 16); - return rgb(((n >>> 16) & 0xff) * 0.6, ((n >>> 8) & 0xff) * 0.6, (n & 0xff) * 0.6); -} - -function rgb(r, g, b) { - return `#${[r, g, b].map((part) => Math.round(part).toString(16).padStart(2, "0")).join("")}`; -} - -function modifiers(event) { - return (event.ctrlKey ? 1 : 0) | (event.altKey ? 2 : 0) | (event.shiftKey ? 4 : 0) | (event.metaKey ? 8 : 0); -} - -function pointerButton(button) { - return button === 1 ? BUTTON.middle : button === 2 ? BUTTON.right : button === 3 ? BUTTON.back : button === 4 ? BUTTON.forward : BUTTON.left; -} - -function clamp(value, low, high) { - return Math.max(low, Math.min(high, value)); -} - -function putInput(wasm, text) { - const data = encoder.encode(text); - if (data.length > wasm.pardes_input_capacity()) throw new Error("browser input exceeds wasm transfer buffer"); - new Uint8Array(wasm.memory.buffer, wasm.pardes_input_ptr(), data.length).set(data); - return data.length; -} - -function download(bytes, name, type) { - if (typeof document === "undefined") return; - const url = URL.createObjectURL(new Blob([bytes], { type })); - const anchor = document.createElement("a"); - anchor.href = url; - anchor.download = name; - anchor.click(); - setTimeout(() => URL.revokeObjectURL(url), 0); -} diff --git a/src/web/index.html b/src/web/index.html deleted file mode 100644 index 4012c313..00000000 --- a/src/web/index.html +++ /dev/null @@ -1,17 +0,0 @@ -<!doctype html> -<html lang="en"> -<head> - <meta charset="utf-8"> - <meta name="viewport" content="width=device-width, initial-scale=1"> - <title>Pardes</title> - <link rel="stylesheet" href="pardes.css"> -</head> -<body> - <main id="pardes" class="pardes" role="grid" aria-label="Pardes text environment" tabindex="0"></main> - <noscript>Pardes needs JavaScript to drive its WebAssembly core.</noscript> - <script type="module"> - import { boot } from "./app.mjs"; - boot(document.getElementById("pardes")); - </script> -</body> -</html> diff --git a/src/web/libc.c b/src/web/libc.c deleted file mode 100644 index c49fa03e..00000000 --- a/src/web/libc.c +++ /dev/null @@ -1,152 +0,0 @@ -/* Minimal libc-shaped surface used by Tree-sitter inside the freestanding - * browser module. Allocation lives in web.zig so it shares Zig's wasm heap; - * these routines neither import browser functions nor perform IO. */ -#include <ctype.h> -#include <stdarg.h> -#include <stddef.h> -#include <stdint.h> -#include <stdio.h> -#include <string.h> -#include <wctype.h> - -_Noreturn void abort(void) { - __builtin_trap(); -} - -size_t strlen(const char *str) { - const char *end = str; - while (*end) end++; - return (size_t)(end - str); -} - -char *strchr(const char *str, int character) { - const unsigned char needle = (unsigned char)character; - do { - if ((unsigned char)*str == needle) return (char *)str; - } while (*str++); - return (char *)0; -} - -void *memchr(const void *ptr, int value, size_t count) { - const unsigned char *bytes = (const unsigned char *)ptr; - const unsigned char needle = (unsigned char)value; - for (size_t index = 0; index < count; index++) { - if (bytes[index] == needle) return (void *)(bytes + index); - } - return (void *)0; -} - -int strcmp(const char *lhs, const char *rhs) { - while (*lhs && (unsigned char)*lhs == (unsigned char)*rhs) { - lhs++; - rhs++; - } - return (int)(unsigned char)*lhs - (int)(unsigned char)*rhs; -} - -int strncmp(const char *lhs, const char *rhs, size_t count) { - while (count && *lhs && (unsigned char)*lhs == (unsigned char)*rhs) { - lhs++; - rhs++; - count--; - } - return count ? (int)(unsigned char)*lhs - (int)(unsigned char)*rhs : 0; -} - -char *strncpy(char *restrict dest, const char *restrict src, size_t count) { - char *result = dest; - while (count && *src) { - *dest++ = *src++; - count--; - } - while (count--) *dest++ = '\0'; - return result; -} - -int isprint(int character) { - return character >= 0x20 && character <= 0x7e; -} - -int isdigit(int character) { - return character >= '0' && character <= '9'; -} - -int iswspace(wint_t character) { - return character == ' ' || (character >= '\t' && character <= '\r'); -} - -int iswalnum(wint_t character) { - return iswdigit(character) || iswalpha(character); -} - -int iswalpha(wint_t character) { - return (character >= 'A' && character <= 'Z') || - (character >= 'a' && character <= 'z') || character >= 0x80; -} - -int iswblank(wint_t character) { - return character == ' ' || character == '\t'; -} - -int iswdigit(wint_t character) { - return character >= '0' && character <= '9'; -} - -int iswlower(wint_t character) { - return character >= 'a' && character <= 'z'; -} - -int iswupper(wint_t character) { - return character >= 'A' && character <= 'Z'; -} - -int iswxdigit(wint_t character) { - return iswdigit(character) || (character >= 'A' && character <= 'F') || - (character >= 'a' && character <= 'f'); -} - -wint_t towupper(wint_t character) { - return iswlower(character) ? character - ('a' - 'A') : character; -} - -int vsnprintf(char *restrict buffer, size_t size, const char *restrict format, va_list args) { - (void)format; - (void)args; - if (size) buffer[0] = '\0'; - return 0; -} - -int snprintf(char *restrict buffer, size_t size, const char *restrict format, ...) { - va_list args; - va_start(args, format); - int result = vsnprintf(buffer, size, format, args); - va_end(args); - return result; -} - -int fprintf(FILE *stream, const char *format, ...) { - (void)stream; - (void)format; - return 0; -} - -int fclose(FILE *stream) { - (void)stream; - return 0; -} - -FILE *fdopen(int descriptor, const char *mode) { - (void)descriptor; - (void)mode; - return (FILE *)0; -} - -int fputc(int character, FILE *stream) { - (void)stream; - return character; -} - -int fputs(const char *string, FILE *stream) { - (void)stream; - return (int)strlen(string); -} diff --git a/src/web/libc/include/assert.h b/src/web/libc/include/assert.h deleted file mode 100644 index fd018947..00000000 --- a/src/web/libc/include/assert.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef PARDES_WEB_ASSERT_H -#define PARDES_WEB_ASSERT_H - -#ifndef static_assert -#define static_assert _Static_assert -#endif - -#ifdef NDEBUG -#define assert(expression) ((void)0) -#else -#define assert(expression) ((expression) ? (void)0 : __builtin_trap()) -#endif - -#endif diff --git a/src/web/libc/include/ctype.h b/src/web/libc/include/ctype.h deleted file mode 100644 index 985c8759..00000000 --- a/src/web/libc/include/ctype.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef PARDES_WEB_CTYPE_H -#define PARDES_WEB_CTYPE_H - -int isprint(int character); -int isdigit(int character); - -#endif diff --git a/src/web/libc/include/endian.h b/src/web/libc/include/endian.h deleted file mode 100644 index a047c88f..00000000 --- a/src/web/libc/include/endian.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef PARDES_WEB_ENDIAN_H -#define PARDES_WEB_ENDIAN_H - -#define __LITTLE_ENDIAN 1234 -#define __BIG_ENDIAN 4321 -#define __BYTE_ORDER __LITTLE_ENDIAN - -#define htole16(value) (value) -#define le16toh(value) (value) -#define htole32(value) (value) -#define le32toh(value) (value) -#define htole64(value) (value) -#define le64toh(value) (value) -#define htobe16(value) __builtin_bswap16(value) -#define be16toh(value) __builtin_bswap16(value) -#define htobe32(value) __builtin_bswap32(value) -#define be32toh(value) __builtin_bswap32(value) -#define htobe64(value) __builtin_bswap64(value) -#define be64toh(value) __builtin_bswap64(value) - -#endif diff --git a/src/web/libc/include/inttypes.h b/src/web/libc/include/inttypes.h deleted file mode 100644 index 7e795746..00000000 --- a/src/web/libc/include/inttypes.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef PARDES_WEB_INTTYPES_H -#define PARDES_WEB_INTTYPES_H - -#include <stdint.h> - -#define PRId32 "d" - -#endif diff --git a/src/web/libc/include/limits.h b/src/web/libc/include/limits.h deleted file mode 100644 index 6ba31375..00000000 --- a/src/web/libc/include/limits.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef PARDES_WEB_LIMITS_H -#define PARDES_WEB_LIMITS_H - -#define CHAR_BIT __CHAR_BIT__ -#define INT_MAX __INT_MAX__ -#define UINT_MAX (__INT_MAX__ * 2U + 1U) -#define USHRT_MAX (__SHRT_MAX__ * 2U + 1U) - -#endif diff --git a/src/web/libc/include/stdio.h b/src/web/libc/include/stdio.h deleted file mode 100644 index 92895054..00000000 --- a/src/web/libc/include/stdio.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef PARDES_WEB_STDIO_H -#define PARDES_WEB_STDIO_H - -#include <stdarg.h> -#include <stddef.h> - -typedef struct PardesWebFile FILE; - -#define stderr ((FILE *)0) - -int fprintf(FILE *stream, const char *format, ...); -int fclose(FILE *stream); -FILE *fdopen(int descriptor, const char *mode); -int fputc(int character, FILE *stream); -int fputs(const char *string, FILE *stream); -int snprintf(char *restrict buffer, size_t size, const char *restrict format, ...); -int vsnprintf(char *restrict buffer, size_t size, const char *restrict format, va_list args); - -#endif diff --git a/src/web/libc/include/stdlib.h b/src/web/libc/include/stdlib.h deleted file mode 100644 index cb280904..00000000 --- a/src/web/libc/include/stdlib.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef PARDES_WEB_STDLIB_H -#define PARDES_WEB_STDLIB_H - -#include <stddef.h> - -#ifndef NULL -#define NULL ((void *)0) -#endif - -void *malloc(size_t size); -void *calloc(size_t count, size_t size); -void *realloc(void *ptr, size_t size); -void free(void *ptr); -_Noreturn void abort(void); - -#endif diff --git a/src/web/libc/include/string.h b/src/web/libc/include/string.h deleted file mode 100644 index 7e5b8783..00000000 --- a/src/web/libc/include/string.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef PARDES_WEB_STRING_H -#define PARDES_WEB_STRING_H - -#include <stddef.h> - -void *memchr(const void *ptr, int value, size_t count); -int memcmp(const void *lhs, const void *rhs, size_t count); -void *memcpy(void *restrict dest, const void *restrict src, size_t count); -void *memmove(void *dest, const void *src, size_t count); -void *memset(void *dest, int value, size_t count); -size_t strlen(const char *str); -char *strchr(const char *str, int character); -int strcmp(const char *lhs, const char *rhs); -int strncmp(const char *lhs, const char *rhs, size_t count); -char *strncpy(char *restrict dest, const char *restrict src, size_t count); - -#endif diff --git a/src/web/libc/include/wchar.h b/src/web/libc/include/wchar.h deleted file mode 100644 index 4888631e..00000000 --- a/src/web/libc/include/wchar.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef PARDES_WEB_WCHAR_H -#define PARDES_WEB_WCHAR_H - -#include <stddef.h> -#include <wctype.h> - -typedef __WCHAR_TYPE__ wchar_t; - -#endif diff --git a/src/web/libc/include/wctype.h b/src/web/libc/include/wctype.h deleted file mode 100644 index 77bbabe9..00000000 --- a/src/web/libc/include/wctype.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef PARDES_WEB_WCTYPE_H -#define PARDES_WEB_WCTYPE_H - -#include <stddef.h> - -typedef unsigned int wint_t; - -int iswalnum(wint_t character); -int iswalpha(wint_t character); -int iswblank(wint_t character); -int iswdigit(wint_t character); -int iswlower(wint_t character); -int iswspace(wint_t character); -int iswupper(wint_t character); -int iswxdigit(wint_t character); -wint_t towupper(wint_t character); - -#endif diff --git a/src/web/pardes.css b/src/web/pardes.css deleted file mode 100644 index 5cb44f88..00000000 --- a/src/web/pardes.css +++ /dev/null @@ -1,99 +0,0 @@ -@font-face { - font-family: "Pardes Mono"; - src: url("./AdwaitaMono-Regular.ttf") format("truetype"); - font-display: swap; -} - -:root { - color-scheme: dark; - --pardes-bg: #121212; - --pardes-fg: #cccccc; - --pardes-font-size: 18px; - --pardes-cell-width: 9.333333px; - --pardes-cell-height: 19.459459px; -} - -html, -body { - width: 100%; - height: 100%; - margin: 0; - overflow: hidden; - background: var(--pardes-bg); -} - -.pardes { - box-sizing: border-box; - width: 100vw; - height: 100vh; - overflow: hidden; - color: var(--pardes-fg); - background: var(--pardes-bg); - font-family: "Pardes Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - font-size: var(--pardes-font-size); - font-variant-ligatures: none; - line-height: 1; - outline: none; - touch-action: none; - user-select: text; - cursor: text; -} - -.pardes-row { - display: flex; - width: max-content; - height: var(--pardes-cell-height); - line-height: var(--pardes-cell-height); - white-space: pre; -} - -.pardes-cell { - box-sizing: border-box; - display: inline-block; - flex: 0 0 var(--pardes-cell-width); - width: var(--pardes-cell-width); - height: var(--pardes-cell-height); - overflow: hidden; - text-align: left; - white-space: pre; -} - -/* The browser keeps the canonical DOM grid body-sized for native text - selection. The inherited fixed line-height centers the smaller face, and - each glyph remains centered in its original DOM column. */ -.pardes-cell.is-tagline { - font-size: var(--pardes-tagline-font-size, 100%); - text-align: center; -} - -.pardes-cell.is-cursor { - color: var(--cell-bg) !important; - background: var(--cell-fg) !important; -} - -.pardes-cell.is-cursor.is-bar { - color: var(--cell-fg) !important; - background: var(--cell-bg) !important; - box-shadow: inset 2px 0 var(--cell-fg); -} - -.pardes-cell.is-blinking { - animation: pardes-blink 1s step-end infinite; -} - -.pardes-probe { - position: fixed; - left: -10000px; - top: -10000px; - width: var(--pardes-cell-width); - height: var(--pardes-cell-height); - visibility: hidden; -} - -@keyframes pardes-blink { - 50% { opacity: 0; } -} - -@media (prefers-reduced-motion: reduce) { - .pardes-cell.is-blinking { animation: none; } -} diff --git a/src/web/zstbi.zig b/src/web/zstbi.zig deleted file mode 100644 index 76b144f7..00000000 --- a/src/web/zstbi.zig +++ /dev/null @@ -1,30 +0,0 @@ -//! Freestanding image-decoder shim. -//! -//! The browser core has no libc or C allocator ABI. Image bytes still survive -//! dumps, but decoding belongs in the JavaScript IO layer rather than pulling -//! stb_image and an Emscripten runtime into the state machine. - -const std = @import("std"); - -pub fn init(_: std.Io, _: std.mem.Allocator) void {} -pub fn deinit() void {} - -pub const Image = struct { - data: []u8 = &.{}, - width: u32 = 0, - height: u32 = 0, - num_components: u32 = 4, - bytes_per_component: u32 = 1, - bytes_per_row: u32 = 0, - is_hdr: bool = false, - - pub fn loadFromMemory(_: []const u8, _: u32) !Image { - return error.ImageDecodeUnavailable; - } - - pub fn resize(_: *const Image, _: u32, _: u32) Image { - return .{}; - } - - pub fn deinit(_: *Image) void {} -}; diff --git a/test/output.zig b/test/output.zig index 3d92e867..eb4da9b3 100644 --- a/test/output.zig +++ b/test/output.zig @@ -493,7 +493,6 @@ fn configFixture(tmp: *std.testing.TmpDir, content: ?[]const u8, buf: *[4096]u8) } test "Config opens the startup file, and a second Config goes back to its pane" { - if (comptime !pardes.hosted) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -521,7 +520,6 @@ test "Config opens the startup file, and a second Config goes back to its pane" } test "Config with no startup file opens a pane of its name, and Save makes its directory" { - if (comptime !pardes.hosted) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [4096]u8 = undefined; @@ -573,7 +571,6 @@ test "EffectCode lists readable virtual sources used by this backend" { .tui => "/virtual/src/tui/panel_compositor.zig", .gui => "/virtual/shaders/ui.vert.glsl", .macos => "/virtual/src/macos/Sources/ScenePostprocessor.swift", - .web => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, out.content, backend_source) != null); var paths = std.mem.tokenizeScalar(u8, out.content, '\n'); @@ -759,7 +756,6 @@ test "LookNext/LookPrev skips formatted context and selects comment match locati } test "LookNext/LookPrev selects one output location per row and opens nothing" { - if (platform == .web) return; var cwd_buf: [4096]u8 = undefined; var path_buf: [4096]u8 = undefined; const paths = try projectPaths(&cwd_buf, &path_buf); @@ -794,7 +790,6 @@ test "LookNext/LookPrev selects one output location per row and opens nothing" { } test "LookPrev exactly reverses LookNext across output panes and the ring seam" { - if (platform == .web) return; var cwd_buf: [4096]u8 = undefined; var path_buf: [4096]u8 = undefined; const paths = try projectPaths(&cwd_buf, &path_buf); @@ -985,7 +980,6 @@ test "Look ignores slash-only comment markers while retaining root and real path for ([_][]const u8{ "(//),", "///!" }) |marker| try std.testing.expectEqual(@as(?look.Span, null), look.wordSpan(null, marker, ".", &realbuf)); try std.testing.expectEqual(@as(?look.Span, null), look.lineSpan(null, " // ordinary comment", ".", &realbuf)); - if (platform == .web) return; try std.testing.expect(look.resolve(null, "/", ".", &realbuf) == .dir); try std.testing.expect(look.wordSpan(null, "/", ".", &realbuf) != null); var pathbuf: [4096]u8 = undefined; diff --git a/test/panes.zig b/test/panes.zig index 6decd43d..9e4886fb 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -2579,7 +2579,6 @@ const TerminalTests = struct { } test "fresh-shell greeting waits for OSC 133 B input phase" { - if (pardes.platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[0].?; @@ -2614,7 +2613,6 @@ const TerminalTests = struct { } test "the greeting is dropped, never typed later, once something ran or was typed first" { - if (pardes.platform == .web) return; for ([_][]const u8{ // A command ran before the first prompt was seen at rest. "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07\x1b]133;C;aid=pardes\x07out\r\n\x1b]133;D;0;aid=pardes\x07\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07", @@ -2638,7 +2636,6 @@ const TerminalTests = struct { } test "fresh-shell commands preserve order and wait for OSC 133 B" { - if (pardes.platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} // the host has not acknowledged spawn yet @@ -2677,7 +2674,6 @@ const TerminalTests = struct { } test "unmarked fresh shells omit the automatic greeting" { - if (pardes.platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{}); defer p.deinit(); const pane = p.panes[0].?; diff --git a/test/pdf.zig b/test/pdf.zig index 053e45dc..460a5734 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -94,7 +94,7 @@ const PdfLinkTests = struct { } test "PDF links activate embedded URLs and blank internal annotations" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try init(tmp); @@ -112,7 +112,7 @@ const PdfLinkTests = struct { } test "PDF links offer distinct visible destinations and do not duplicate the same URL" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try init(tmp); @@ -152,7 +152,7 @@ const PdfLinkTests = struct { } test "PDF links hover clears on leave page and reload while right drag chooses Look text" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try init(tmp); @@ -201,7 +201,7 @@ test { } test "PDF mounted bytes own their source after the caller frees it" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const source = try pardes.filesystem.readFile(gpa, "docs/design.pdf"); var document = pdf_impl.Document.openBytes(source) catch |err| { @@ -224,7 +224,7 @@ test "PDF mounted bytes own their source after the caller frees it" { } test "explicit OS PDF opens and reloads keep their namespace path" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -264,7 +264,7 @@ test "PDF feature gates keep argv and builtin behavior coherent" { try std.testing.expectEqualStrings("tz", config.leader_path.get(maybe_fit.?).?); try std.testing.expectEqualStrings("ti", config.leader_path.get(maybe_tint.?).?); try std.testing.expectEqualStrings("ts", config.leader_path.get(maybe_sections.?).?); - } else if (platform != .web) { + } else { const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", .cols = 80, @@ -279,7 +279,7 @@ test "PDF feature gates keep argv and builtin behavior coherent" { } test "PdfSections Look follows the exact owning PDF, not an equal path" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -340,7 +340,7 @@ test "SDL PDF raster policy is materially denser than Kitty" { } test "watched PDF reload replaces MuPDF state and preserves the reading view" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); @@ -482,7 +482,7 @@ test "watched PDF reload replaces MuPDF state and preserves the reading view" { } test "PDF reload does not re-center an already revealed matching search" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const fixture = try pardes.filesystem.readFile(gpa, "docs/design.pdf"); defer gpa.free(fixture); @@ -538,7 +538,7 @@ test "PDF reload does not re-center an already revealed matching search" { } test "MuPDF pane renders, navigates, searches, and round-trips its page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -881,7 +881,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { } test "a fling's banded pages show the reader exactly what whole pages would" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; // The contract fast scrolling is allowed to change: HOW pixels are carried // (a strip of a page instead of the page) but never WHICH pixels arrive. So @@ -976,7 +976,7 @@ fn expectNearRows(expected: []const u8, got: []const u8) !void { } test "a tall page is drawn at the display's resolution, in bands that are the whole page's rows" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; // The page is fifteen A4 heights tall. Squeezed whole into the raster // budget it was a third as wide as the pane and blown up, blurred; it is @@ -1145,7 +1145,7 @@ fn copySourceRect( } test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape leaves at once" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1226,7 +1226,7 @@ test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape lea } test "PDF continuous strip renders every intersecting short page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1281,7 +1281,7 @@ test "PDF continuous strip renders every intersecting short page" { } test "PDF tint resolves a theme's null page colors to its chrome" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", @@ -1301,7 +1301,7 @@ test "PDF tint resolves a theme's null page colors to its chrome" { } test "PDF tint and tinted theme changes rebuild every visible raster only" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1441,7 +1441,7 @@ test "PDF tint and tinted theme changes rebuild every visible raster only" { } test "PDF resize preserves page-relative document position" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1487,7 +1487,7 @@ test "PDF resize preserves page-relative document position" { } test "PDF pane geometry change preserves its page-relative position" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1544,7 +1544,7 @@ test "PDF pane geometry change preserves its page-relative position" { } test "PDF n/N addresses and reveals distinct MuPDF hits on one page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -1644,7 +1644,7 @@ test "PDF n/N addresses and reveals distinct MuPDF hits on one page" { } test "PDF native mouse selection, Look, and highlights share page geometry" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ @@ -2001,7 +2001,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { } test "Esc back into a PDF keeps the offset within its page" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2043,7 +2043,7 @@ test "Esc back into a PDF keeps the offset within its page" { } test "PDF Back and Forward clear selections and land on recorded pages" { - if (!pdf_enabled or platform == .web) return error.SkipZigTest; + if (!pdf_enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", .cols = 80, .rows = 28 }); defer p.deinit(); p.native_images = true; @@ -2070,7 +2070,7 @@ test "PDF Back and Forward clear selections and land on recorded pages" { } test "a PDF's fit and tint, and Collapse, read in its ctl and come back from a Dump" { - if (!pdf_enabled or platform == .web) return; + if (!pdf_enabled) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2121,7 +2121,7 @@ fn stripAtPlace(p: *Pardes, pane: *pardes.Pane, page: usize, fraction: f64) !f64 } test "a PDF's jumps: Back after a far jump returns to the exact offset, two places on one page are two entries" { - if (!pdf_enabled or platform == .web) return error.SkipZigTest; + if (!pdf_enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .file = jumpPdf(), .cols = 80, .rows = 28 }); defer p.deinit(); p.native_images = true; @@ -2156,7 +2156,7 @@ test "a PDF's jumps: Back after a far jump returns to the exact offset, two plac } test "a PDF's jumps: JumpScope file keeps to the PDF, and a closed PDF reopens at its place" { - if (!pdf_enabled or platform == .web) return error.SkipZigTest; + if (!pdf_enabled) return error.SkipZigTest; // Recent keeps a file by the path it was opened as: a real one here, // as a Look opens one. var cwd_buf: [4096]u8 = undefined; diff --git a/test/pdf_sections_bench.zig b/test/pdf_sections_bench.zig index 4ab4b5c4..30b89e09 100644 --- a/test/pdf_sections_bench.zig +++ b/test/pdf_sections_bench.zig @@ -432,7 +432,7 @@ fn summarize( } /// A host benchmark compiler barrier. MuPDF benchmarks are build-and-run -/// steps, so they never target the freestanding web backend; an empty volatile +/// steps, so they run on a native backend only; an empty volatile /// asm with only the abstract memory clobber is valid on every native backend /// Zig can run here and costs no machine instruction. inline fn compilerBarrier() void { diff --git a/test/web-snapshots/README.md b/test/web-snapshots/README.md deleted file mode 100644 index 999e8fad..00000000 --- a/test/web-snapshots/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Browser interaction tests - -`zig build web-snap` loads `touch.dump` (`python3 -B tools/web_fixture.py <pardes> test/web-snapshots/touch.dump` makes it: a native session on `touch-fixture.zig` at 100x30, theme helix, Verbose off) and runs `touch.mjs` in Chromium. -The fixed source fixture exercises complete keyword styles, touch Look through -the self filesystem, separator resizing, and scrolling without another Look. -Assertions locate current pane geometry; no live project source or author paths -are captured in goldens. diff --git a/test/web-snapshots/touch-fixture.zig b/test/web-snapshots/touch-fixture.zig deleted file mode 100644 index b1d5d81e..00000000 --- a/test/web-snapshots/touch-fixture.zig +++ /dev/null @@ -1,58 +0,0 @@ -pub fn choose(value: u32) []const u8 { - if (value == 42) return "touch fixture"; - return "/virtual/pane/1/body"; -} - -pub const rows = [_]u32{ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, -};
\ No newline at end of file diff --git a/test/web-snapshots/touch.dump b/test/web-snapshots/touch.dump Binary files differdeleted file mode 100644 index bcc58352..00000000 --- a/test/web-snapshots/touch.dump +++ /dev/null diff --git a/test/web-snapshots/touch.mjs b/test/web-snapshots/touch.mjs deleted file mode 100644 index 6ced7a29..00000000 --- a/test/web-snapshots/touch.mjs +++ /dev/null @@ -1,302 +0,0 @@ -import assert from "node:assert/strict"; - -function tags(frame) { - // This fixture has workspace and column bars in its first two rows; a - // pane's tag text starts after the two-cell marker gutter. - return frame.styleRows.flatMap((cells, y) => y > 1 && /^\s{2}\S/.test(frame.lines[y]) && cells.some((cell) => cell[2] & 128) ? [y] : []); -} - -function pane(frame, name) { - const rows = tags(frame); - const top = rows.find((row) => frame.lines[row].includes(name)); - assert.notEqual(top, undefined, `missing pane ${name}`); - const bottom = rows.find((row) => row > top) ?? frame.rows; - return { top, bottom, lines: frame.lines.slice(top + 1, bottom) }; -} - -// helix's keyword and string/number colours (src/themes/helix.zig). -const KW = 0xd776f9, STR = 0xf3cd7a; - -function styled(frame) { - const source = pane(frame, "touch-fixture.zig"); - for (const [line, word, fg, bold] of [ - ["pub fn choose", "fn", KW, false], - ["pub fn choose", "choose", 0xbdbdbd, false], - ["if (value", "if", KW, false], - ["if (value", "42", STR, false], - ["if (value", '"touch fixture"', STR, false], - ]) { - const row = source.lines.findIndex((text) => text.includes(line)); - assert(row >= 0, `missing source line ${line}`); - const col = source.lines[row].indexOf(word); - for (let x = col; x < col + word.length; x++) { - const style = frame.styleRows[source.top + 1 + row][x]; - assert.equal(style[0], fg, `${word} cell ${x - col} foreground`); - assert.equal(Boolean(style[2] & 1), bold, `${word} cell ${x - col} bold`); - } - } - for (const [row, line] of source.lines.entries()) { - const number = /\b(\d+),/.exec(line); - if (!number) continue; - for (let x = number.index; x < number.index + number[1].length; x++) { - assert.equal(frame.styleRows[source.top + 1 + row][x][0], STR, `row ${row} number foreground`); - } - } -} - -export default async function ({ grid, touch, wait, stable, delay, evaluate, mouse }) { - await stable(100, 5000); - const compactGeometry = await evaluate(`(() => { - const root = document.createElement("div"); - root.className = "pardes"; - root.style.cssText = "position:fixed;left:0;top:0;width:20px;height:40px"; - document.body.append(root); - const memory = new WebAssembly.Memory({initial:1}); - const bytes = new Uint8Array(memory.buffer), data = new DataView(memory.buffer); - for (const [base,count] of [[0,4],[1024,10]]) for(let i=0;i<count;i++) { - const off=base+i*20; bytes[off]=65+i; bytes[off+18]=1; - data.setUint32(off+8,0xffffff,true); data.setUint32(off+12,0x123456,true); - if(base && i<2) data.setUint16(off+16,128,true); - } - const values=[3,2,1,0,0,2,2,42,0,2,1,1]; - const wasm={memory,pardes_gui_tagline_font_percent:()=>50,pardes_frame:()=>4, - pardes_pointer_shape:()=>0,pardes_frame_cols:()=>2,pardes_frame_rows:()=>2, - pardes_frame_ptr:()=>0,pardes_cursor_x:()=>65535,pardes_cursor_y:()=>65535,pardes_cursor_bar:()=>0, - pardes_body_layer_limit:()=>1,pardes_body_layer_value:(_,field)=>values[field],pardes_body_layer_cells:()=>1024}; - const renderer=new pardes.runtime.renderer.constructor(root,wasm); - Object.assign(renderer,{cellWidth:10,cellHeight:20,taglineWidth:5,taglineHeight:10}); - renderer.render(); - const layer=renderer.layerRoot.firstChild, rect=layer.getBoundingClientRect(); - const bands=[...layer.children].slice(0,3).map(node=>{ - const box=node.getBoundingClientRect();return [box.y-rect.y,box.height]; - }); - const cursor=layer.querySelector('.is-cursor'); - renderer.render(); - const result={bands,height:rect.height,clipped:getComputedStyle(layer).overflow, - cursor:cursor?.textContent,cached:renderer.layerRoot.firstChild===layer}; - values[0]=5;values[2]=3;values[6]=4;values[11]=0;values[12]=1;values[13]=1; - renderer.render(); - const borders=()=>[...renderer.layerRoot.querySelectorAll('[data-context-border]')].map(node=>parseFloat(node.style.top)); - result.gapBorders=borders(); - const withGap=renderer.layerRoot.firstChild; - values[12]=0; - renderer.render(); - result.closedGapBorders=borders(); - result.borderChangeInvalidates=renderer.layerRoot.firstChild!==withGap; - // The 13 fields of a tag layer: a one-line tag, its caret on line 0. - const tagValues=[2,2,0,42,1,0,1,1,1,1,0x334455,1,0]; - wasm.pardes_tag_layer_limit=()=>1; - wasm.pardes_tag_layer_value=(_,field)=>tagValues[field]; - wasm.pardes_tag_layer_cells=()=>1024; - wasm.pardes_tagline_band_offset=()=>2560; - renderer.render(); - const tag=renderer.tagRoot.firstChild; - result.tag={left:parseFloat(tag.style.left),top:parseFloat(tag.style.top),width:parseFloat(tag.style.width), - text:tag.textContent,cursor:tag.querySelector('.is-cursor')?.textContent, - gripVisible:renderer.cells[0].style.visibility,covered:renderer.cells[1].style.visibility, - background:tag.style.backgroundColor}; - renderer.render(); - result.tag.cached=renderer.tagRoot.firstChild===tag; - tagValues[10]=0x556677; - renderer.render(); - result.tag.bgInvalidates=renderer.tagRoot.firstChild!==tag; - wasm.pardes_tag_text_inset=()=>3; - tagValues[1]=1;tagValues[4]=3;tagValues[5]=0; - bytes[0]=32;data.setUint32(8,0x778899,true); - renderer.render(); - const columnGrip=renderer.tagRoot.querySelector('[data-tag-grip]'); - const marks=node=>[...node.children].map(mark=>[parseFloat(mark.style.left),parseFloat(mark.style.top),parseFloat(mark.style.width)]); - result.columnMarks=columnGrip ? marks(columnGrip) : []; - tagValues[1]=2;tagValues[5]=1;bytes[40]=32;data.setUint32(48,0x778899,true); - renderer.render(); - result.paneMarks=marks(renderer.tagRoot.querySelector('[data-tag-grip]')); - const inkCenter=canvas=>{ - const pixels=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data; - let minX=canvas.width,minY=canvas.height,maxX=-1,maxY=-1; - for(let y=0;y<canvas.height;y++) for(let x=0;x<canvas.width;x++) if(pixels[(y*canvas.width+x)*4+3]>8) { - minX=Math.min(minX,x);maxX=Math.max(maxX,x);minY=Math.min(minY,y);maxY=Math.max(maxY,y); - } - return {x:(minX+maxX+1-canvas.width)/2,y:(minY+maxY+1-canvas.height)/2,visible:maxX>=0}; - }; - Object.assign(renderer,{cellWidth:20,cellHeight:40,taglineWidth:10,taglineHeight:28}); - renderer.cells[2].style.font='18px serif'; - renderer.resetGripMetrics(); - result.modeGlyphs=[]; - for(const glyph of ['^','$']) { - bytes[40]=glyph.charCodeAt(0); - renderer.render(); - const canvas=renderer.tagRoot.querySelector('canvas[data-tag-grip]'); - const center=inkCenter(canvas),size=renderer.gripMetrics.size; - renderer.render(); - result.modeGlyphs.push({...center,suppressed:renderer.cells[2].textContent===' ', - reused:renderer.tagRoot.querySelector('canvas[data-tag-grip]')===canvas, - measuredOnce:renderer.gripMetrics.size===size}); - } - const glyphCell=renderer.cells[2]; - glyphCell.style.font='italic 24px serif'; - renderer.resetGripMetrics(); - const italic=renderer.drawGripGlyph(glyphCell,{text:'j',attrs:2},40,40); - result.italic=inkCenter(italic); - const saved=renderer.gripMetrics.values().next().value; - renderer.drawGripGlyph(glyphCell,{text:'j',attrs:2},40,40); - result.italic.cached=renderer.gripMetrics.size===1 && renderer.gripMetrics.values().next().value===saved; - document.fonts.dispatchEvent(new Event('loadingdone')); - result.fontInvalidation=renderer.gripMetrics.size===0 && renderer.gripFonts.size===0 && renderer.tagNodes.size===0; - glyphCell.style.font='italic 30px serif'; - renderer.drawGripGlyph(glyphCell,{text:'j',attrs:2},40,40); - result.fontRemeasured=renderer.gripMetrics.values().next().value!==saved && [...renderer.gripFonts.values()][0].includes('30px'); - root.remove();return result; - })()`); - assert.deepEqual(compactGeometry.bands, [[0,10],[10,20],[30,20]], "compact headers release real height to additional body rows"); - assert.equal(compactGeometry.height,40); - assert.equal(compactGeometry.clipped,"hidden"); - assert.equal(compactGeometry.cursor,"E"); - assert(compactGeometry.cached,"unchanged compact layers reuse their DOM nodes"); - assert.deepEqual(compactGeometry.gapBorders,[20,30],"source gaps and final header have separators, consecutive headers do not"); - assert.deepEqual(compactGeometry.closedGapBorders,[30]); - assert(compactGeometry.borderChangeInvalidates,"separator changes invalidate an otherwise unchanged layer"); - - assert.deepEqual(compactGeometry.tag, {left:10,top:10,width:10,text:"AB",cursor:"B", - gripVisible:"",covered:"hidden",background:"rgb(51, 68, 85)",cached:true,bgInvalidates:true}, - "tag text uses its own columns after a fixed body-width grip, with cursor and cached base background"); - - assert.deepEqual(compactGeometry.columnMarks,[],"column handles have no mark"); - assert.deepEqual(compactGeometry.paneMarks,[[7,33,6],[7,36,6]],"pane handles keep their physical mark geometry"); - - for (const glyph of [...compactGeometry.modeGlyphs,compactGeometry.italic]) { - assert(glyph.visible,"mode indicator has visible rasterized ink"); - assert(Math.abs(glyph.x)<=1 && Math.abs(glyph.y)<=1,`ink center offset ${glyph.x},${glyph.y}`); - } - for (const glyph of compactGeometry.modeGlyphs) assert(glyph.suppressed && glyph.reused && glyph.measuredOnce,"mode ink is drawn once and cached"); - assert(compactGeometry.italic.cached,"asymmetric italic glyph reuses cached ink bounds"); - assert(compactGeometry.fontInvalidation && compactGeometry.fontRemeasured,"font loading clears cached faces and bounds before remeasurement"); - - let frame = await grid(); - assert.equal(tags(frame).length, 1); - styled(frame); - const link = "/virtual/pane/1/body"; - const row = frame.lines.findIndex((text) => text.includes(link)); - const col = frame.lines[row].indexOf(link) + 5; - let finger = await touch("down", 1, col, row, null); - finger = await touch("move", 1, col + 0.2, row + 0.1, finger); - await touch("up", 1, col + 0.2, row + 0.1, finger); - await wait(async () => tags(await grid()).length === 2, 5000, "Look opening the reflected body"); - await stable(100, 5000); - frame = await grid(); - styled(frame); - const reflected = pane(frame, link); - assert(reflected.lines.some((text) => text.includes("pub fn choose"))); - const original = pane(frame, "touch-fixture.zig"); - const sharedRows = Math.min(reflected.lines.length, original.lines.length); - assert(sharedRows >= 6); - assert.deepEqual(reflected.lines.slice(0, sharedRows), original.lines.slice(0, sharedRows), "Look must read the source pane body"); - - const center = Math.floor(frame.cols / 2); - // No rule between panes: the lower one's grip, its tag's gutter, moves it. - const separator = Math.max(original.top, reflected.top); - const distance = original.top < reflected.top ? 4 : -4; - finger = await touch("down", 2, 0, separator, null); - for (let step = 1; step <= 8; step++) { - finger = await touch("move", 2, 0, separator + distance * step / 8, finger); - await delay(20); - } - await touch("up", 2, 0, separator + distance, finger); - await stable(100, 5000); - frame = await grid(); - assert.equal(tags(frame).length, 2); - const resized = pane(frame, "touch-fixture.zig"); - assert(resized.lines.length >= original.lines.length + 3, "separator drag must resize, not scroll the body"); - assert.equal(resized.lines[0], original.lines[0], "resizing must preserve the source viewport"); - styled(frame); - - const beforeScroll = resized.lines[0]; - const reflectedBeforeScroll = pane(frame, link).lines; - const from = resized.bottom - 3; - const to = Math.max(resized.top + 2, from - 7); - finger = await touch("down", 3, center, from, null); - for (let step = 1; step <= 12; step++) { - finger = await touch("move", 3, center, from + (to - from) * step / 12, finger); - await delay(20); - } - await touch("up", 3, center, to, finger); - await stable(100, 5000); - frame = await grid(); - assert.equal(tags(frame).length, 2, "scroll must not also Look"); - const scrolled = pane(frame, "touch-fixture.zig"); - assert.equal(scrolled.top, resized.top, "body scrolling must not resize"); - assert.notEqual(scrolled.lines[0], beforeScroll, "source must scroll"); - assert(Number(scrolled.lines[0].trim().split(/\s+/)[0]) > 1, "scroll advances source line numbers"); - assert.deepEqual(pane(frame, link).lines, reflectedBeforeScroll, "scrolling the source must leave its neighbor alone"); - - const sourceRow = scrolled.top + 2; - const reflectedRow = pane(frame, link).top + 2; - const point = await evaluate(`(() => { - const runtime = pardes.runtime; - const root = runtime.root; - const wasm = runtime.wasm; - const events = []; - const canceled = []; - const pointerDownCanceled = []; - const click = (row) => { - wasm.pardes_mouse(0, 0, 10, row, 0); - wasm.pardes_mouse(0, 1, 10, row, 0); - wasm.pardes_tick(); - runtime.renderer.render(); - }; - click(${sourceRow}); - click(${reflectedRow}); - runtime.wasm = { ...wasm, pardes_mouse: (...args) => { - events.push(args.slice(0, 2)); - wasm.pardes_mouse(...args); - }, pardes_mouse_pixel: (...args) => { - events.push(args.slice(0, 2)); - wasm.pardes_mouse_pixel(...args); - } }; - const observe = (event) => { - if (event.type === "pointerdown") pointerDownCanceled.push(event.defaultPrevented); - else if (event.button === 3 || event.button === 4) canceled.push(event.defaultPrevented); - }; - for (const type of ["pointerdown", "mousedown", "auxclick"]) root.addEventListener(type, observe); - pardes.thumbTest = { wasm, observe, events, canceled, pointerDownCanceled }; - return runtime.cellPoint(10, ${sourceRow}); - })()`); - const thumb = async (button, held = false) => { - const mask = button === "back" ? 8 : 16; - await mouse({ type: "mousePressed", button, buttons: mask | Number(held), ...point, clickCount: 1 }); - await mouse({ type: "mouseReleased", button, buttons: Number(held), ...point, clickCount: 1 }); - await stable(100, 5000); - return (await grid()).cursorY; - }; - try { - const backRow = await thumb("back"); - const forwardRow = await thumb("forward"); - assert(backRow > scrolled.top && backRow < scrolled.bottom, "Back returns to the source pane"); - const reflectedAfter = pane(await grid(), link); - assert(forwardRow > reflectedAfter.top && forwardRow < reflectedAfter.bottom, "Forward returns to the reflected pane"); - - await mouse({ type: "mousePressed", button: "left", buttons: 1, ...point, clickCount: 1 }); - await evaluate("pardes.thumbTest.heldPointer = pardes.runtime.pointer"); - await thumb("back", true); - await thumb("forward", true); - const navigation = await evaluate(`({ - events: pardes.thumbTest.events, - canceled: pardes.thumbTest.canceled, - pointerDownCanceled: pardes.thumbTest.pointerDownCanceled, - keptPointer: pardes.thumbTest.heldPointer !== null && pardes.runtime.pointer === pardes.thumbTest.heldPointer, - })`); - const presses = navigation.events.filter((event) => event[1] === 0 && (event[0] === 8 || event[0] === 9)); - assert.deepEqual(presses, [[8, 0], [9, 0], [8, 0], [9, 0]], "each physical thumb press navigates once"); - assert(!navigation.events.some((event) => event[0] === 1 || (event[0] === 0 && event[1] === 3)), "thumb buttons must not become selection drags or middle clicks"); - assert(navigation.canceled.length >= 4 && navigation.canceled.every(Boolean), "thumb mouse and auxclick events must cancel browser defaults"); - assert(navigation.pointerDownCanceled.every((value) => !value), "mouse pointerdown must permit subsequent mousedown events"); - assert(navigation.keptPointer, "thumb navigation must retain the held selection pointer"); - } finally { - await mouse({ type: "mouseReleased", button: "left", buttons: 0, ...point, clickCount: 1 }); - await evaluate(`(() => { - for (const type of ["pointerdown", "mousedown", "auxclick"]) - pardes.runtime.root.removeEventListener(type, pardes.thumbTest.observe); - pardes.runtime.wasm = pardes.thumbTest.wasm; - delete pardes.thumbTest; - })()`); - } -} diff --git a/test/web_driver_test.mjs b/test/web_driver_test.mjs deleted file mode 100644 index 5484d763..00000000 --- a/test/web_driver_test.mjs +++ /dev/null @@ -1,134 +0,0 @@ -import assert from "node:assert/strict"; -import { spawn } from "node:child_process"; -import { once } from "node:events"; -import net from "node:net"; -import test from "node:test"; -import { Cdp, stopChrome } from "./web_snapshot.mjs"; - -class Socket extends EventTarget { - readyState = WebSocket.OPEN; - sent = []; - closes = 0; - - send(data) { - this.sent.push(JSON.parse(data)); - } - - reply(data) { - this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(data) })); - } - - close() { - this.readyState = WebSocket.CLOSED; - this.closes += 1; - this.dispatchEvent(new Event("close")); - } -} - -test("CDP replies clear deadlines and preserve protocol errors", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, [], 20); - try { - const reply = client.send("Runtime.enable"); - socket.reply({ id: socket.sent[0].id, result: { enabled: true } }); - assert.deepEqual(await reply, { enabled: true }); - const error = assert.rejects(client.send("Runtime.bad"), /Runtime.bad: unknown method/); - socket.reply({ id: socket.sent[1].id, error: { message: "unknown method" } }); - await error; - await new Promise((resolve) => setTimeout(resolve, 40)); - assert.equal(client.pending.size, 0); - assert.equal(client.error, null); - assert.equal(socket.closes, 0); - } finally { - client.close(); - } -}); - -test("CDP timeout rejects all pending and future commands", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, [], 20); - await Promise.all([ - assert.rejects(client.send("Runtime.evaluate"), /Runtime.evaluate timed out/), - assert.rejects(client.send("Page.enable"), /Runtime.evaluate timed out/), - ]); - await assert.rejects(client.send("Log.enable"), /Runtime.evaluate timed out/); - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); - assert.equal(socket.sent.length, 2); -}); - -for (const event of ["close", "error"]) { - test(`CDP ${event} immediately rejects pending commands`, { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, [], 10_000); - const pending = Promise.all([ - assert.rejects(client.send("Runtime.evaluate"), /DevTools connection/), - assert.rejects(client.send("Page.enable"), /DevTools connection/), - ]); - socket.dispatchEvent(new Event(event)); - await pending; - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); - }); -} - -test("CDP rejects malformed replies and synchronous send failures", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, []); - const pending = assert.rejects(client.send("Runtime.evaluate"), /invalid DevTools message/); - socket.dispatchEvent(new MessageEvent("message", { data: "not json" })); - await pending; - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); - - const broken = new Socket(); - broken.send = () => { throw new Error("broken transport"); }; - const failed = new Cdp(broken, []); - await assert.rejects(failed.send("Page.enable"), /send DevTools command Page.enable/); - assert.equal(failed.pending.size, 0); - assert.equal(broken.closes, 1); -}); - -test("closing CDP cancels commands once", { timeout: 2_000 }, async () => { - const socket = new Socket(); - const client = new Cdp(socket, []); - const pending = assert.rejects(client.send("Runtime.evaluate"), /DevTools client closed/); - client.close(); - client.close(); - await pending; - assert.equal(client.pending.size, 0); - assert.equal(socket.closes, 1); -}); - -test("CDP closes a stalled connection after its deadline", { timeout: 2_000 }, async (t) => { - const sockets = new Set(); - const server = net.createServer((socket) => { - sockets.add(socket); - socket.resume(); - socket.on("close", () => sockets.delete(socket)); - }); - t.after(async () => { - const closed = new Promise((resolve) => server.close(resolve)); - for (const socket of sockets) socket.destroy(); - await closed; - }); - server.listen(0, "127.0.0.1"); - await once(server, "listening"); - await assert.rejects(Cdp.connect(`ws://127.0.0.1:${server.address().port}`, [], 40), /connection timed out/); - const deadline = Date.now() + 1_000; - while (sockets.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 5)); - assert.equal(sockets.size, 0, "timed-out connection must close its TCP socket"); -}); - -test("Chrome cleanup escalates and reaps a process ignoring SIGTERM", { timeout: 2_000 }, async (t) => { - const child = spawn(process.execPath, ["--input-type=module", "-e", ` - process.on("SIGTERM", () => {}); - setInterval(() => {}, 1000); - console.log("ready"); - `], { stdio: ["ignore", "pipe", "ignore"] }); - t.after(() => stopChrome(child, 10)); - await once(child.stdout, "data"); - await stopChrome(child, 20); - assert.equal(child.signalCode, "SIGKILL"); - await stopChrome(child, 20); -}); diff --git a/test/web_harness.mjs b/test/web_harness.mjs deleted file mode 100644 index 7fd58b86..00000000 --- a/test/web_harness.mjs +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env node -// Dependency-free JS harness: instantiate the real freestanding core in Node, -// then render its packed frame through app.mjs against a deliberately tiny DOM -// double. Chrome is reserved for the separate browser/e2e snapshot harness. - -import assert from "node:assert/strict"; -import fs from "node:fs/promises"; -import path from "node:path"; -import { pathToFileURL } from "node:url"; - -if (process.argv.length !== 3) { - console.error("usage: node test/web_harness.mjs <zig-out/web>"); - process.exit(2); -} - -async function main() { - const webDir = path.resolve(process.argv[2]); - const wasmBytes = await fs.readFile(path.join(webDir, "pardes.wasm")); - const module = await WebAssembly.compile(wasmBytes); - const { DomRenderer, browserHost } = await import(pathToFileURL(path.join(webDir, "app.mjs"))); - assert.deepEqual( - [...new Set(WebAssembly.Module.imports(module).map((entry) => entry.module))], - ["pardes"], - "the freestanding core must import nothing but the page's own host", - ); - - // The page's real import object, with every call recorded: the browser host - // is only what a page can actually do, and a replay must ask it for nothing. - const host = browserHost(); - const asked = []; - for (const [name, fn] of Object.entries(host.imports.pardes)) { - host.imports.pardes[name] = (...args) => { - asked.push(name); - return fn(...args); - }; - } - const { exports: wasm } = await WebAssembly.instantiate(module, host.imports); - host.wasm = wasm; - - for (const name of [ - "memory", "pardes_init", "pardes_frame", "pardes_frame_ptr", "pardes_key", - "pardes_mouse", "pardes_pointer_leave", "pardes_pointer_shape", "pardes_gui_tagline_font_percent", - "pardes_paste", "pardes_tick", - "pardes_should_quit", "pardes_deinit", - ]) assert.ok(wasm[name], `missing wasm export ${name}`); - - assert.equal(wasm.pardes_init(80, 24), 0, `wasm init error ${wasm.pardes_last_error()}`); - assert.equal(wasm.pardes_frame(), 0, "a frame exists only once the core has presented one"); - wasm.pardes_tick(); - assert.equal(wasm.pardes_frame(), 80 * 24); - assert.ok(wasm.pardes_frame_ptr() > 0); - - const document = new FakeDocument(); - const root = document.createElement("main"); - root.ownerDocument = document; - const renderer = new DomRenderer(root, wasm); - const draw = () => { - wasm.pardes_tick(); - return renderer.render(); - }; - const first = renderer.render(); - assert.equal(root.style.cursor, "text"); - renderer.wasm = { ...wasm, pardes_pointer_shape: () => 1 }; - renderer.render(); - assert.equal(root.style.cursor, "pointer", "link hover should display the hand pointer"); - renderer.wasm = wasm; - renderer.render(); - assert.equal(root.style.cursor, "text", "leaving a link should restore the text pointer"); - - assert.equal(first.cols, 80); - assert.equal(first.rows, 24); - assert.equal(root.children.length, 24); - assert.equal(root.children[0].children.length, 80); - assert.ok(first.cells.some((cell) => cell.text !== " "), "dump rendered an empty frame"); - assert.ok(root.walk().every((node) => node.tagName !== "CANVAS"), "renderer created a canvas"); - const taglineIndex = first.cells.findIndex((cell) => cell.attrs & (1 << 7)); - const bodyIndex = first.cells.findIndex((cell) => !(cell.attrs & (1 << 7)) && cell.text !== " "); - assert.ok(taglineIndex >= 0, "frame ABI did not mark a tagline font role"); - assert.ok(bodyIndex >= 0, "fixture has no body glyph to compare with tagline"); - assert.ok(renderer.cells[taglineIndex].classList.names.has("is-tagline"), "DOM tagline class was not applied"); - assert.ok(!renderer.cells[bodyIndex].classList.names.has("is-tagline"), "DOM inferred tagline role for body text"); - assert.equal( - root.style["--pardes-tagline-font-size"], - `${wasm.pardes_gui_tagline_font_percent()}%`, - "DOM did not use the build-time tagline percentage", - ); - - const firstCell = renderer.cells[0]; - const second = draw(); - assert.equal(renderer.cells[0], firstCell, "stable frames should reuse DOM nodes"); - assert.equal(second.cells.length, 80 * 24); - - // The embedded dump is test/web-snapshots/touch.dump.zon, a fixed source - // fixture (no live project paths). Over-scroll first (the core clamps at row - // zero) so the Look below always lands on the fixture's own first rows. - for (let tick = 0; tick < 128; tick += 1) wasm.pardes_mouse(3, 0, 5, 3, 0); - const listingTop = draw(); - const topLines = Array.from({ length: listingTop.rows }, (_, row) => - listingTop.cells.slice(row * listingTop.cols, (row + 1) * listingTop.cols).map((cell) => cell.text).join("")); - assert.ok( - topLines.some((text) => /^\s*1 pub fn choose/.test(text)), - "fixture source did not scroll to its first row", - ); - const link = "/virtual/pane/1/body"; - const linkRow = topLines.findIndex((text) => text.includes(link)); - assert.ok(linkRow >= 0, "fixture has no Look target"); - const linkCol = topLines[linkRow].indexOf(link) + 5; - wasm.pardes_mouse(2, 0, linkCol, linkRow, 0); - wasm.pardes_mouse(2, 1, linkCol, linkRow, 0); - const looked = draw(); - const lookedText = looked.cells.map((cell) => cell.text).join(""); - assert.ok( - lookedText.includes(`${link} `) && lookedText.split("pub fn choose").length - 1 >= 2, - "right-click LOOK did not open the reflected source body", - ); - const sourceRows = Array.from({ length: looked.rows }, (_, row) => - looked.cells.slice(row * looked.cols, (row + 1) * looked.cols)); - const codeRows = sourceRows.filter((row) => row.map((cell) => cell.text).join("").match(/^\s*\d+\s/)); - const codeColors = new Set(codeRows.flatMap((row) => row.slice(5).map((cell) => `${cell.fg}:${cell.attrs & 1}`))); - assert.ok(codeColors.size >= 3, "Tree-sitter did not apply distinct syntax styles to the fixture"); - assert.deepEqual(asked, [], "a plain replay asked the page for host IO"); - - wasm.pardes_resize(41, 13); - const resized = draw(); - assert.equal(resized.cols, 41); - assert.equal(resized.rows, 13); - assert.equal(root.children.length, 13); - assert.equal(root.children[0].children.length, 41); - - wasm.pardes_deinit(); - console.error("web harness ok: freestanding wasm + Tree-sitter + packed DOM renderer"); -} - -class FakeDocument { - constructor() { - this.body = new FakeElement("body", this); - } - - createElement(tagName) { - return new FakeElement(tagName, this); - } -} - -class FakeElement { - constructor(tagName, ownerDocument) { - this.tagName = tagName.toUpperCase(); - this.ownerDocument = ownerDocument; - this.children = []; - this.attributes = new Map(); - this.dataset = {}; - this.style = new FakeStyle(); - this.classList = new FakeClassList(this); - this.className = ""; - this.textContent = ""; - } - - setAttribute(name, value) { - this.attributes.set(name, String(value)); - } - - replaceChildren(...children) { - this.children = children; - } - - *walk() { - yield this; - for (const child of this.children) yield* child.walk(); - } -} - -class FakeStyle { - setProperty(name, value) { - this[name] = value; - } -} - -class FakeClassList { - constructor(element) { - this.element = element; - this.names = new Set(); - } - - toggle(name, force) { - if (force) this.names.add(name); - else this.names.delete(name); - this.element.className = [...this.names].join(" "); - } -} - -await main(); diff --git a/test/web_snapshot.mjs b/test/web_snapshot.mjs deleted file mode 100644 index 61467c4d..00000000 --- a/test/web_snapshot.mjs +++ /dev/null @@ -1,550 +0,0 @@ -#!/usr/bin/env node -// Native touch events through Chromium's DevTools protocol, without npm. -// PARDES_CHROME overrides the Chromium executable. -import childProcess from "node:child_process"; -import fs from "node:fs"; -import fsp from "node:fs/promises"; -import http from "node:http"; -import net from "node:net"; -import os from "node:os"; -import path from "node:path"; -import { fileURLToPath, pathToFileURL } from "node:url"; - -const VIEWPORT = { width: 1120, height: 720 }; -let scriptPath; -let server; -let chrome; -let client; -let userDataDir; -let chromeStderr = ""; -const browserLog = []; - -async function main() { - const args = process.argv.slice(2); - const update = args.includes("--update"); - const positional = args.filter((arg) => arg !== "--update"); - if (positional.length !== 2) { - console.error("usage: node test/web_snapshot.mjs <zig-out/web> <test.mjs|script.snap> [--update]"); - process.exitCode = 2; - return; - } - const webDir = path.resolve(positional[0]); - scriptPath = path.resolve(positional[1]); - const scenarioModule = scriptPath.endsWith(".mjs"); - const goldenPath = scriptPath.replace(/\.snap$/, ".golden"); - try { - if (!scenarioModule && goldenPath === scriptPath) throw new Error(`not a test module or .snap path: ${scriptPath}`); - if (scenarioModule && update) throw new Error("semantic browser tests have no golden to update"); - const served = await serveDirectory(webDir); - server = served.server; - const debugPort = await unusedPort(); - const chromePath = await findChrome(); - userDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), "pardes-web-snap-")); - chrome = childProcess.spawn(chromePath, [ - "--headless=new", - "--no-sandbox", - "--disable-dev-shm-usage", - "--enable-unsafe-swiftshader", - "--use-angle=swiftshader", - "--no-first-run", - "--no-default-browser-check", - `--remote-debugging-address=127.0.0.1`, - `--remote-debugging-port=${debugPort}`, - `--user-data-dir=${userDataDir}`, - "about:blank", - ], { stdio: ["ignore", "ignore", "pipe"] }); - chrome.on("error", (error) => { chromeStderr += `\n${error.message}`; }); - chrome.stderr.setEncoding("utf8"); - chrome.stderr.on("data", (chunk) => { - chromeStderr = (chromeStderr + chunk).slice(-16_384); - }); - - await waitForDevTools(debugPort, chrome); - const targetResponse = await fetch( - `http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(`http://127.0.0.1:${served.port}/index.html`)}`, - { method: "PUT", signal: AbortSignal.timeout(10_000) }, - ); - if (!targetResponse.ok) throw new Error(`create Chrome target: HTTP ${targetResponse.status}`); - const target = await targetResponse.json(); - client = await Cdp.connect(target.webSocketDebuggerUrl, browserLog); - await client.send("Runtime.enable"); - await client.send("Page.enable"); - await client.send("Log.enable"); - await client.send("Emulation.setDeviceMetricsOverride", { - ...VIEWPORT, - screenWidth: VIEWPORT.width, - screenHeight: VIEWPORT.height, - deviceScaleFactor: 1, - mobile: false, - }); - await client.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }); - await waitForRuntime(20_000); - - if (scenarioModule) { - const scenario = await import(pathToFileURL(scriptPath)); - await scenario.default({ grid, touch: dispatchTouch, wait: waitUntil, stable: waitStable, delay, evaluate, - mouse: (event) => client.send("Input.dispatchMouseEvent", event) }); - console.error(`web test ok: ${path.relative(process.cwd(), scriptPath)}`); - return; - } - const output = await runScript(await fsp.readFile(scriptPath, "utf8")); - if (update) { - await fsp.writeFile(goldenPath, output); - console.error(`updated ${path.relative(process.cwd(), goldenPath)}`); - } else { - const golden = await fsp.readFile(goldenPath, "utf8").catch(() => null); - if (golden === null) throw new Error(`missing ${goldenPath}; run with --update`); - if (golden !== output) { - const actualPath = goldenPath.replace(/\.golden$/, ".actual"); - await fsp.writeFile(actualPath, output); - throw new Error(`snapshot mismatch; actual written to ${actualPath}`); - } - console.error(`web snapshot ok: ${path.relative(process.cwd(), scriptPath)}`); - } - } catch (error) { - console.error(error?.stack ?? error); - if (scenarioModule && client) { - const frame = await grid().catch(() => null); - if (frame) console.error(formatSnapshot("failure", frame)); - } - if (browserLog.length) console.error(`browser log:\n${browserLog.join("\n")}`); - if (chromeStderr.trim()) console.error(`chromium stderr (tail):\n${chromeStderr.trim()}`); - process.exitCode = 1; - } finally { - client?.close(); - if (chrome) await stopChrome(chrome); - if (server) { - const closed = new Promise((resolve) => server.close(resolve)); - server.closeAllConnections(); - await closed; - } - if (userDataDir) await fsp.rm(userDataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - } -} - -async function runScript(source) { - let output = ""; - let activeTouch = null; - const lines = source.split("\n"); - for (let index = 0; index < lines.length; index += 1) { - const line = lines[index].trim(); - if (!line || line.startsWith("#")) continue; - const tokens = line.split(/\s+/); - const command = tokens.shift(); - try { - if (command === "wait") { - const timeout = integer(tokens.shift(), "wait timeout"); - const needle = tokens.join(" "); - if (!needle) throw new Error("wait needs text"); - await waitUntil(async () => (await grid()).text.includes(needle), timeout, `screen containing ${JSON.stringify(needle)}`); - } else if (command === "stable") { - const quiet = integer(tokens.shift(), "stable quiet time"); - const timeout = integer(tokens.shift(), "stable timeout"); - await waitStable(quiet, timeout); - } else if (command === "snap") { - const label = tokens.join(" "); - if (!label) throw new Error("snap needs a label"); - output += formatSnapshot(label, await grid()); - } else if (command === "snapstyle") { - const label = tokens.join(" "); - if (!label) throw new Error("snapstyle needs a label"); - output += formatStyleSnapshot(label, await grid()); - } else if (command === "touch") { - const phase = tokens.shift(); - const id = integer(tokens.shift(), "touch id"); - const col = number(tokens.shift(), "touch col"); - const row = number(tokens.shift(), "touch row"); - if (tokens.length || !["down", "move", "up"].includes(phase)) throw new Error("bad touch command"); - activeTouch = await dispatchTouch(phase, id, col, row, activeTouch); - await delay(40); - } else if (command === "swipe") { - const id = integer(tokens.shift(), "swipe id"); - const x0 = number(tokens.shift(), "swipe start col"); - const y0 = number(tokens.shift(), "swipe start row"); - const x1 = number(tokens.shift(), "swipe end col"); - const y1 = number(tokens.shift(), "swipe end row"); - const steps = integer(tokens.shift(), "swipe steps"); - if (tokens.length || steps < 1) throw new Error("bad swipe command"); - activeTouch = await dispatchTouch("down", id, x0, y0, activeTouch); - for (let step = 1; step <= steps; step += 1) { - const t = step / steps; - activeTouch = await dispatchTouch("move", id, x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, activeTouch); - await delay(20); - } - activeTouch = await dispatchTouch("up", id, x1, y1, activeTouch); - await delay(80); - } else { - throw new Error(`unknown command ${command}`); - } - } catch (error) { - const screen = await grid().catch(() => null); - const detail = screen ? `\ncurrent screen:\n${screen.lines.map((row) => `|${row}`).join("\n")}` : ""; - throw new Error(`${path.basename(scriptPath)}:${index + 1}: ${line}\n${error.message}${detail}`, { cause: error }); - } - } - if (activeTouch) throw new Error("script ended with a finger still down"); - return output; -} - -async function dispatchTouch(phase, id, col, row, active) { - const point = await evaluate(`pardes.test.cellPoint(${JSON.stringify(col)}, ${JSON.stringify(row)})`); - const touch = { x: point.x, y: point.y, id, radiusX: 1, radiusY: 1, force: 1 }; - if (phase === "down") { - if (active) throw new Error("only one finger is supported by this web test"); - await client.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [touch] }); - return touch; - } - if (!active || active.id !== id) throw new Error(`finger ${id} is not down`); - if (phase === "move") { - await client.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [touch] }); - return touch; - } - // Chrome's touchEnd carries no points; a final move gives SDL the scripted - // release coordinate before the lift. - await client.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [touch] }); - await client.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); - return null; -} - -async function grid() { - return evaluate(`(() => { - const frame = pardes.test.grid(); - const { cols, rows, cursorX, cursorY } = frame; - const lines = []; - const styleRows = []; - for (let y = 0; y < rows; y++) { - let line = ""; - const styles = []; - for (let x = 0; x < cols; x++) { - const cell = frame.cells[y * cols + x]; - line += cell.text || " "; - styles.push([cell.fg, cell.bg, cell.attrs]); - } - lines.push(line.replace(/ +$/, "")); - styleRows.push(styles); - } - return { - cols, rows, lines, styleRows, - cursorX, cursorY, - text: lines.join("\\n"), - }; - })()`); -} - -function formatSnapshot(label, state) { - const cursorX = state.cursorX < 0 ? 0 : state.cursorX; - const cursorY = state.cursorY < 0 ? 0 : state.cursorY; - let out = `== snap ${label} grid=${state.cols}x${state.rows} cursor=${cursorX},${cursorY}\n`; - for (const line of state.lines) out += `|${line}\n`; - return out; -} - -function formatStyleSnapshot(label, state) { - let out = `== style ${label}\n`; - for (let y = 0; y < state.rows; y++) { - const styles = state.styleRows[y]; - out += `|${y}:`; - let runStart = 0; - let runKey = styleKey(styles[0]); - for (let x = 1; x <= state.cols; x++) { - const key = x === state.cols ? null : styleKey(styles[x]); - if (key === runKey) continue; - out += ` ${runStart}-${x - 1} ${runKey}`; - runStart = x; - runKey = key; - } - out += "\n"; - } - return out; -} - -function styleKey([fg, bg, attrs]) { - return `${colorKey(fg)},${colorKey(bg)},${attrsKey(attrs)}`; -} - -function colorKey(color) { - if (color === 0x01000000) return "d"; - if ((color & 0xff000000) === 0x02000000) return `p${color & 0xff}`; - return `#${(color & 0xffffff).toString(16).padStart(6, "0")}`; -} - -function attrsKey(attrs) { - let out = ""; - if (attrs & (1 << 0)) out += "b"; - if (attrs & (1 << 1)) out += "f"; - if (attrs & (1 << 2)) out += "i"; - if (attrs & (1 << 3)) out += "k"; - if (attrs & (1 << 4)) out += "r"; - if (attrs & (1 << 5)) out += "v"; - if (attrs & (1 << 6)) out += "x"; - out += ["", "u", "U", "~", ".", "-"][(attrs >> 8) & 0x7] ?? "?"; - return out; -} - -async function waitStable(quiet, timeout) { - const deadline = Date.now() + timeout; - let previous = JSON.stringify(await grid()); - while (Date.now() < deadline) { - await delay(Math.min(quiet, deadline - Date.now())); - const current = JSON.stringify(await grid()); - if (current === previous && Date.now() <= deadline) return; - previous = current; - } - throw new Error(`screen did not stabilize within ${timeout}ms`); -} - -async function waitForRuntime(timeout) { - await waitUntil(async () => { - try { - return await evaluate(`(() => { - const app = globalThis.pardes; - if (!app?.test?.grid()?.cols || document.querySelector("canvas")) return false; - const want = app.runtime.gridSize(); - const frame = app.test.grid(); - const tagline = document.querySelector(".pardes-cell.is-tagline"); - const body = document.querySelector(".pardes-cell:not(.is-tagline)"); - if (!tagline || !body) return false; - const tagRect = tagline.getBoundingClientRect(); - const bodyRect = body.getBoundingClientRect(); - return frame.cols === want.cols && frame.rows === want.rows && - document.querySelectorAll(".pardes-row").length === want.rows && - tagRect.width === bodyRect.width && tagRect.height === bodyRect.height && - parseFloat(getComputedStyle(tagline).fontSize) < parseFloat(getComputedStyle(body).fontSize); - })()`); - } catch (error) { - if (client.error) throw error; - return false; - } - }, timeout, "Pardes web runtime"); -} - -async function waitUntil(predicate, timeout, description) { - const deadline = Date.now() + timeout; - while (Date.now() < deadline) { - if (await predicate()) return; - if (chrome && (chrome.exitCode !== null || chrome.signalCode !== null)) - throw new Error(`Chromium exited with ${chrome.exitCode ?? chrome.signalCode}`); - await delay(50); - } - throw new Error(`timed out waiting for ${description}`); -} - -async function evaluate(expression) { - const response = await client.send("Runtime.evaluate", { - expression, - returnByValue: true, - awaitPromise: true, - }); - if (response.exceptionDetails) throw new Error(response.exceptionDetails.text); - return response.result.value; -} - -export class Cdp { - static async connect(url, log, timeout = 10_000) { - const socket = new WebSocket(url); - const client = new Cdp(socket, log, timeout); - try { - await new Promise((resolve, reject) => { - const finish = (error) => { - clearTimeout(timer); - socket.removeEventListener("open", opened); - socket.removeEventListener("close", failed); - socket.removeEventListener("error", failed); - if (error) reject(error); else resolve(); - }; - const opened = () => finish(); - const failed = () => finish(client.error ?? new Error(`connect DevTools websocket ${url}`)); - const timer = setTimeout(() => finish(new Error(`DevTools connection timed out after ${timeout}ms`)), timeout); - socket.addEventListener("open", opened, { once: true }); - socket.addEventListener("close", failed, { once: true }); - socket.addEventListener("error", failed, { once: true }); - }); - return client; - } catch (error) { - client.close(); - throw error; - } - } - - constructor(socket, log, timeout = 10_000) { - this.socket = socket; - this.timeout = timeout; - this.nextId = 1; - this.pending = new Map(); - this.error = null; - socket.addEventListener("close", (event) => this.fail(new Error(`DevTools connection closed (${event.code ?? "unknown"})`))); - socket.addEventListener("error", () => this.fail(new Error("DevTools connection error"))); - socket.addEventListener("message", (event) => { - if (this.error) return; - try { - const message = JSON.parse(event.data); - if (message.id) { - const pending = this.pending.get(message.id); - if (!pending) return; - this.pending.delete(message.id); - clearTimeout(pending.timer); - if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.message}`)); - else pending.resolve(message.result ?? {}); - return; - } - if (message.method === "Runtime.exceptionThrown") - log.push(`exception: ${message.params.exceptionDetails.text}`); - else if (message.method === "Runtime.consoleAPICalled") - log.push(`console ${message.params.type}: ${message.params.args.map((arg) => arg.value ?? arg.description).join(" ")}`); - else if (message.method === "Log.entryAdded") - log.push(`${message.params.entry.level}: ${message.params.entry.text}`); - } catch (error) { - this.fail(new Error("invalid DevTools message", { cause: error })); - } - }); - } - - send(method, params = {}) { - if (this.error) return Promise.reject(this.error); - if (this.socket.readyState !== WebSocket.OPEN) { - this.fail(new Error("DevTools connection is not open")); - return Promise.reject(this.error); - } - const id = this.nextId++; - return new Promise((resolve, reject) => { - const timer = setTimeout(() => this.fail(new Error(`${method} timed out after ${this.timeout}ms`)), this.timeout); - this.pending.set(id, { resolve, reject, method, timer }); - try { - this.socket.send(JSON.stringify({ id, method, params })); - } catch (error) { - this.fail(new Error(`send DevTools command ${method}`, { cause: error })); - } - }); - } - - fail(error) { - if (this.error) return; - this.error = error; - for (const pending of this.pending.values()) { - clearTimeout(pending.timer); - pending.reject(error); - } - this.pending.clear(); - this.socket.close(); - } - - close() { - this.fail(new Error("DevTools client closed")); - } -} - -export async function stopChrome(child, timeout = 2_000) { - if (!child.pid || child.exitCode !== null || child.signalCode !== null) return; - await new Promise((resolve) => { - const timer = setTimeout(() => child.kill("SIGKILL"), timeout); - child.once("exit", () => { - clearTimeout(timer); - resolve(); - }); - child.kill("SIGTERM"); - }); -} - -async function serveDirectory(root) { - const canonicalRoot = await fsp.realpath(root); - const server = http.createServer(async (request, response) => { - try { - const url = new URL(request.url, "http://localhost"); - const relative = decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname); - const filename = path.resolve(canonicalRoot, `.${relative}`); - if (filename !== canonicalRoot && !filename.startsWith(`${canonicalRoot}${path.sep}`)) { - response.writeHead(403).end(); - return; - } - const contents = await fsp.readFile(filename); - const contentType = filename.endsWith(".wasm") ? "application/wasm" - : filename.endsWith(".js") || filename.endsWith(".mjs") ? "text/javascript; charset=utf-8" - : filename.endsWith(".css") ? "text/css; charset=utf-8" - : filename.endsWith(".ttf") ? "font/ttf" - : "text/html; charset=utf-8"; - response.writeHead(200, { "content-type": contentType, "cache-control": "no-store" }); - response.end(contents); - } catch { - response.writeHead(404).end(); - } - }); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - return { server, port: server.address().port }; -} - -async function unusedPort() { - const probe = net.createServer(); - await new Promise((resolve, reject) => { - probe.once("error", reject); - probe.listen(0, "127.0.0.1", resolve); - }); - const port = probe.address().port; - await new Promise((resolve) => probe.close(resolve)); - return port; -} - -async function waitForDevTools(port, child) { - const deadline = Date.now() + 10_000; - while (Date.now() < deadline) { - if (!child.pid || child.exitCode !== null || child.signalCode !== null) - throw new Error(`Chromium exited with ${child.exitCode ?? child.signalCode}`); - try { - const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(500) }); - if (response.ok) return; - } catch {} - await delay(50); - } - throw new Error("Chromium DevTools endpoint did not start"); -} - -async function findChrome() { - const candidates = []; - if (process.env.PARDES_CHROME) candidates.push(process.env.PARDES_CHROME); - for (const command of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable"]) { - const found = childProcess.spawnSync("which", [command], { encoding: "utf8" }); - if (found.status === 0 && found.stdout.trim()) candidates.push(found.stdout.trim()); - } - // macOS installs a browser as an application BUNDLE, whose executable is - // buried inside it and never on PATH, so the lookup above finds nothing on - // a Mac that has Chrome sitting in /Applications. - if (process.platform === "darwin") - for (const app of ["Google Chrome", "Chromium", "Google Chrome Canary"]) - candidates.push(`/Applications/${app}.app/Contents/MacOS/${app}`); - const cache = process.env.PLAYWRIGHT_BROWSERS_PATH || path.join(os.homedir(), ".cache", "ms-playwright"); - for (const entry of await fsp.readdir(cache).catch(() => [])) { - if (entry.startsWith("chromium-")) { - candidates.push(path.join(cache, entry, "chrome-linux64", "chrome")); - candidates.push(path.join(cache, entry, "chrome-linux", "chrome")); - } else if (entry.startsWith("chromium_headless_shell-")) { - candidates.push(path.join(cache, entry, "chrome-headless-shell-linux64", "chrome-headless-shell")); - } - } - for (const candidate of candidates) { - try { - await fsp.access(candidate, fs.constants.X_OK); - return candidate; - } catch {} - } - throw new Error("no Chromium found; set PARDES_CHROME=/path/to/chrome"); -} - -function integer(value, label) { - const parsed = Number.parseInt(value, 10); - if (!Number.isSafeInteger(parsed) || String(parsed) !== value) throw new Error(`bad ${label}: ${value}`); - return parsed; -} - -function number(value, label) { - const parsed = Number(value); - if (!Number.isFinite(parsed)) throw new Error(`bad ${label}: ${value}`); - return parsed; -} - -function delay(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(); diff --git a/tools/web_fixture.py b/tools/web_fixture.py deleted file mode 100644 index 06fc54cd..00000000 --- a/tools/web_fixture.py +++ /dev/null @@ -1,34 +0,0 @@ -"""web_fixture.py PARDES OUT: the web shell's touch fixture as a dump of this -build: one pane on touch-fixture.zig at 100x30, theme helix. - - python3 -B tools/web_fixture.py <pardes> test/web-snapshots/touch.dump -""" -import os, sys, time, shutil, struct, fcntl, termios -from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'test')) -import fs # noqa: E402 - -binary, out = sys.argv[1], sys.argv[2] -root = Path('/tmp/pardes-web-fixture') # fixed: the dump names it -shutil.rmtree(root, ignore_errors=True) -root.mkdir(parents=True, mode=0o700) -shutil.copy(Path(__file__).resolve().parent.parent / 'test' / 'web-snapshots' / 'touch-fixture.zig', root / 'touch-fixture.zig') -# Set at startup, which announces nothing: a fixture with no message on -# its pane. -(root / 'config' / 'pardes').mkdir(parents=True) -(root / 'config' / 'pardes' / 'init').write_text('Theme helix\nVerbose off\n') -handles = {} -with fs.session(binary, root, 'web', tty=True, file=root / 'touch-fixture.zig', inherited={'PARDES_DAEMON': 'off'}, terminal=handles) as (client, address): - fcntl.ioctl(handles['input_fd'], termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0)) - deadline = time.monotonic() + 10 - while client.screen()['cols'] != 100: - assert time.monotonic() < deadline - time.sleep(.01) - client.write('/ctl', b'Dump\n') - while b'\ndump ' not in client.read('/log'): - assert time.monotonic() < deadline - time.sleep(.01) - print(client.read('/index').decode()) - shutil.copy(root / 'web.dump.zon', out) -shutil.rmtree(root, ignore_errors=True) -print(os.path.getsize(out), 'bytes') |
