diff options
| -rw-r--r-- | build.zig | 2340 | ||||
| -rw-r--r-- | build.zig.zon | 7 | ||||
| -rw-r--r-- | build/addons.zig | 114 | ||||
| -rw-r--r-- | build/core.zig | 620 | ||||
| -rw-r--r-- | build/docs.zig | 79 | ||||
| -rw-r--r-- | build/gui.zig | 205 | ||||
| -rw-r--r-- | build/library.zig | 49 | ||||
| -rw-r--r-- | build/macos.zig | 200 | ||||
| -rw-r--r-- | build/mupdf.zig (renamed from mupdf.zig) | 4 | ||||
| -rw-r--r-- | build/patches.zig | 338 | ||||
| -rw-r--r-- | build/patches/ghostty_kitty.zig | 15 | ||||
| -rw-r--r-- | build/patches/mvzr_budget.zig | 4 | ||||
| -rw-r--r-- | build/patches/vaxis_parser.zig | 13 | ||||
| -rw-r--r-- | build/patches/vaxis_render.zig | 25 | ||||
| -rw-r--r-- | build/process.zig | 14 | ||||
| -rw-r--r-- | build/tests.zig | 264 | ||||
| -rw-r--r-- | build/tools.zig | 303 | ||||
| -rw-r--r-- | docs/shared-libs.md | 4 | ||||
| -rw-r--r-- | docs/typ/building.typ | 14 | ||||
| -rw-r--r-- | tools/patch.zig | 39 |
20 files changed, 2439 insertions, 2212 deletions
@@ -1,33 +1,18 @@ const std = @import("std"); const builtin = @import("builtin"); -const mupdf_build = @import("mupdf.zig"); +const core = @import("build/core.zig"); +const docs = @import("build/docs.zig"); +const gui = @import("build/gui.zig"); +const macos = @import("build/macos.zig"); +const tools = @import("build/tools.zig"); +const tests = @import("build/tests.zig"); const process_build = @import("build/process.zig"); -const grammar_manifest = @import("src/grammar_manifest.zig"); -/// The package manifest, imported UNTYPED on purpose — see the `version` -/// option in `shellOptions` for why that word is load-bearing. +/// The package manifest, imported untyped (build/core.zig has the reason). const zon = @import("build.zig.zon"); -/// Releases are numbered 0.N; the zon holds "0.N.0" because it must be semver, -/// and what a user sees drops that ".0". -const display_version = if (std.mem.endsWith(u8, zon.version, ".0") and std.mem.count(u8, zon.version, ".") == 2) - zon.version[0 .. zon.version.len - 2] -else - zon.version; - -/// Every dependency the manifest pins, by its content hash: a grammar, -/// ghostty or the Unicode tables steps a core differently, so they are part -/// of a replica's semantics hash (src/wire.zig `semantics`). -const deps_text = blk: { - var text: []const u8 = ""; - for (@typeInfo(@TypeOf(zon.dependencies)).@"struct".field_names) |name| { - const dep = @field(zon.dependencies, name); - text = text ++ name ++ " " ++ (if (@hasField(@TypeOf(dep), "hash")) dep.hash else "path") ++ "\n"; - } - break :blk text; -}; pub const Platform = enum { tui, gui, macos }; -const PerfBuild = struct { +pub const PerfBuild = struct { compiler: []const u8, target: []const u8, cpu: []const u8, @@ -48,32 +33,30 @@ pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, . pub const TreeSitterGrammars = enum { disabled, zig, minimal, full }; -const gui_shaders = [_][]const u8{ - "ui.vert", - "ui.frag", - "decor.frag", - "overlay.vert", - "overlay.frag", - "image.vert", - "image.frag", -}; - pub fn build(b: *std.Build) void { // A package that depends on pardes takes its library; nothing of the // editor is configured for it. - if (!b.isRoot()) return library(b); + if (!b.isRoot()) return @import("build/library.zig").build(b); + // This configure reads the environment (HOME, XDG_DATA_HOME, + // HX_HARNESS), the clock (-Dtest-rebuild) and vendor/themes and + // vendor/queries without telling the configure cache, so it is never + // cached (REORG decision 20; typst's lookup did this before it moved to + // make time). + b.graph.poisonCache(); 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 - // 0.17 keeps the prefix in the maker process, out of this script's - // reach, so `--prefix` no longer turns it off: -Dhome-install=false does. - const home_enabled = b.option(bool, "home-install", "install binaries and addons into the user directories (default: true)") orelse true; - const home_bin: ?[]const u8 = if (also_gui and home_enabled) + // A bare `zig build` also copies the binaries into ~/.local/bin, and the + // addon steps theirs into the user's data directory. Zig 0.17 keeps the + // prefix in the maker process, out of this script's reach, so `--prefix` + // no longer turns it off: -Dhome-install=false does. With -Dplatform + // neither is copied, but the addons with -Dhome-install=true. + const home_option = b.option(bool, "home-install", "copy into the user directories: a bare `zig build` the binaries and addons, -Dplatform the addons only when true (default: true for a bare `zig build`)"); + const home_bin: ?[]const u8 = if (also_gui and (home_option orelse true)) if (b.graph.environ_map.get("HOME")) |home| b.pathJoin(&.{ home, ".local", "bin" }) else null else null; - const home_addons: ?[]const u8 = if (!home_enabled) null else if (b.graph.environ_map.get("XDG_DATA_HOME")) |data| + const home_addons: ?[]const u8 = if (!(home_option orelse also_gui)) null else if (b.graph.environ_map.get("XDG_DATA_HOME")) |data| b.pathJoin(&.{ data, "pardes", "addons" }) else if (b.graph.environ_map.get("HOME")) |home| b.pathJoin(&.{ home, ".local", "share", "pardes", "addons" }) @@ -109,40 +92,7 @@ pub fn build(b: *std.Build) void { doc_typ_opts.addOptionPathUntracked("dir", b.path("docs/typ")); // The words the shipped addons bring (PdfFit...), which the docs name too. doc_typ_opts.addOptionPathUntracked("addons", b.path("addons")); - // The docs (docs/typ, docs/site): each output is one typst run, and each - // reads docs/typ/builtins-*.json; `builtins-json` refreshes this build's from the - // registry first (the tool is wired below, once the core module is). - const typst_bin: ?[]const u8 = b.findProgram(.{ .names = &.{"typst"} }); - var doc_renders: [3]?*std.Build.Step.Run = @splat(null); - const cheatsheet_step = b.step("cheatsheet", "render docs/typ/cheatsheet-a4.typ to <prefix>/share/doc/pardes/cheatsheet.pdf (needs typst)"); - const book_step = b.step("book", "render docs/typ/book.typ to <prefix>/share/doc/pardes/pardes.pdf (needs typst)"); - // The website: one Typst bundle run writes every page, the stylesheet, - // the fonts and the media (docs/site/site.typ). - const site_step = b.step("site", "render the docs website to <prefix>/share/doc/pardes/site (needs typst)"); - if (typst_bin) |typst| { - // They read all of docs/typ, docs/site and the tutor, so they always - // run rather than track every file. - const sheet = b.addSystemCommand(&.{ typst, "compile", "--ignore-system-fonts" }); - sheet.addFileArg(b.path("docs/typ/cheatsheet-a4.typ")); - sheet.has_side_effects = true; - cheatsheet_step.dependOn(&b.addInstallFile(sheet.addOutputFileArg("cheatsheet.pdf"), "share/doc/pardes/cheatsheet.pdf").step); - const book = b.addSystemCommand(&.{ typst, "compile", "--ignore-system-fonts", "--root", "." }); - book.setCwd(b.path(".")); - book.addFileArg(b.path("docs/typ/book.typ")); - book.has_side_effects = true; - book_step.dependOn(&b.addInstallFile(book.addOutputFileArg("pardes.pdf"), "share/doc/pardes/pardes.pdf").step); - const site = b.addSystemCommand(&.{ typst, "compile", "--format", "bundle", "--features", "bundle,html", "--root", "." }); - site.setCwd(b.path(".")); - site.addFileArg(b.path("docs/site/site.typ")); - const site_dir = site.addOutputDirectoryArg("site"); - site.has_side_effects = true; - site_step.dependOn(&b.addInstallDirectory(.{ .source_dir = site_dir, .install_dir = .prefix, .install_subdir = "share/doc/pardes/site" }).step); - doc_renders = .{ sheet, book, site }; - } else { - cheatsheet_step.dependOn(&b.addFail("zig build cheatsheet needs typst on PATH").step); - book_step.dependOn(&b.addFail("zig build book needs typst on PATH").step); - site_step.dependOn(&b.addFail("zig build site needs typst on PATH").step); - } + const doc_renders = docs.add(b); const test_nonce: ?*std.Build.Module = if (b.option(bool, "test-rebuild", "force fresh Zig test compilation while retaining cached C dependencies") orelse false) blk: { const files = b.addTempFiles(); const source = files.add("test_nonce.zig", b.fmt("pub const nonce = {d};\n", .{std.Io.Clock.awake.now(b.graph.io).nanoseconds})); @@ -162,125 +112,6 @@ pub fn build(b: *std.Build) void { const macos_sdk = b.option([]const u8, "macos-sdk", "the macOS SDK a gui built for macOS from another system takes SDL's headers and frameworks from"); 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 sketchbook's committed dev/draw/shaders/prebuilt/*.spv instead of running glslc over its GLSL (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui; - - const mupdf_check = b.step("mupdf-check", "the pdf addon's check: MuPDF compiles, links, renders and searches docs/design.pdf, and its script runs"); - const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])"); - const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])"); - - // 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, .{}); - defer threaded.deinit(); - const io = threaded.io(); - - const root_mod = b.createModule(.{ - .target = target, - .optimize = optimize, - // 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) { - .macos => "src/macos.zig", - .tui, .gui => "src/main.zig", - }), - .link_libc = true, - }); - const core_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/pardes.zig"), - .link_libc = true, - }); - // The core without the terminal module (docs/next-terminal.md, Phase 1): - // what core-test is compiled from. No ghostty-vt, wuffs, zstbi or C++; - // a shell boot is a scratch pane, a test that needs a terminal skips, - // and shell-test runs them all with one. - const core_lean = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/pardes.zig"), - .link_libc = true, - }); - - const isolated_mod: ?*std.Build.Module = if (platform == .tui) b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/main.zig"), - .link_libc = true, - }) else null; - - // `zig build static`'s: the addons compiled in (Addon.zig). Linked - // statically on musl alone, as glibc links only dynamically; the gui's - // is dynamic (SDL and the GPU need the display's libraries) with the - // addons in it all the same. - const static_linkage: ?std.builtin.LinkMode = if (target.result.isMuslLibC()) .static else null; - const static_mod: ?*std.Build.Module = if ((platform == .tui and static_linkage != null) or platform == .gui) b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/main.zig"), - .link_libc = true, - }) else null; - - const gui_mod: ?*std.Build.Module = if (also_gui) b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/main.zig"), - .link_libc = true, - }) else null; - - const CoreMod = struct { mod: ?*std.Build.Module, shell: Platform }; - var core_mods_buf: [6]*std.Build.Module = undefined; - var core_shells_buf: [6]Platform = undefined; - var core_mods_len: usize = 0; - // root_mod FIRST: the module map below is folded out of its import table. - for ([_]CoreMod{ - .{ .mod = root_mod, .shell = platform }, - // hxdiff's headless core and pardes-isolate are the primary shell's - // configuration compiled two more ways, not two more frontends. - .{ .mod = core_module, .shell = platform }, - .{ .mod = core_lean, .shell = platform }, - .{ .mod = isolated_mod, .shell = platform }, - .{ .mod = static_mod, .shell = platform }, - .{ .mod = gui_mod, .shell = .gui }, - }) |entry| if (entry.mod) |m| { - core_mods_buf[core_mods_len] = m; - core_shells_buf[core_mods_len] = entry.shell; - core_mods_len += 1; - }; - const core_mods = core_mods_buf[0..core_mods_len]; - // The manifest marks every dependency lazy but tree-sitter's runtime, so - // that a package depending on pardes fetches what `library` takes and - // nothing else. pardes takes these whatever it builds: the missing ones - // are asked for here in one round, the grammars with them, where each - // `b.dependency` below would end the configure to fetch its own alone. - const ts = treeSitter(b, io, target, c_optimize, tree_sitter_grammars); - inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| { - // One by path (cloud9, until its pin returns) is there already. - const dep = @field(zon.dependencies, name); - if (@hasField(@TypeOf(dep), "hash")) if (!std.Build.package_map.get(dep.hash).?.available) { - _ = b.lazyDependency(name, .{}); - }; - } - const cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9"); - for (core_mods) |mod| mod.addImport("cloud9", cloud9); - const core_shells = core_shells_buf[0..core_mods_len]; - // The modules the addons are compiled into (Addon.zig reads their - // `pardes_addon`): the static step's, and every one for a system - // Addon.zig's loader, over a Linux memfd, does not run on. - const builtin_mods: []const *std.Build.Module = if (target.result.os.tag != .linux) core_mods else if (static_mod) |m| b.allocator.dupe(*std.Build.Module, &.{m}) catch @panic("OOM") else &.{}; - - // The conditional dependencies, hoisted so one `wireCore` call at the end - // can name them all. The unconditional ones are ordinary consts below. - const ts_mod = ts.mod; - const ts_queries_opts = ts.queries; - var ghostty_core_vt: ?*std.Build.Module = null; - const ts_libs = ts.libs; - - const themes_mod = generatedThemes(b, io, target, optimize); - - // forkpty: in libc proper on glibc>=2.34 and darwin; the BSDs keep it in libutil - if (target.result.os.tag == .freebsd or target.result.os.tag == .netbsd or target.result.os.tag == .openbsd) - root_mod.linkSystemLibrary("util", .{}); - // The macOS shell carries the workspace tag row's commands in its native // menu bar; the row itself goes away. `-Dworkspace-tag=true` puts it back. const workspace_tag = b.option(bool, "workspace-tag", "draw the workspace tag row (default: on except on macOS, whose menu bar carries its commands)"); @@ -294,57 +125,6 @@ pub fn build(b: *std.Build) void { // stamps one anyway. const stamp_commit = b.option(bool, "stamp-commit", "embed the git commit in --version and crash records (default: release builds and the ~/.local install)") orelse (optimize != .debug or home_install); - const shell_cfg: ShellConfig = .{ - .tree_sitter_grammars = tree_sitter_grammars, - .tracy = tracy != null, - .workspace_tag = workspace_tag, - .prebuilt_shaders = prebuilt_shaders, - .embed_sources = embed_sources, - .commit = if (stamp_commit) gitCommit(b) else null, - .change = if (stamp_commit) jjChange(b) else null, - .built = if (stamp_commit) command(b, &.{ "date", "-u", "+%Y-%m-%d %H:%M UTC" }) else null, - }; - const opts = shellOptions(b, shell_cfg, platform); - const gui_opts: ?*std.Build.Step.Options = if (also_gui) shellOptions(b, shell_cfg, .gui) else null; - - if (tracy) |tracy_path| { - for ([_]*std.Build.Module{ root_mod, core_module }) |mod| { - mod.addIncludePath(.{ .cwd_relative = tracy_path }); - mod.addCSourceFile(.{ - .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) }, - .flags = &.{ - "-DTRACY_ENABLE=1", - "-DTRACY_NO_SAMPLING", - "-DTRACY_NO_CALLSTACK", - "-DTRACY_NO_SYSTEM_TRACING", - "-DTRACY_NO_CRASH_HANDLER", - "-DTRACY_NO_CODE_TRANSFER", - "-fno-sanitize=undefined", - }, - }); - mod.link_libcpp = true; - } - } - - 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 - // with it holding the editor. Its matcher gets a step budget, patched into - // the fetched source here at build time so that a fresh fetch keeps it: - // each entry to matchPattern, which its backtracking recurses through, - // spends a step, and with none left the match fails and says so - // (src/regexp.zig). A bump that moves the anchor stops the build. - const mvzr_mod = patchedMvzr(b, io, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize); - - // The C heap every C library with an allocator hook is handed: the core's - // tree-sitter and fonts, and pdf.zig's MuPDF, which is a module of its own. - const c_heap_mod = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/c_heap.zig"), - }); - // MuPDF, and the FreeType and zlib it is built against, are lazy: a // build asks for them only when it builds the pdf addon (or a window, // FreeType). Zig 0.17's configure is told the -D options and never the @@ -354,788 +134,92 @@ pub fn build(b: *std.Build) void { // MuPDF once. const pdf = b.option(bool, "pdf", "build the pdf addon over MuPDF (default: on once MuPDF is fetched, as -Dpdf does)") orelse (std.Build.package_map.get(zon.dependencies.mupdf.hash).?.available or target.result.os.tag != .linux); - const mupdf_dep = if (pdf) b.lazyDependency("mupdf", .{}) else null; - // 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 = if (pdf or also_gui or platform == .gui) b.lazyDependency("freetype", .{ - .target = target, - .optimize = c_optimize, - .@"enable-libpng" = false, - }) else null; - const freetype = if (freetype_dep) |d| d.artifact("freetype") else null; - // The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's - // records are the header's, never a mirror of it. - const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); - // ...and what an addon in Zig imports over it (src/kinds/addon.zig). - const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); - const snake_shader_step = b.step("snake-shader", "build the optional GPU snake addon into zig-out/lib"); - var snake_shader_lib: ?*std.Build.Step.Compile = null; - const veil_step = b.step("veil", "build the frame corpus's translucent GPU test addon (test/veil.zig) into zig-out/lib"); - if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { - const files = b.addWriteFiles(); - for ([_][]const u8{ "vert", "frag", "post.frag" }) |stage| { - const compile = b.addSystemCommand(&.{ "glslc", "-O" }); - compile.addFileArg(b.path(b.fmt("addons/snake_shader/snake.{s}", .{stage}))); - compile.addArg("-o"); - _ = files.addCopyFile(compile.addOutputFileArg(b.fmt("snake.{s}.spv", .{stage})), b.fmt("{s}.spv", .{stage})); - } - const shader_module = b.createModule(.{ .root_source_file = files.add("shaders.zig", "const v align(4) = @embedFile(\"vert.spv\").*;\npub const vert: []const u8 = &v;\nconst f align(4) = @embedFile(\"frag.spv\").*;\npub const frag: []const u8 = &f;\nconst p align(4) = @embedFile(\"post.frag.spv\").*;\npub const post: []const u8 = &p;\n") }); - const module = b.createModule(.{ .root_source_file = b.path("addons/snake_shader/snake_shader.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") }, .{ .name = "shaders", .module = shader_module } } }); - const lib = b.addLibrary(.{ .name = "snake_shader", .linkage = .dynamic, .root_module = module }); - snake_shader_lib = lib; - snake_shader_step.dependOn(&b.addInstallArtifact(lib, .{}).step); - snake_shader_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); - // The frame corpus's translucent addon (test/veil.zig), into lib/ beside the snake. - const veil = b.addLibrary(.{ .name = "veil", .linkage = .dynamic, .root_module = b.createModule(.{ .root_source_file = b.path("test/veil.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") } } }) }); - veil_step.dependOn(&b.addInstallArtifact(veil, .{}).step); - } - // The PDF addon (addons/pdf/pdf.zig over MuPDF through pdf_bridge.c), built - // and installed as the image addon is: compiled only for a step that - // needs it (`pdf`, the tests). MuPDF is compiled against the build's - // FreeType and zlib and links them into the library, which holds its - // own copy of each beside a window's FreeType (docs/shared-libs.md); so - // all three are position-independent, and the library exports its - // `pardes_addon` alone. - var pdf_addon: ?*std.Build.Step.Compile = null; - if (mupdf_dep) |md| if (freetype_dep) |fd| { - // ...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 = fd.builder.dependency("zlib", .{ .target = target, .optimize = c_optimize }).artifact("z"); - freetype.?.root_module.pic = true; - zlib.root_module.pic = true; - const mupdf = mupdf_build.add(b, io, md, .{ - .target = target, - .optimize = c_optimize, - .jpx = enable_jpx, - .freetype = freetype.?, - .zlib = zlib, - .pic = true, - }); - // The bridge's header translated here for pdf.zig (Zig 0.17 has no - // @cImport), as the kinds' header is for the core. - const bridge_mod = b.addTranslateC(.{ .root_source_file = b.path("addons/pdf/pdf_bridge.h"), .target = target, .optimize = c_optimize }).createModule(); - const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); - mupdf.linkTo(pdf_mod); - pdf_mod.addIncludePath(b.path("addons/pdf")); - pdf_mod.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); - const lib = b.addLibrary(.{ .name = "pdf", .linkage = .dynamic, .root_module = pdf_mod }); - lib.setVersionScript(b.addWriteFiles().add("pdf.map", "{ global: pardes_addon; local: *; };\n")); - pdf_addon = lib; - // ...and the same module compiled into a pardes, which exports - // nothing there (addon.exportLib). - for (builtin_mods) |m| m.addImport("pdf_addon", pdf_mod); - mupdf_check.dependOn(mupdf_build.addProbe(b, mupdf, .{ - .target = target, - .pdf = b.path("docs/design.pdf"), - })); + const mupdf_check = b.step("mupdf-check", "the pdf addon's check: MuPDF compiles, links, renders and searches docs/design.pdf, and its script runs"); + const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])"); + const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])"); - // The PDF benches: the core over the addon, a pane of it. - const config = b.addOptions(); - config.addOption(bool, "release_fast_core", optimize == .fast); - config.addOption([]const u8, "core_optimize", @tagName(optimize)); - config.addOptionPath("pdf_addon", lib.getEmittedBin()); - for ([_]struct { step: *std.Build.Step, exe: []const u8, file: []const u8, optimize: std.lang.Optimize }{ - .{ .step = pdf_pointer_bench_step, .exe = "pardes-pdf-pointer-bench", .file = "test/pdf_pointer_bench.zig", .optimize = .fast }, - .{ .step = pdf_scroll_bench_step, .exe = "pardes-pdf-scroll-bench", .file = "test/pdf_scroll_bench.zig", .optimize = optimize }, - }) |bench| { - const exe = b.addExecutable(.{ .name = bench.exe, .root_module = b.createModule(.{ .target = target, .optimize = bench.optimize, .root_source_file = b.path(bench.file), .link_libc = true }) }); - exe.root_module.addImport("pardes", core_module); - exe.root_module.addOptions("pdf_bench_config", config); - const run = b.addRunArtifact(exe); - run.addPassthruArgs(); - run.setCwd(b.path(".")); - bench.step.dependOn(&run.step); - } + const shell_cfg: core.ShellConfig = .{ + .tree_sitter_grammars = tree_sitter_grammars, + .tracy = tracy != null, + .workspace_tag = workspace_tag, + .prebuilt_shaders = prebuilt_shaders, + .embed_sources = embed_sources, + .commit = if (stamp_commit) core.gitCommit(b) else null, + .change = if (stamp_commit) core.jjChange(b) else null, + .built = if (stamp_commit) core.command(b, &.{ "date", "-u", "+%Y-%m-%d %H:%M UTC" }) else null, }; - // Without it, what needs it says how to have it. - const no_pdf: ?*std.Build.Step = if (pdf_addon == null) &b.addFail("this step needs the pdf addon, over MuPDF: add -Dpdf (it is fetched once, and on from then)").step else null; - if (no_pdf) |s| for ([_]*std.Build.Step{ mupdf_check, pdf_pointer_bench_step, pdf_scroll_bench_step }) |step| step.dependOn(s); - - const uucode_mod = uucodeModule(b, target, optimize).?; - - const vaxis_dep = b.dependency("vaxis", .{ + // What every core is made of, the shells' options and the addons + // (build/core.zig). + const a = core.assemble(b, .{ .target = target, .optimize = optimize, - .external_uucode = true, - }); - const vaxis_mod = vaxis_dep.module("vaxis"); - // vaxis's input parser, patched here at build time like mvzr so that a - // fresh fetch keeps it: no reply, split read or malformed sequence may - // reach the editor as typed text, and none may panic or end input. - // - A cursor position report that no F3 could have sent is no key: the - // startup width queries' `CSI 1;1R` arrived as two F3s, which a shell - // pane took for text. - // - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key, - // not Alt+Escape followed by `[A` as text. - // - An X10 mouse report and a kitty graphics reply cut short by a read - // wait for their rest: the first became three bytes of text, the - // second sliced past its input. - // - A byte no UTF-8 starts with is dropped instead of failing the parse, - // which stopped input. (vaxis itself now drops a malformed color or - // clipboard reply and ends an OSC at its first terminator.) - // - A device report's fields are sought in the sequence, not past it. - // A bump that moves an anchor stops the build. - { - var src = configureRead(b, io, vaxis_dep.builder.root, "src/Parser.zig", 1 << 20) catch @panic("read vaxis Parser.zig"); - const edits = [_]struct { anchor: []const u8, with: []const u8, count: usize = 1 }{ - .{ - .anchor = - \\ 0x5F => return parseApc(input), - \\ else => { - , - .with = - \\ 0x5F => return parseApc(input), - \\ // pardes's patch (its build.zig): ESC before a key's sequence is Alt on the key. - \\ 0x1B => if (input.len > 2 and (input[2] == '[' or input[2] == 'O')) { - \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf, self.cursor_position_requests) else parseSs3(input[1..]); - \\ if (inner.n == 0) return inner; - \\ if (inner.event) |*event| switch (event.*) { - \\ .key_press, .key_release => |*key| key.mods.alt = true, - \\ else => {}, - \\ }; - \\ inner.n += 1; - \\ return inner; - \\ } else return .{ .event = .{ .key_press = .{ .codepoint = Key.escape, .mods = .{ .alt = true } } }, .n = 2 }, - \\ else => { - , - }, - .{ - .anchor = " const first_cp = iter.next() orelse return error.InvalidUTF8;\n", - .with = " const first_cp = iter.next() orelse return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n", - }, - .{ - .anchor = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return error.InvalidUTF8;\n", - .with = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n", - }, - .{ - .anchor = - \\ const sequence = input[0 .. end + 1 + 1]; - \\ - \\ switch (input[2]) { - , - .with = - \\ // pardes's patch (its build.zig): an ESC that ends the input is half an ST. - \\ if (input.len < end + 2) return .{ .event = null, .n = 0 }; - \\ const sequence = input[0 .. end + 1 + 1]; - \\ - \\ switch (input[2]) { - , - }, - .{ - .anchor = - \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { - \\ // Legacy keys - \\ - , - .with = - \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { - \\ // pardes's patch (its build.zig): a cursor position report is no key. - \\ if (final == 'R' and cursorReport(sequence)) return null_event; - \\ // Legacy keys - \\ - , - }, - .{ - .anchor = " std.debug.assert(sequence.len >= 4); // ESC [ ? c == 4 bytes\n", - .with = " if (sequence.len < 4) return null_event; // pardes's patch (its build.zig)\n", - }, - .{ - .anchor = "const delim_idx = std.mem.indexOfScalarPos(u8, input, 3, ';')", - .with = "const delim_idx = std.mem.indexOfScalarPos(u8, sequence, 3, ';')", - .count = 2, - }, - .{ - .anchor = "input[delim_idx + 1 .. sequence.len - 2]", - .with = "sequence[@min(delim_idx + 1, sequence.len - 2) .. sequence.len - 2]", - }, - .{ - .anchor = " if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {\n", - .with = - \\ // pardes's patch (its build.zig): an X10 report still arriving is incomplete, not text. - \\ if (input.len == 3 and input[2] == 'M' and full_input.len < 6) return .{ .event = null, .n = 0 }; - \\ if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) { - \\ - , - }, - }; - for (edits) |edit| { - if (std.mem.count(u8, src, edit.anchor) != edit.count) std.debug.panic("vaxis's Parser.zig changed at `{s}`: redo its patch in build.zig", .{edit.anchor}); - src = std.mem.replaceOwned(u8, b.allocator, src, edit.anchor, edit.with) catch @panic("OOM"); - } - const cursor_report = - \\ - \\/// pardes's patch (its build.zig): whether `CSI ... R` answers a cursor - \\/// position query. Only `CSI 1 ; mods R` with mods past 1 is a modified F3 - \\/// (a bare F3 is `SS3 R`); a report has another row, or col 1 (mods 1). - \\fn cursorReport(sequence: []const u8) bool { - \\ const params = sequence[2 .. sequence.len - 1]; - \\ if (params.len > 0 and params[0] == '?') return true; - \\ var fields = std.mem.splitScalar(u8, params, ';'); - \\ const row = fields.first(); - \\ const col = fields.next() orelse return false; - \\ if (fields.next() != null or row.len == 0 or col.len == 0) return false; - \\ for (params) |c| if (c != ';' and !std.ascii.isDigit(c)) return false; - \\ return !std.mem.eql(u8, row, "1") or std.mem.eql(u8, col, "1"); - \\} - \\ - ; - // vaxis's render, patched the same way: a blank whose ink alone - // changed is not sent, since a blank's ink shows nowhere. A fade - // (InactiveDim on a focus change) sent every blank of every pane it - // touched again: 7 KB a click for three shell panes. The terminal - // keeps the old ink there, and so does vaxis's last frame. - var render_src = configureRead(b, io, vaxis_dep.builder.root, "src/Vaxis.zig", 1 << 20) catch @panic("read vaxis Vaxis.zig"); - const render_anchor = - \\ if ((!self.refresh and - \\ last.eql(cell) and - ; - if (std.mem.count(u8, render_src, render_anchor) != 1) std.debug.panic("vaxis's Vaxis.zig changed at `{s}`: redo its patch in build.zig", .{render_anchor}); - render_src = std.mem.replaceOwned(u8, b.allocator, render_src, render_anchor, - \\ if ((!self.refresh and - \\ (last.eql(cell) or blankInkOnly(&last, &cell)) and // pardes's patch (its build.zig) - \\ - ) catch @panic("OOM"); - // And the secondary cursors count as changed when they differ, not - // when they are the same: read the other way round, every render - // started a frame, ~40 bytes to the terminal with nothing changed. - const secondary_anchor = " std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary);\n"; - if (std.mem.count(u8, render_src, secondary_anchor) != 1) std.debug.panic("vaxis's Vaxis.zig changed at `{s}`: redo its patch in build.zig", .{secondary_anchor}); - render_src = std.mem.replaceOwned(u8, b.allocator, render_src, secondary_anchor, " !std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary); // pardes's patch (its build.zig)\n") catch @panic("OOM"); - const blank_ink = - \\ - \\/// pardes's patch (its build.zig): a blank cell (a space, no underline, - \\/// strike or reverse) that differs from the last frame's blank in its - \\/// ink alone, which shows nowhere. - \\inline fn blankInkOnly(last: *const InternalScreen.InternalCell, cell: *const Cell) bool { - \\ if (!(cell.char.grapheme.len == 1 and cell.char.grapheme[0] == ' ')) return false; - \\ if (last.default or cell.default) return false; - \\ if (!(last.char.items.len == 1 and last.char.items[0] == ' ')) return false; - \\ const s = cell.style; - \\ if (s.reverse or s.strikethrough or s.ul_style != .off) return false; - \\ if (!std.mem.eql(u8, last.uri.items, cell.link.uri)) return false; - \\ // Field by field: Style.eql is slow, and this runs for every blank - \\ // a scrolling shell moves. - \\ const l = last.style; - \\ return sameColor(l.bg, s.bg) and sameColor(l.ul, s.ul) and l.ul_style == s.ul_style and - \\ l.bold == s.bold and l.dim == s.dim and l.italic == s.italic and l.blink == s.blink and - \\ !l.reverse and !l.strikethrough and l.invisible == s.invisible; - \\} - \\ - \\inline fn sameColor(a: Cell.Color, b: Cell.Color) bool { - \\ return switch (a) { - \\ .default => b == .default, - \\ .index => |i| b == .index and b.index == i, - \\ .rgb => |rgb| b == .rgb and rgb[0] == b.rgb[0] and rgb[1] == b.rgb[1] and rgb[2] == b.rgb[2], - \\ }; - \\} - \\ - ; - // And its event queue: a pop that makes room woke one blocked - // writer, and only on the pop from full. The tui has two writers - // (a pane's pty reader, and the input reader posting the frame - // ack's wake), so when the loop emptied a full queue in one batch - // the writer not woken waited on for good: under `yes` the pane - // stopped being read, its program blocked on the pty, while keys - // went on working. Every blocked writer is woken now. - var queue_src = configureRead(b, io, vaxis_dep.builder.root, "src/queue.zig", 1 << 20) catch @panic("read vaxis queue.zig"); - const wake_one = "self.not_full.signal(self.io);"; - if (std.mem.count(u8, queue_src, wake_one) != 2) std.debug.panic("vaxis's queue.zig changed at `{s}`: redo its patch in build.zig", .{wake_one}); - queue_src = std.mem.replaceOwned(u8, b.allocator, queue_src, wake_one, "self.not_full.broadcast(self.io); // pardes's patch (its build.zig)") catch @panic("OOM"); - const files = b.addWriteFiles(); - _ = files.add("Parser.zig", b.fmt("{s}{s}", .{ src, cursor_report })); - _ = files.add("Vaxis.zig", b.fmt("{s}{s}", .{ render_src, blank_ink })); - _ = files.add("queue.zig", queue_src); - _ = files.addCopyFile(vaxis_dep.path("src/widgets/terminal/Parser.zig"), "widgets/terminal/Parser.zig"); - // Suffixes: this leaves out both Parser.zig files, Vaxis.zig and - // queue.zig, written above. - _ = files.addCopyDirectory(vaxis_dep.path("src"), "", .{ .exclude_extensions = &.{ "Parser.zig", "Vaxis.zig", "queue.zig" } }); - vaxis_mod.root_source_file = files.getDirectory().path(b, "main.zig"); - } - - var ghostty_vt_for_tests: ?*std.Build.Module = null; - 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| { - const ghostty_vt = dep.module("ghostty-vt"); - ghostty_vt_for_tests = ghostty_vt; - ghostty_vt.addImport("uucode", uucode_mod); - patchGhosttyKitty(b, io, dep, ghostty_vt); - ghostty_core_vt = ghostty_vt; - } - // override uucode on vaxis LAST so it wins over ghostty's build() wiring. - vaxis_mod.addImport("uucode", uucode_mod); - - // One PNG decoder (docs/shared-libs.md): ghostty's, wuffs, which - // ghostty-vt links for kitty graphics whatever pardes does; a terminal's - // PNG is decoded through it (TerminalImages.zig), and of zstbi only its - // resize is left, for the PNG's downscale: stb_image and its writer - // (with the deflate it carries) are patched out, here at build time so - // a fresh fetch keeps it. The image addon has its own (addons/image). - const wuffs_mod: ?*std.Build.Module = if (ghostty_core_vt) |vt| vt.import_table.get("wuffs") else null; - { - var sources: usize = 0; - for (zstbi_mod.link_objects.items) |obj| switch (obj) { - .c_source_file => |csf| { - sources += 1; - var src = configureRead(b, io, zstbi_dep.builder.root, "src/zstbi.c", 1 << 20) catch @panic("read zstbi.c"); - // zstbi.deinit still resets the reader's and the writer's - // flip flags, and Image.deinit frees the resize's output. - for ([_][2][]const u8{ - .{ "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" }, - .{ "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" }, - }) |cut| { - if (std.mem.count(u8, src, cut[0]) != 1) std.debug.panic("zstbi.c changed at `{s}`: redo its patch in build.zig", .{cut[0]}); - src = std.mem.replaceOwned(u8, b.allocator, src, cut[0], cut[1]) catch @panic("OOM"); - } - csf.file = b.addWriteFiles().add("zstbi.c", src); - }, - 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 - // compressor and decompressor alone, single-threaded and without its - // x86 assembly, each context made with ZSTD_customMem over c_heap; of - // 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. - { - const dep = b.dependency("zstd", .{}); - const zstd = b.addLibrary(.{ - .name = "zstd", - .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }), - .linkage = .static, - }); - zstd.root_module.addCSourceFiles(.{ - .root = dep.path("lib"), - .files = &.{ - "common/debug.c", "common/entropy_common.c", "common/error_private.c", - "common/fse_decompress.c", "common/pool.c", "common/threading.c", - "common/xxhash.c", "common/zstd_common.c", "compress/fse_compress.c", - "compress/hist.c", "compress/huf_compress.c", "compress/zstd_compress.c", - "compress/zstd_compress_literals.c", "compress/zstd_compress_sequences.c", "compress/zstd_compress_superblock.c", - "compress/zstd_double_fast.c", "compress/zstd_fast.c", "compress/zstd_lazy.c", - "compress/zstd_ldm.c", "compress/zstd_opt.c", "compress/zstd_preSplit.c", - "decompress/huf_decompress.c", "decompress/zstd_ddict.c", "decompress/zstd_decompress.c", - "decompress/zstd_decompress_block.c", - }, - .flags = &.{ - "-DXXH_NAMESPACE=ZSTD_", "-DZSTD_DISABLE_ASM", "-DZSTD_LEGACY_SUPPORT=0", - "-DDEBUGLEVEL=0", "-DZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR", - "-DZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR", - }, - }); - zstd.link_function_sections = true; - zstd.link_data_sections = true; - for (core_mods) |m| m.linkLibrary(zstd); - } - - // xitdb keeps what pardes writes to disk (src/Db.zig): pure Zig, no C - // library and no allocator hook of its own (it takes Zig allocators). - const xitdb_mod = b.dependency("xitdb", .{ .target = target, .optimize = optimize }).module("xitdb"); - - // One call per module instead of one line per module per dependency, and - // BEFORE the fold below, which reads what these imports put in the table. - // The image addon (addons/image/image.zig over stb_image, stb.c), - // installed by its step and handed by path to every test that opens a - // picture. - const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); - image_mod.addIncludePath(zstbi_dep.path("libs/stbi")); - image_mod.addCSourceFile(.{ .file = b.path("addons/image/stb.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); - const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = image_mod }); - for (builtin_mods) |m| m.addImport("image_addon", image_mod); - // The records the core and the terminal both name (src/plain/plain.zig). - const plain_mod = b.createModule(.{ .root_source_file = b.path("src/plain/plain.zig"), .target = target, .optimize = optimize }); - // The terminal, a module of its own (src/term/term.zig): the emulator and - // what it brings are its, and every core but core-test's is given it. - const term_mod = b.createModule(.{ .root_source_file = b.path("src/term/term.zig"), .target = target, .optimize = optimize, .link_libc = true }); - term_mod.addImport("plain", plain_mod); - if (ghostty_core_vt) |x| term_mod.addImport("ghostty-vt", x); - if (wuffs_mod) |x| term_mod.addImport("wuffs", x); - term_mod.addImport("zstbi", zstbi_mod); - const term_on = b.addOptions(); - term_on.addOption(bool, "terminal", true); - const term_off = b.addOptions(); - term_off.addOption(bool, "terminal", false); - for (core_mods) |m| if (m == core_lean) { - m.addOptions("term_options", term_off); - } else { - m.addImport("term", term_mod); - m.addOptions("term_options", term_on); - }; - for (core_mods) |m| wireCore(m, .{ - .plain = plain_mod, - .kind = kind_mod, - .themes = themes_mod, - .tree_sitter = ts_mod, - .ts_libs = ts_libs.items, - .ts_queries = ts_queries_opts, - .mvzr = mvzr_mod, - .c_heap = c_heap_mod, - .vaxis = vaxis_mod, - .uucode = uucode_mod, - .xitdb = xitdb_mod, + .c_optimize = c_optimize, + .tree_sitter_grammars = tree_sitter_grammars, + .tracy = tracy, + .shell_cfg = shell_cfg, + .platform = platform, + .also_gui = also_gui, + .pdf = pdf, + .enable_jpx = enable_jpx, + .doc_typ = doc_typ_opts, + .mupdf_check = mupdf_check, + .pdf_pointer_bench_step = pdf_pointer_bench_step, + .pdf_scroll_bench_step = pdf_scroll_bench_step, }); + const parts = a.parts; + const opts = a.opts; + // Off Linux, whose memfd Addon.zig's loader needs, every core has the + // addons compiled in. + const compiled_in = target.result.os.tag != .linux; + // The macOS shell is a library whose host owns main(): it roots at + // its own flat C ABI instead of src/main.zig. Tracy's client and BSD + // libutil go to the shell (and Tracy's to the core) alone, as before + // core.module. + const root_mod = core.module(b, parts, .{ .root = if (platform == .macos) "src/macos.zig" else "src/main.zig", .config = opts, .builtin_addons = compiled_in, .tracy = true, .util = true }); + // hxdiff's headless core and pardes-isolate are the primary shell's + // configuration compiled two more ways, not two more frontends. + const core_cfg: core.Core = .{ .root = "src/pardes.zig", .config = opts, .builtin_addons = compiled_in, .tracy = true }; + const core_module = core.module(b, parts, core_cfg); + // The core without the terminal module (docs/next-terminal.md, Phase 1): + // what core-test is compiled from. No ghostty-vt, wuffs, zstbi or C++; + // a shell boot is a scratch pane, a test that needs a terminal skips, + // and shell-test runs them all with one. + const lean_cfg: core.Core = .{ .root = "src/pardes.zig", .config = opts, .builtin_addons = compiled_in, .terminal = false }; + const core_lean = core.module(b, parts, lean_cfg); + const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "src/main.zig", .config = opts, .builtin_addons = compiled_in, .isolated = true }) else null; + // `zig build static`'s: the addons compiled in (Addon.zig). Linked + // statically on musl alone, as glibc links only dynamically; the gui's + // is dynamic (SDL and the GPU need the display's libraries) with the + // addons in it all the same. + const static_linkage: ?std.builtin.LinkMode = if (target.result.isMuslLibC()) .static else null; + const static_mod: ?*std.Build.Module = if ((platform == .tui and static_linkage != null) or platform == .gui) core.module(b, parts, .{ .root = "src/main.zig", .config = opts, .builtin_addons = true }) else null; + const gui_mod: ?*std.Build.Module = if (also_gui) core.module(b, parts, .{ .root = "src/main.zig", .config = a.gui_opts.?, .builtin_addons = compiled_in }) else null; + if (a.pdf.lib) |lib| tools.pdfBenches(b, target, optimize, core_module, lib, pdf_pointer_bench_step, pdf_scroll_bench_step); - const iso_off = b.addOptions(); - iso_off.addOption(bool, "isolated", false); - const iso_on = b.addOptions(); - iso_on.addOption(bool, "isolated", true); - const builtin_off = b.addOptions(); - builtin_off.addOption(bool, "on", false); - const builtin_on = b.addOptions(); - builtin_on.addOption(bool, "on", true); - // ...the pdf one only when it is built (-Dpdf=false leaves it out). - builtin_on.addOption(bool, "pdf", pdf_addon != null); - - for (core_mods, core_shells) |mod, shell| { - // config.zig's test checks the words and keys docs/typ names exist. - mod.addOptions("doc_typ", doc_typ_opts); - mod.addOptions("pardes_config", if (also_gui and shell == .gui) gui_opts.? else opts); - mod.addOptions("pardes_isolation", if (isolated_mod == mod) iso_on else iso_off); - mod.addOptions("builtin_addons", if (std.mem.indexOfScalar(*std.Build.Module, builtin_mods, mod) != null) builtin_on else builtin_off); - } - - // docs/typ/builtins-<platform>.json: every builtin, from the registry and the Help - // rows (src/builtins_json.zig), rewritten in the source tree so a plain - // `typst compile` reads it too; a unit test fails when it is stale. - // A terminal build writes builtins-tui.json and a window build - // builtins-gui.json; style.typ merges the two into one glossary. - const builtins_json_step = b.step("builtins-json", "rewrite docs/typ/builtins-<tui|gui>.json from the builtin registry, and with tui docs/typ/command-line.txt from pardes help --all (-Dplatform=tui or gui)"); - if (requested_platform == .tui or requested_platform == .gui) { - const gen = b.addExecutable(.{ .name = "pardes-gen-builtins-json", .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("tools/gen_builtins_json.zig"), - .imports = &.{.{ .name = "pardes", .module = core_module }}, - }) }); - const run_gen = b.addRunArtifact(gen); - const json = run_gen.addOutputFileArg("builtins.json"); - for ([_][]const u8{ "image/image.zig", "pdf/pdf.zig" }) |f| run_gen.addFileArg(b.path(b.fmt("addons/{s}", .{f}))); - const update = b.addUpdateSourceFiles(); - update.addCopyFileToSource(json, b.fmt("docs/typ/builtins-{s}.json", .{@tagName(platform)})); - builtins_json_step.dependOn(&update.step); - for (doc_renders) |r| if (r) |run| run.step.dependOn(&update.step); - } else builtins_json_step.dependOn(&b.addFail("builtins-json writes one build's list: pass -Dplatform=tui or -Dplatform=gui").step); + const builtins_json_step = docs.builtinsJson(b, requested_platform, platform, target, optimize, core_module, doc_renders); - const gui_shell_mod: ?*std.Build.Module = gui_mod orelse - if (platform == .gui) root_mod else null; - // The static step's gui module is a gui shell too. - const gui_shell_mods: [2]?*std.Build.Module = .{ gui_shell_mod, if (platform == .gui) static_mod else null }; - // SDL's headers, for the macOS trackpad adapter's test after the loop. - var sdl_include: ?std.Build.LazyPath = null; - // sketchbook's Cells.zig's own tests (the instance ABI), for unit-test. + // The window's shells: the bare build's pardes-gui; -Dplatform=gui's + // pardes-gui and its static. var cells_test: ?*std.Build.Step.Compile = null; - // sketchbook's Atlas.zig's own tests, for unit-test. var atlas_test: ?*std.Build.Step.Compile = null; - for (gui_shell_mods) |gui_shell_entry| if (gui_shell_entry) |gm| { - // This shell's `c`, for the Atlas's tests below. - var font_c: ?*std.Build.Module = null; - // SDL's build asks a cross build for macOS for the SDK's paths. - const sdk: ?std.Build.LazyPath = if (macos_sdk) |p| .{ .cwd_relative = p } else null; - const sdl_dep = b.lazyDependency("sdl", .{ .target = target, .optimize = optimize, .sanitize_c = .off, .preferred_linkage = .static, .system_include_path = if (sdk) |p| p.path(b, "usr/include") else null, .system_framework_path = if (sdk) |p| p.path(b, "System/Library/Frameworks") else null, .library_path = if (sdk) |p| p.path(b, "usr/lib") else null }); - if (sdl_dep) |dep| { - const sdl_lib = dep.artifact("SDL3"); - // SDL's own stb_image (SDL_stb.c, for SDL_LoadPNG and a camera's - // MJPEG, neither of which pardes calls) is a second PNG and JPEG - // decoder beside the build's: off (docs/shared-libs.md). - sdl_lib.root_module.addCMacro("SDL_DISABLE_STB", "1"); - gm.linkLibrary(sdl_lib); - gm.addIncludePath(dep.path("include")); - // gui.zig's `c`: SDL and the font shim, which @cImport gave it before Zig 0.17. - const header = b.addWriteFiles().add("gui_c.h", - \\#define SDL_DISABLE_OLD_NAMES 1 - \\#include <SDL3/SDL.h> - \\#include "font.h" - \\#include "macos_trackpad.h" - \\ - ); - const gui_c = b.addTranslateC(.{ .root_source_file = header, .target = target, .optimize = optimize }); - gui_c.addIncludePath(dep.path("include")); - gui_c.addIncludePath(b.path("src/gui")); - const gui_c_mod = gui_c.createModule(); - font_c = gui_c_mod; - gm.addImport("gui_c", gui_c_mod); - if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { - const gpu = b.createModule(.{ .root_source_file = sb.path("dev/draw/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } }); - gm.addImport("sketch_gpu", gpu); - // The glyph atlas (dev/text/Atlas.zig) over the font shim - // (vendor/font.{c,h}), compiled below against pardes's - // FreeType and HarfBuzz. - const atlas_mod = b.createModule(.{ .root_source_file = sb.path("dev/text/Atlas.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} }); - gm.addImport("font_atlas", atlas_mod); - // pardes's renderer, moved to sketchbook (dev/draw/), compiled - // against pardes's SDL; its tests run with unit-test. Its - // SPIR-V is sketchbook's GLSL through glslc, or the prebuilt - // copies with -Dprebuilt-shaders. - const cells_mod = b.createModule(.{ .root_source_file = sb.path("dev/draw/Cells.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }); - for (gui_shaders) |name| cells_mod.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{ - .root_source_file = if (prebuilt_shaders) - sb.path(b.fmt("dev/draw/shaders/prebuilt/{s}.spv", .{name})) - else - compileGlsl(b, sb.path(b.fmt("dev/draw/shaders/{s}.glsl", .{name})), name), - }); - gm.addImport("gpu_cells", cells_mod); - gm.addImport("gpu_present", b.createModule(.{ .root_source_file = sb.path("dev/draw/Present.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "gpu_cells", .module = cells_mod } } })); - if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("dev/draw/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }), .filters = test_filters }); - gui_c.addIncludePath(sb.path("vendor")); - gm.addImport("gpu_scene", sb.module("gpu_scene")); - } - sdl_include = dep.path("include"); - if (target.result.os.tag == .macos) { - const arch = if (target.result.cpu.arch == .aarch64) "arm64" else @tagName(target.result.cpu.arch); - const shim = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O2", "-target", b.fmt("{s}-apple-macos13.0", .{arch}), "-I" }); - shim.addDirectoryArg(dep.path("include")); - shim.addArg("-c"); - shim.addFileArg(b.path("src/gui/macos_trackpad.m")); - // Header changes invalidate the independently compiled adapter. - shim.addFileInput(b.path("src/gui/macos_trackpad.h")); - shim.addArg("-o"); - gm.addObjectFile(shim.addOutputFileArg("macos_trackpad.o")); - gm.linkFramework("Cocoa", .{}); - } - } - const ft = freetype orelse continue; - gm.linkLibrary(ft); - // 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, - // plus its allocator: gui.zig's ui_malloc and friends, over a Zig - // allocator, as FreeType's is. - if (b.lazyDependency("harfbuzz", .{})) |upstream| { - const harfbuzz = b.addLibrary(.{ - .name = "harfbuzz", - .linkage = .static, - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .link_libc = true, - .link_libcpp = true, - }), - }); - harfbuzz.root_module.linkLibrary(ft); - harfbuzz.root_module.addIncludePath(upstream.path("src")); - harfbuzz.root_module.addCSourceFile(.{ - .file = upstream.path("src/harfbuzz.cc"), - .flags = &.{ - "-DHAVE_STDBOOL_H", - "-DHAVE_UNISTD_H", - "-DHAVE_SYS_MMAN_H", - "-DHAVE_PTHREAD=1", - "-DHAVE_FREETYPE=1", - "-DHAVE_FT_GET_VAR_BLEND_COORDINATES=1", - "-DHAVE_FT_SET_VAR_BLEND_COORDINATES=1", - "-DHAVE_FT_DONE_MM_VAR=1", - "-DHAVE_FT_GET_TRANSFORM=1", - "-Dhb_malloc_impl=ui_malloc", - "-Dhb_calloc_impl=ui_calloc", - "-Dhb_realloc_impl=ui_realloc", - "-Dhb_free_impl=ui_free", - }, - }); - gm.linkLibrary(harfbuzz); - gm.addIncludePath(upstream.path("src")); - // The Atlas's own tests, over the same FreeType, HarfBuzz and - // shim, the embedded face theirs to draw. - if (atlas_test == null) if (font_c) |fc| if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { - const atlas_mod = b.createModule(.{ .root_source_file = sb.path("dev/text/Atlas.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "c", .module = fc }} }); - atlas_mod.linkLibrary(ft); - atlas_mod.linkLibrary(harfbuzz); - atlas_mod.addIncludePath(upstream.path("src")); - atlas_mod.addCSourceFile(.{ .file = sb.path("vendor/font.c") }); - atlas_mod.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf") }); - atlas_test = b.addTest(.{ .root_module = atlas_mod, .filters = test_filters }); - }; - } - if (target.result.os.tag.isDarwin()) - gm.addRPath(.{ .cwd_relative = "/usr/local/lib" }); - if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| gm.addCSourceFile(.{ .file = sb.path("vendor/font.c") }); - // the embedded UI font: provided as a build import since assets/ lives - // outside the src/ module root (@embedFile can't escape it) - gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ - .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf"), - }); - }; - if (target.result.os.tag == .macos) if (sdl_include) |include| { - const adapter_test = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O1", "-framework", "Cocoa", "-I" }); - adapter_test.addDirectoryArg(include); - adapter_test.addFileArg(b.path("test/macos_trackpad.m")); - adapter_test.addFileInput(b.path("src/gui/macos_trackpad.m")); - adapter_test.addFileInput(b.path("src/gui/macos_trackpad.h")); - adapter_test.addArg("-o"); - const adapter_bin = adapter_test.addOutputFileArg("macos-trackpad-test"); - const run_adapter = std.Build.Step.Run.create(b, "run macos-trackpad-test"); - run_adapter.addFileArg(adapter_bin); - run_adapter.has_side_effects = true; - b.step("macos-trackpad-test", "test native SDL trackpad decoding and haptics without hardware").dependOn(&run_adapter.step); - }; - - if (platform == .macos) { - const header = b.addTranslateC(.{ - .root_source_file = b.path("src/macos/pardes.h"), - .target = target, - .optimize = optimize, - }); - root_mod.addImport("pardes.h", header.createModule()); - - const lib = b.addLibrary(.{ - .name = "pardes", - .linkage = .static, - .root_module = root_mod, - }); - lib.bundle_compiler_rt = true; - lib.bundle_ubsan_rt = true; - const archive: ?std.Build.LazyPath = - if (builtin.os.tag.isDarwin() and target.result.os.tag.isDarwin()) fatArchive(b, lib) else null; - const install_lib: *std.Build.Step = if (archive) |a| - &b.addInstallLibFile(a, "libpardes.a").step - else - &b.addInstallArtifact(lib, .{}).step; - b.getInstallStep().dependOn(install_lib); - b.installFile("src/macos/pardes.h", "include/pardes.h"); - - const app_step = b.step("macos-app", "assemble zig-out/pardes.app (needs macOS + swiftc)"); - const dmg_step = b.step("macos-dmg", "package zig-out/pardes.dmg for distribution (needs macOS + swiftc)"); - if (archive) |lib_archive| { - const apple_arch: []const u8 = - if (target.result.cpu.arch == .aarch64) "arm64" else @tagName(target.result.cpu.arch); - const triple = b.fmt("{s}-apple-macos{d}.{d}", .{ - apple_arch, macos_min_version.major, macos_min_version.minor, - }); - const min_version = b.fmt("{d}.{d}", .{ macos_min_version.major, macos_min_version.minor }); - - const swift_mode: []const u8 = switch (optimize) { - .debug => "-Onone", - .small => "-Osize", - .fast, .safe => "-O", - }; - - const link = b.addSystemCommand(&.{ "swiftc", swift_mode, "-target", triple, "-import-objc-header" }); - link.addFileArg(b.path("src/macos/pardes.h")); - link.addArg("-o"); - const app_bin = link.addOutputFileArg("pardes"); - for ([_][]const u8{ - "main.swift", - "AppDelegate.swift", - "PardesView.swift", - "ScenePostprocessor.swift", - "FileWatcher.swift", - }) |src| - link.addFileArg(b.path(b.fmt("src/macos/Sources/{s}", .{src}))); - link.addFileArg(lib_archive); - link.addArgs(&.{ - "-lc++", - "-framework", - "AppKit", - "-framework", - "CoreText", - "-framework", - "CoreGraphics", - "-framework", - "CoreImage", - "-framework", - "Metal", - }); - - const icon_build = b.addSystemCommand(&.{ "swiftc", "-O", "-target", triple, "-o" }); - const icon_bin = icon_build.addOutputFileArg("pardes-icon"); - icon_build.addFileArg(b.path("src/macos/icon.swift")); - const icon_run = std.Build.Step.Run.create(b, "pardes-icon"); - icon_run.addFileArg(icon_bin); - icon_run.addFileArg(b.path("src/macos/icon.png")); - const icon_dir = icon_run.addOutputDirectoryArg("Resources"); - - const plist = b.addSystemCommand(&.{ - "plutil", "-replace", "LSMinimumSystemVersion", "-string", min_version, "-o", - }); - const plist_out = plist.addOutputFileArg("Info.plist"); - plist.addFileArg(b.path("src/macos/Info.plist")); - - const version_plist = b.addSystemCommand(&.{ - "plutil", "-replace", "CFBundleShortVersionString", "-string", display_version, "-o", - }); - const version_plist_out = version_plist.addOutputFileArg("Info.plist"); - version_plist.addFileArg(plist_out); - - const install_app_bin = b.addInstallFileWithDir(app_bin, .{ .custom = "pardes.app/Contents/MacOS" }, "pardes"); - const install_plist = b.addInstallFileWithDir(version_plist_out, .{ .custom = "pardes.app/Contents" }, "Info.plist"); - const install_scene_kernel = b.addInstallFileWithDir( - b.path("shaders/crt.ci.metal"), - .{ .custom = "pardes.app/Contents/Resources" }, - "crt.ci.metal", - ); - // CFBundleIconFile names this without its extension; without both - // halves the Dock shows the generic blank page. - const install_icon = b.addInstallFileWithDir(icon_dir.path(b, "pardes.icns"), .{ .custom = "pardes.app/Contents/Resources" }, "pardes.icns"); - - const sign = b.addSystemCommand(&.{ "codesign", "--force", "--sign", macos_identity }); - if (!std.mem.eql(u8, macos_identity, "-")) sign.addArgs(&.{ "--options", "runtime", "--timestamp" }); - sign.setCwd(installed("")); - sign.addArg("pardes.app"); - sign.has_side_effects = true; - sign.step.dependOn(&install_app_bin.step); - sign.step.dependOn(&install_plist.step); - sign.step.dependOn(&install_icon.step); - sign.step.dependOn(&install_scene_kernel.step); - app_step.dependOn(&sign.step); - - const dmg = b.addSystemCommand(&.{ "hdiutil", "create", "-volname", "pardes", "-ov", "-format", "UDZO", "-srcfolder" }); - dmg.setCwd(installed("")); - dmg.addArgs(&.{ "pardes.app", "pardes.dmg" }); - dmg.has_side_effects = true; - dmg.step.dependOn(&sign.step); - dmg_step.dependOn(&dmg.step); - - b.getInstallStep().dependOn(&sign.step); - } else { - const why = b.addFail("pardes.app needs a Darwin host and target; drop -Dtarget= or pass -Dtarget=native"); - app_step.dependOn(&why.step); - dmg_step.dependOn(&why.step); - } - - const e2e_step = b.step("macos-e2e", "run the offscreen AppKit snapshot suite (needs macOS + swiftc)"); - if (archive) |lib_archive| { - const arch = if (target.result.cpu.arch == .aarch64) "arm64" else @tagName(target.result.cpu.arch); - const triple = b.fmt("{s}-apple-macos{d}.{d}", .{ arch, macos_min_version.major, macos_min_version.minor }); - const e2e = b.addSystemCommand(&.{ "swiftc", "-O", "-target", triple, "-import-objc-header" }); - e2e.addFileArg(b.path("src/macos/pardes.h")); - e2e.addArg("-o"); - const e2e_bin = e2e.addOutputFileArg("pardes-macos-e2e"); - for ([_][]const u8{ - "src/macos/Sources/PardesView.swift", - "src/macos/Sources/ScenePostprocessor.swift", - "src/macos/Sources/FileWatcher.swift", - "src/macos/Sources/AppDelegate.swift", - "test/macos_e2e.swift", - }) |source| e2e.addFileArg(b.path(source)); - e2e.addFileArg(lib_archive); - e2e.addArgs(&.{ "-lc++", "-framework", "AppKit", "-framework", "CoreText", "-framework", "CoreGraphics", "-framework", "CoreImage", "-framework", "Metal" }); - const files = b.addWriteFiles(); - const runnable = files.addCopyFile(e2e_bin, "pardes-macos-e2e"); - _ = files.addCopyFile(b.path("shaders/crt.ci.metal"), "crt.ci.metal"); - const run_e2e = std.Build.Step.Run.create(b, "run macos-e2e"); - run_e2e.addFileArg(runnable); - run_e2e.setCwd(b.path(".")); - run_e2e.addPassthruArgs(); - run_e2e.has_side_effects = true; - e2e_step.dependOn(&run_e2e.step); - } else e2e_step.dependOn(&b.addFail("macos-e2e needs a Darwin host and target").step); + if (also_gui or platform == .gui) { + const window = gui.make(b, target, optimize, macos_sdk, prebuilt_shaders, a.freetype, test_filters); + for ([_]?*std.Build.Module{ gui_mod, if (platform == .gui) root_mod else null, if (platform == .gui) static_mod else null }) |m| if (m) |gm| window.wire(gm); + cells_test = window.cells_test; + atlas_test = window.atlas_test; + } - const unit_step = b.step("unit-test", "run the C-ABI guard and core unit tests"); - const unit_tests = b.addTest(.{ .root_module = root_mod, .filters = test_filters }); - if (test_nonce) |nonce| unit_tests.root_module.addImport("test_rebuild_nonce", nonce); - test_build.dependOn(&unit_tests.step); - const run_unit = b.addRunArtifact(unit_tests); - 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); - } else { + if (platform == .macos) macos.add(b, .{ + .macos_identity = macos_identity, + .optimize = optimize, + .root_mod = root_mod, + .target = target, + .test_build = test_build, + .test_filters = test_filters, + .test_nonce = test_nonce, + .unit_profile = unit_profile, + }) 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) exe_name = b.fmt("{s}-{s}-{s}", .{ exe_name, @tagName(target.result.os.tag), @tagName(target.result.cpu.arch) }); @@ -1144,29 +228,17 @@ pub fn build(b: *std.Build) void { .root_module = root_mod, }); installHome(b, exe, home_bin); - // docs/typ/command-line.txt: `pardes help --all`, the commands' - // help and the tree's README as this build prints them (never a - // session's), which the reference's "The pardes command" shows; - // main.zig's test fails when it is stale. The terminal's build - // writes it, the window's prints the same. - if (requested_platform == .tui) { - const run_help = b.addRunArtifact(exe); - run_help.addArgs(&.{ "help", "--all" }); - const update = b.addUpdateSourceFiles(); - update.addCopyFileToSource(run_help.captureStdOut(.{}), "docs/typ/command-line.txt"); - builtins_json_step.dependOn(&update.step); - for (doc_renders) |r| if (r) |run| run.step.dependOn(&update.step); - } + if (requested_platform == .tui) docs.commandLine(b, exe, builtins_json_step, doc_renders); // The addons, a step each: the default install is the binaries // alone, and `zig build image pdf` (or `addons`) puts the libraries // where the start scan finds them, <prefix>/lib/pardes/addons (and - // $XDG_DATA_HOME/pardes/addons unless -Dhome-install=false). + // $XDG_DATA_HOME/pardes/addons as home_addons says). const addons_step = b.step("addons", "install the image and pdf addons"); - for ([_]?*std.Build.Step.Compile{ image_addon, pdf_addon }, [_][]const u8{ "image", "pdf" }) |lib, name| { + for ([_]?*std.Build.Step.Compile{ a.image_addon, a.pdf.lib }, [_][]const u8{ "image", "pdf" }) |lib, name| { const step = b.step(name, b.fmt("install the {s} addon, <prefix>/lib/pardes/addons/{s}.so", .{ name, name })); addons_step.dependOn(step); const l = lib orelse { - step.dependOn(no_pdf.?); + step.dependOn(a.pdf.no_pdf.?); continue; }; step.dependOn(&b.addInstallFileWithDir(l.getEmittedBin(), .lib, b.fmt("pardes/addons/{s}.so", .{name})).step); @@ -1191,7 +263,7 @@ pub fn build(b: *std.Build) void { // also how a build for macOS, whose loader has no memfd, could have // image and PDF panes. const static_step = b.step("static", "a pardes with the image and pdf addons in it: the terminal's static (-Dplatform=tui -Dtarget=x86_64-linux-musl), the gui's dynamic (-Dplatform=gui)"); - if (no_pdf) |s| static_step.dependOn(s) else if (static_mod) |m| + if (a.pdf.no_pdf) |s| static_step.dependOn(s) else if (static_mod) |m| static_step.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = exe_name, .linkage = if (platform == .gui) null else static_linkage, .root_module = m }), .{}).step) else static_step.dependOn(&b.addFail("static is the terminal's on musl (-Dplatform=tui -Dtarget=x86_64-linux-musl) or the gui's (-Dplatform=gui)").step); @@ -1209,617 +281,68 @@ pub fn build(b: *std.Build) void { iso_step.dependOn(&run_iso.step); } - const addons: []const *std.Build.Step.Compile = if (pdf_addon) |l| b.allocator.dupe(*std.Build.Step.Compile, &.{ image_addon, l }) catch @panic("OOM") else &.{image_addon}; + const addon_libs: []const *std.Build.Step.Compile = if (a.pdf.lib) |l| b.allocator.dupe(*std.Build.Step.Compile, &.{ a.image_addon, l }) catch @panic("OOM") else &.{a.image_addon}; + // The scripted language server the tests' sessions and the tty cases ask. + const lspmock = tools.program(b, "pardes-lspmock", "test/lspmock.zig", target, optimize, &.{}); process_build.add(b, .{ .exe = exe, - .addons = addons, + .lspmock = lspmock, + .addons = addon_libs, .target = target, .optimize = optimize, - .ghostty_vt = ghostty_vt_for_tests, - .cloud9 = cloud9, + .ghostty_vt = a.ghostty_vt, + .cloud9 = parts.cloud9, .gui = platform == .gui, }); - const image_harness = b.addExecutable(.{ - .name = "pardes-image-harness", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/image_harness.zig"), - .link_libc = true, - }), - }); - if (ghostty_vt_for_tests) |vt| image_harness.root_module.addImport("ghostty-vt", vt); - switch (target.result.os.tag) { - .freebsd, .netbsd, .openbsd => image_harness.root_module.linkSystemLibrary("util", .{}), - else => {}, - } - const run_image_harness = b.addRunArtifact(image_harness); - run_image_harness.addArtifactArg(exe); - run_image_harness.addArtifactArg(image_addon); - run_image_harness.addArg(if (platform == .gui) "gui" else "tui"); - run_image_harness.has_side_effects = true; - b.step("image-harness", "exercise native Kitty/SDL image rendering end to end").dependOn(&run_image_harness.step); - - // Kitty graphics through a terminal pane, end to end: a client in - // the pane's bash (and kitten icat, chafa when installed), a kitty - // terminal outside (tui) or the GPU capture (gui). test/kitty.zig - // is the same protocol at the core. - const kitty_client = b.addExecutable(.{ - .name = "pardes-kitty-client", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/kitty_client.zig"), - .link_libc = true, - }), - }); - const kitty_harness = b.addExecutable(.{ - .name = "pardes-kitty-harness", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/kitty_harness.zig"), - .link_libc = true, - }), - }); - if (ghostty_vt_for_tests) |vt| kitty_harness.root_module.addImport("ghostty-vt", vt); - switch (target.result.os.tag) { - .freebsd, .netbsd, .openbsd => kitty_harness.root_module.linkSystemLibrary("util", .{}), - else => {}, - } - const run_kitty_harness = b.addRunArtifact(kitty_harness); - run_kitty_harness.addArtifactArg(exe); - run_kitty_harness.addArtifactArg(kitty_client); - run_kitty_harness.addArg(if (platform == .gui) "gui" else "tui"); - run_kitty_harness.has_side_effects = true; - b.step("kitty-harness", "kitty graphics through a terminal pane end to end (a client inside, a kitty terminal or the GPU capture outside)").dependOn(&run_kitty_harness.step); - - const pdf_harness_step = b.step("pdf-harness", "exercise continuous PDF rendering, search, and sections navigation end to end"); - if (no_pdf) |s| pdf_harness_step.dependOn(s) else { - const run_pdf_harness = b.addRunArtifact(image_harness); - run_pdf_harness.addArtifactArg(exe); - run_pdf_harness.addArtifactArg(image_addon); - run_pdf_harness.addArg(if (platform == .gui) "gui" else "tui"); - run_pdf_harness.addArg("pdf"); - run_pdf_harness.addArtifactArg(pdf_addon.?); - run_pdf_harness.has_side_effects = true; - pdf_harness_step.dependOn(&run_pdf_harness.step); - } - - const hxdiff = b.addExecutable(.{ - .name = "pardes-hxdiff", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/hxdiff.zig"), - .link_libc = true, - }), - }); - hxdiff.root_module.addImport("pardes", core_module); - const run_hxdiff = b.addRunArtifact(hxdiff); - run_hxdiff.has_side_effects = true; - // Bare, it runs the checked-in suite (test/hxdiff.zig); `-- --parity` - // runs each case in a file pane and a pty pane and compares the two. - run_hxdiff.addPassthruArgs(); - run_hxdiff.setCwd(b.path(".")); - // the new line's indent per file type, against the reference helix - // with its grammars (test/hxcases/hx_indent.py): before the suite, - // whose count stays the last line - const run_hxindent = b.addRunArtifact(hxdiff); - run_hxindent.has_side_effects = true; - run_hxindent.addArgs(&.{ "--strict", "test/hxcases/indent.jsonl", "test/hxcases/indent-goldens.jsonl" }); - run_hxindent.setCwd(b.path(".")); - run_hxdiff.step.dependOn(&run_hxindent.step); - const hxdiff_step = b.step("hxdiff", "compare Helix results (-- --strict cases reference [waivers]; cases alone emits; --parity: a pty pane against a file pane)"); - hxdiff_step.dependOn(&run_hxdiff.step); - - // The same cases on the library (src/lib_editor.zig): test/hxlib.zig - // types them into an editor value and prints its results, which - // hxdiff holds against helix's goldens, or with `-- --parity` - // against the file pane, so the library cannot drift from either. - const hxlib = b.addExecutable(.{ - .name = "pardes-hxlib", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/hxlib.zig"), - .link_libc = true, - }), - }); - hxlib.root_module.addImport("pardes-editor", editorModule(b, null, target, optimize, shell_cfg, .{ - .themes = themes_mod, - .tree_sitter = ts_mod, - .ts_libs = ts_libs.items, - .ts_queries = ts_queries_opts, - .uucode = uucode_mod, - .mvzr = mvzr_mod, - .vaxis = vaxis_mod, - })); - const run_hxlib = b.addRunArtifact(hxlib); - run_hxlib.addArgs(&.{ "test/hxcases/cases.jsonl", "test/hxcases/parity.jsonl" }); - run_hxlib.setCwd(b.path(".")); - run_hxlib.has_side_effects = true; - const run_hxdiff_lib = b.addRunArtifact(hxdiff); - run_hxdiff_lib.has_side_effects = true; - run_hxdiff_lib.addPrefixedFileArg("--actual=", run_hxlib.captureStdOut(.{})); - run_hxdiff_lib.addPassthruArgs(); - run_hxdiff_lib.setCwd(b.path(".")); - b.step("hxlib", "hxdiff's cases on the library, against helix's goldens (-- --parity: against the file pane)").dependOn(&run_hxdiff_lib.step); - - const helix_harness = b.option([]const u8, "helix-harness", "path to the reference hx-harness executable") orelse - b.graph.environ_map.get("HX_HARNESS") orelse "hx-harness"; - const reference = b.addSystemCommand(&.{helix_harness}); - reference.addFileArg(b.path("test/hxcases/cases.jsonl")); - reference.has_side_effects = true; - const reference_results = reference.captureStdOut(.{}); - const live_diff = b.addRunArtifact(hxdiff); - live_diff.addArg("--strict"); - live_diff.addFileArg(b.path("test/hxcases/cases.jsonl")); - live_diff.addFileArg(reference_results); - live_diff.addFileArg(b.path("test/hxcases/waivers.jsonl")); - live_diff.has_side_effects = true; - b.step("hxdiff-live", "compare the editor against a freshly run Helix reference").dependOn(&live_diff.step); - const update_reference = b.addUpdateSourceFiles(); - update_reference.addCopyFileToSource(reference_results, "test/hxcases/goldens.jsonl"); - update_reference.step.dependOn(&live_diff.step); - b.step("hxdiff-update", "replace checked-in Helix goldens after the live comparison passes").dependOn(&update_reference.step); - - // every helix-golf example, one case per step of its walkthrough - const run_hxgolf = b.addRunArtifact(hxdiff); - run_hxgolf.has_side_effects = true; - run_hxgolf.addArgs(&.{ "--strict", "test/hxcases/golf.jsonl", "test/hxcases/golf-goldens.jsonl", "test/hxcases/golf-waivers.jsonl" }); - run_hxgolf.setCwd(b.path(".")); - b.step("hxgolf", "compare the helix-golf examples against their Helix results").dependOn(&run_hxgolf.step); - - const lspbench = b.addExecutable(.{ - .name = "pardes-lspbench", - .root_module = b.createModule(.{ - .target = target, - .optimize = .fast, - .root_source_file = b.path("test/lspbench.zig"), - .link_libc = true, - }), - }); - lspbench.root_module.addImport("pardes", core_module); - const run_lspbench = b.addRunArtifact(lspbench); - run_lspbench.addPassthruArgs(); - run_lspbench.setCwd(b.path(".")); - run_lspbench.has_side_effects = true; - const lspbench_step = b.step("lspbench", "language-backend latency + feature matrix (-- [--json] [--check] [repo-root]), or one query (-- probe <kind> <file> <line>:<col> [arg] [--reps N])"); - lspbench_step.dependOn(&run_lspbench.step); - - const rollback_bench = b.addExecutable(.{ - .name = "pardes-rollback-bench", - .root_module = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("test/rollback_bench.zig"), .link_libc = true }), - }); - rollback_bench.root_module.addImport("pardes", core_module); - const run_rollback_bench = b.addRunArtifact(rollback_bench); - run_rollback_bench.has_side_effects = true; - b.step("rollback-bench", "a replica's rollback copy (walked state, pinned blobs, walk time) for a typical and a big session, and a fork of the big one (-Doptimize=ReleaseFast)").dependOn(&run_rollback_bench.step); - - const replicas = b.addExecutable(.{ - .name = "pardes-replicas", - .root_module = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("test/replicas.zig"), .link_libc = true }), - }); - replicas.root_module.addImport("pardes", core_module); - replicas.root_module.addImport("term", term_mod); - const run_replicas = b.addRunArtifact(replicas); - run_replicas.addPassthruArgs(); - run_replicas.has_side_effects = true; - b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); - - const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); - if (optimize != .fast) { - locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); - } else { - const locations_bench_module = b.createModule(.{ - .target = target, - .optimize = .fast, - .root_source_file = b.path("test/locations_bench.zig"), - .link_libc = true, - }); - locations_bench_module.addImport("pardes", core_module); - const locations_bench = b.addTest(.{ .root_module = locations_bench_module, .filters = &.{"locations benchmark cold and warm formatting"} }); - const run_locations_bench = b.addRunArtifact(locations_bench); - run_locations_bench.has_side_effects = true; - locations_bench_step.dependOn(&run_locations_bench.step); - } - - const perf_optimize: std.lang.Optimize = .fast; - const perf_options = b.addOptions(); - const perf_target = std.Target.Query.fromTarget(&target.result); - perf_options.addOption(PerfBuild, "identity", .{ - .compiler = builtin.zig_version_string, - .target = perf_target.zigTriple(b.allocator) catch @panic("out of memory"), - .cpu = perf_target.serializeCpuAlloc(b.allocator) catch @panic("out of memory"), - .driver_optimize = @tagName(perf_optimize), - .core_optimize = @tagName(optimize), - .c_optimize = @tagName(c_optimize), - .terminal_optimize = @tagName(ghostty_optimize), - .platform = @tagName(platform), - .grammars = @tagName(tree_sitter_grammars), - .mupdf = pdf_addon != null, - .jpx = enable_jpx, - .tracy = tracy != null, - .terminal_simd = ghostty_simd, - .prebuilt_shaders = platform == .gui and prebuilt_shaders, - }); - perf_options.addOptionPath("image_addon", image_addon.getEmittedBin()); - perf_options.addOption(bool, "has_pdf_addon", pdf_addon != null); - if (pdf_addon) |l| perf_options.addOptionPath("pdf_addon", l.getEmittedBin()); - const perf = b.addExecutable(.{ - .name = "pardes-perf", - .root_module = b.createModule(.{ - .target = target, - .optimize = perf_optimize, - .root_source_file = b.path("test/perf.zig"), - .link_libc = true, - }), - }); - perf.root_module.addImport("pardes", core_module); - // --live drives the real binary through a pty (test/e2e_harness.zig). - if (ghostty_vt_for_tests) |vt| perf.root_module.addImport("ghostty-vt", vt); - perf.root_module.addOptions("perf_options", perf_options); - const run_perf = b.addRunArtifact(perf); - run_perf.has_side_effects = true; - run_perf.addPassthruArgs(); - run_perf.setCwd(b.path(".")); - const perf_step = b.step("perf", "gesture latency or bounded terminal stress (-- [--json] [--reps N] [--base old.json] [--terminal-mib N])"); - perf_step.dependOn(&run_perf.step); - // The gate: the 50k-line file's gestures against the baseline this - // build shape recorded, each within 3x of its best. Record one with - // `zig build perf -Dplatform=P [-Doptimize=O] -- --only medium - // --reps 10 --json > test/perf-baseline-P-O.json` (a build that is - // known good). ponytail: the numbers are this machine's; another - // machine records its own. - const perf_gate = b.addRunArtifact(perf); - perf_gate.has_side_effects = true; - perf_gate.setCwd(b.path(".")); - perf_gate.addArgs(&.{ "--only", "medium", "--reps", "10", "--base", b.fmt("test/perf-baseline-{t}-{t}.json", .{ platform, optimize }), "--max-ratio", "3" }); - const perf_gate_step = b.step("perf-gate", "fail when a gesture on the 50k-line file takes over 3x its recorded baseline (test/perf-baseline-<platform>-<optimize>.json)"); - perf_gate_step.dependOn(&perf_gate.step); - const perf_tests = b.addTest(.{ - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/perf.zig"), - .link_libc = true, - }), - .filters = test_filters, - }); - perf_tests.root_module.addOptions("perf_options", perf_options); - - const fs_bench = b.addExecutable(.{ - .name = "pardes-fs-bench", - .root_module = b.createModule(.{ - .target = target, - .optimize = .fast, - .root_source_file = b.path("test/fs_bench.zig"), - .link_libc = true, - }), - }); - fs_bench.root_module.addImport("pardes", core_module); - const run_fs_bench = b.addRunArtifact(fs_bench); - run_fs_bench.has_side_effects = true; - run_fs_bench.addPassthruArgs(); - run_fs_bench.setCwd(b.path(".")); - const fs_bench_step = b.step("fs-bench", "9P filesystem request cost and allocation count (-- [--json] [--reps N])"); - fs_bench_step.dependOn(&run_fs_bench.step); - const fs_bench_test = b.addTest(.{ - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/fs_bench.zig"), - }), - .filters = test_filters, - }); - - const syntax_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/syntax.zig"), - .link_libc = true, - }); - syntax_module.addOptions("pardes_config", opts); - wireCore(syntax_module, .{ .tree_sitter = ts_mod, .ts_libs = ts_libs.items, .ts_queries = ts_queries_opts, .c_heap = c_heap_mod }); - const syntax_runner = b.addExecutable(.{ - .name = "pardes-syntax", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/syntax.zig"), - .link_libc = true, - }), - }); - syntax_runner.root_module.addImport("syntax", syntax_module); - const run_syntax = b.addRunArtifact(syntax_runner); - run_syntax.addPassthruArgs(); - run_syntax.has_side_effects = true; - b.step("syntax", "emit deterministic syntax snapshots (-- --bench: highlighting latency and allocations)").dependOn(&run_syntax.step); - const syntax_test = b.addTest(.{ - .root_module = syntax_module, - .filters = if (test_filters.len == 0) &.{"syntax "} else test_filters, - }); - const run_syntax_test = b.addRunArtifact(syntax_test); - run_syntax_test.has_side_effects = true; - const syntax_test_step = b.step("syntax-test", "test syntax correctness without building the editor"); - syntax_test_step.dependOn(&run_syntax_test.step); - if (testMatch(b, unit_profile, test_filters, syntax_test_step)) |check| check.addArtifactArg(syntax_test); - - // The library as a package that depends on pardes is given it - // (`library`): test/lib's own `zig build test`, over the packages - // this checkout has fetched. - const lib_test = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "test", "--pkg-dir", "../../zig-pkg" }); - lib_test.setCwd(b.path("test/lib")); - lib_test.has_side_effects = true; - const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/lib)"); - lib_test_step.dependOn(&lib_test.step); - - const history = b.addExecutable(.{ - .name = "pardes-history", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/history.zig"), - }), - }); - const run_history = b.addRunArtifact(history); - run_history.addPassthruArgs(); - run_history.has_side_effects = true; - b.step("history", "compare command output and test/build runtime across jj revisions").dependOn(&run_history.step); - - const unit_step = b.step("unit-test", "run native shell and module unit tests"); - // One copy of each codec in the binary (docs/shared-libs.md): the - // linked symbol table, read for the families the build chose against. - // ELF only; it runs with every unit-test, like the perf gate. - if (target.result.ofmt == .elf) { - const libs_check = b.addExecutable(.{ - .name = "pardes-shared-libs-check", - .root_module = b.createModule(.{ - .target = b.graph.host, - .optimize = .debug, - .root_source_file = b.path("tools/shared_libs_check.zig"), - .link_libc = true, - }), - }); - const run_libs_check = b.addRunArtifact(libs_check); - run_libs_check.addArtifactArg(exe); - const libs_check_step = b.step("shared-libs-check", "fail when the binary links a second copy of a codec the build chose one of (docs/shared-libs.md)"); - libs_check_step.dependOn(&run_libs_check.step); - unit_step.dependOn(&run_libs_check.step); - } - // The perf gate runs with every unit-test (a regression like a - // contrast search per grapheme costs 100x, far past the gate). - unit_step.dependOn(perf_gate_step); - unit_step.dependOn(lib_test_step); - const units: Units = .{ .nonce = test_nonce, .build = test_build, .unit = unit_step, .match = testMatch(b, unit_profile, test_filters, unit_step), .profiler = unit_profile, .filters = test_filters }; - // The perf and fs bench programs' own tests: they compile no editor. - _ = units.add(b, perf_tests, null); - _ = units.add(b, fs_bench_test, null); - if (cells_test) |t| _ = units.add(b, t, null); - if (atlas_test) |t| _ = units.add(b, t, null); - const core_test = b.addTest(.{ .root_module = core_lean, .filters = test_filters }); - const run_core_test = b.addRunArtifact(core_test); - run_core_test.has_side_effects = true; - const core_test_step = b.step("core-test", "run core tests without native shell tests, on the core without a terminal (a test that needs one skips)"); - core_test_step.dependOn(&run_core_test.step); - if (testMatch(b, unit_profile, test_filters, core_test_step)) |check| check.addArtifactArg(core_test); - // The terminal module's own tests (src/term/): the emulator without a core. - const run_term_test = units.add(b, b.addTest(.{ .root_module = term_mod, .filters = test_filters }), null); - b.step("term-test", "run the terminal module's own tests (src/term/)").dependOn(&run_term_test.step); - const pane_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/panes.zig"), - .link_libc = true, - }); - pane_module.addImport("pardes", core_module); - // test/terminal.zig reads the emulator behind a core's terminal. - pane_module.addImport("term", term_mod); - pane_module.addImport("plain", plain_mod); - if (ghostty_vt_for_tests) |x| pane_module.addImport("ghostty-vt", x); - pane_module.addImport("pardes_config", core_module.import_table.get("pardes_config").?); - const test_addons = b.addOptions(); - test_addons.addOptionPath("image", image_addon.getEmittedBin()); - test_addons.addOption(bool, "has_pdf", pdf_addon != null); - if (pdf_addon) |l| test_addons.addOptionPath("pdf", l.getEmittedBin()); - pane_module.addOptions("test_addons", test_addons); - const pane_tests = b.addTest(.{ .root_module = pane_module, .filters = test_filters }); - _ = units.add(b, pane_tests, b.step("pane-test", "run pane, output and namespace integration tests")); - - // The behavioural tests (docs/next-tests.md): their module has the - // session alone, so none can reach past what a 9P client sees. - const session_module = b.createModule(.{ - .target = target, + const t = tools.add(b, .{ + .c_optimize = c_optimize, + .core_module = core_module, + .enable_jpx = enable_jpx, + .exe = exe, + .ghostty_optimize = a.ghostty_optimize, + .ghostty_simd = a.ghostty_simd, + .ghostty_vt_for_tests = a.ghostty_vt, + .image_addon = a.image_addon, + .lean = lean_cfg, + .no_pdf = a.pdf.no_pdf, .optimize = optimize, - .root_source_file = b.path("test/session.zig"), - .link_libc = true, - }); - session_module.addImport("pardes", core_module); - // The scripted language server its language words ask - // (Session.initLanguage), as the tty cases do. - const session_options = b.addOptions(); - session_options.addOptionPath("lspmock", b.addExecutable(.{ - .name = "pardes-lspmock", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/lspmock.zig"), - .link_libc = true, - }), - }).getEmittedBin()); - var fake_addon_lib: ?*std.Build.Step.Compile = null; - // The fake addon (addons/fake/fake.c) and three copies of it built - // wrong, which the loader must refuse (test/behaviour/addons.zig). - for ([_]struct { []const u8, []const u8 }{ - .{ "fake_addon", "-DFAKE_PLAIN" }, - .{ "fake_addon_abi", "-DFAKE_ABI=0x20002" }, - .{ "fake_addon_no_export", "-DFAKE_NO_EXPORT" }, - .{ "fake_addon_core_word", "-DFAKE_WORD=\"Save\"" }, - .{ "fake_addon_no_dump", "-DFAKE_NO_DUMP" }, - }) |variant| { - const lib = b.addLibrary(.{ .name = variant[0], .linkage = .dynamic, .root_module = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true }) }); - lib.root_module.addIncludePath(b.path("src/kinds")); - const name_flag = if (std.mem.eql(u8, variant[0], "fake_addon_abi")) "-DFAKE_NAME=\"fakeabi\"" else if (std.mem.eql(u8, variant[0], "fake_addon_core_word")) "-DFAKE_NAME=\"fakeword\"" else "-DFAKE_PLAIN"; - // The header is the whole contract: it compiles clean under every warning. - lib.root_module.addCSourceFile(.{ .file = b.path("addons/fake/fake.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-override-init", variant[1], name_flag } }); - session_options.addOptionPath(variant[0], lib.getEmittedBin()); - if (std.mem.eql(u8, variant[0], "fake_addon")) fake_addon_lib = lib; - } - session_options.addOptionPath("image_addon", image_addon.getEmittedBin()); - session_options.addOption(bool, "has_pdf_addon", pdf_addon != null); - if (pdf_addon) |l| session_options.addOptionPath("pdf_addon", l.getEmittedBin()); - session_module.addOptions("session_options", session_options); - const behaviour_module = b.createModule(.{ + .parts = parts, + .pdf_addon = a.pdf.lib, + .platform = platform, + .prebuilt_shaders = prebuilt_shaders, + .shell_cfg = shell_cfg, .target = target, - .optimize = optimize, - .root_source_file = b.path("test/behaviour.zig"), - .link_libc = true, + .test_filters = test_filters, + .tracy = tracy, + .tree_sitter_grammars = tree_sitter_grammars, + .unit_profile = unit_profile, }); - behaviour_module.addImport("session", session_module); - // The build's options alone (platform), never the core: a test of a - // window's word knows which build it runs in. - behaviour_module.addImport("pardes_config", core_module.import_table.get("pardes_config").?); - const behaviour_tests = b.addTest(.{ .root_module = behaviour_module, .filters = test_filters }); - const behaviour_test_step = b.step("behaviour-test", "run the behavioural tests, through the 9P tree alone (test/behaviour/), and the T1 runner (-- [--seed N]... | --monkey <seeds> | --replay)"); - _ = units.add(b, behaviour_tests, behaviour_test_step); - // An addon's own test: `--addon-test` over the fake (the template) - // and the snake (a shipped example, built but not installed), each - // with its script, compared with what it printed when written. - const addon_test_step = b.step("addon-test", "pardes --addon-test over the fake, snake and pdf addons, against addons/*/*.out, and the Zig addons' own tests"); - const snake_mod = b.createModule(.{ .root_source_file = b.path("addons/snake/snake.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); - const snake_lib = b.addLibrary(.{ .name = "snake", .linkage = .dynamic, .root_module = snake_mod }); - const life_mod = b.createModule(.{ .root_source_file = b.path("addons/life/life.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); - const life_lib = b.addLibrary(.{ .name = "life", .linkage = .dynamic, .root_module = life_mod }); - for ([_]*std.Build.Module{ snake_mod, life_mod, image_mod }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); - // ...and the pdf addon's, which mupdf-check runs too (its script - // opens docs/design.pdf, from the build root). - const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ snake_shader_lib, "addons/snake_shader/snake_shader" }, .{ life_lib, "addons/life/life" }, .{ pdf_addon, "addons/pdf/pdf" } }; - for (libs) |t| if (t[0]) |lib| { - const run_addon_test = b.addRunArtifact(exe); - run_addon_test.setCwd(b.path(".")); - run_addon_test.addArg("--addon-test"); - run_addon_test.addArtifactArg(lib); - run_addon_test.addFileArg(b.path(b.fmt("{s}.script", .{t[1]}))); - const compare = b.addSystemCommand(&.{ "diff", "-u" }); - compare.addFileArg(b.path(b.fmt("{s}.out", .{t[1]}))); - compare.addFileArg(run_addon_test.captureStdOut(.{})); - behaviour_test_step.dependOn(&compare.step); - addon_test_step.dependOn(&compare.step); - if (lib == pdf_addon) mupdf_check.dependOn(&compare.step); - }; - // The T1 runner (test/monkey9p.zig): its modes over an in-process - // session, random 9P requests with the documented rules checked - // after each, random input hunting panics (`-- --monkey <seeds>`), - // and its seeds' tapes replayed (`-- --replay`). Bare, a short - // fixed-seed run of the first, part of behaviour-test. - const t1_runner = b.addExecutable(.{ - .name = "pardes-monkey-session", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/monkey9p.zig"), - .link_libc = true, - }), - }); - t1_runner.root_module.addImport("session", session_module); - const run_t1_runner = b.addRunArtifact(t1_runner); - run_t1_runner.addPassthruArgs(); - run_t1_runner.has_side_effects = true; - if (test_filters.len == 0) behaviour_test_step.dependOn(&run_t1_runner.step); - - // Kitty graphics conformance at the core: what a terminal pane's - // program sends, what it reads back, what ghostty stores and what a - // frame draws (test/kitty.zig). The end-to-end arm, through a real - // pty and the shell's output, is the kitty-harness step. - const kitty_module = b.createModule(.{ - .target = target, + tests.add(b, .{ + .addon_mod = a.addon_mod, + .atlas_test = atlas_test, + .cells_test = cells_test, + .core_lean = core_lean, + .core_module = core_module, + .core_cfg = core_cfg, + .exe = exe, + .ghostty_vt_for_tests = a.ghostty_vt, + .image_addon = a.image_addon, + .lspmock = lspmock, + .mupdf_check = mupdf_check, .optimize = optimize, - .root_source_file = b.path("test/kitty.zig"), - .link_libc = true, - }); - kitty_module.addImport("pardes", core_module); - const kitty_tests = b.addTest(.{ .root_module = kitty_module, .filters = test_filters }); - _ = units.add(b, kitty_tests, b.step("kitty-test", "run the kitty graphics conformance cases for terminal panes")); - - // 9p_io.zig's and fs.zig's tests as roots of their own, on the - // core's imports and C libraries: native transport integration - // stays reachable even when Zig's filter leaves the core's - // anonymous test-import block out. - for ([_]struct { path: []const u8, step: []const u8, about: []const u8, filters: []const []const u8 }{ - .{ .path = "src/9p_io.zig", .step = "9p-io-test", .about = "run native 9P transport and client integration tests", .filters = &.{ "Unix and TCP", "one fetch", "expired sessions", "posts itself" } }, - .{ .path = "src/fs.zig", .step = "fs-unit-test", .about = "run filesystem unit tests", .filters = test_filters }, - }) |t| { - const m = b.createModule(.{ .root_source_file = b.path(t.path), .target = target, .optimize = optimize, .link_libc = true }); - m.link_objects.appendSlice(b.allocator, core_module.link_objects.items) catch @panic("OOM"); - var imports = core_module.import_table.iterator(); - while (imports.next()) |entry| m.addImport(entry.key_ptr.*, entry.value_ptr.*); - b.step(t.step, t.about).dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = t.filters })).step); - } - - const protocol_step = b.step("9p-test", "run freestanding 9P protocol tests"); - const protocol_match = testMatch(b, unit_profile, test_filters, protocol_step); - for ([_]struct { path: []const u8, libc: bool, optimize: ?std.builtin.OptimizeMode = null }{ - .{ .path = "test/history.zig", .libc = false }, - .{ .path = "src/9p.zig", .libc = false }, - .{ .path = "src/fonts.zig", .libc = true }, - .{ .path = "src/c_heap.zig", .libc = false }, - // Its lookup goes wrong only where the optimizer folds it. - .{ .path = "src/c_heap.zig", .libc = false, .optimize = .ReleaseSafe }, - }) |entry| { - const tests = b.addTest(.{ - .root_module = b.createModule(.{ - .target = target, - .optimize = entry.optimize orelse optimize, - .root_source_file = b.path(entry.path), - .link_libc = entry.libc, - }), - .filters = test_filters, - }); - tests.root_module.addImport("cloud9", cloud9); - const run_tests = units.add(b, tests, null); - if (std.mem.eql(u8, entry.path, "src/9p.zig")) { - protocol_step.dependOn(&run_tests.step); - if (protocol_match) |check| check.addArtifactArg(tests); - } - } - - const deck_module = b.createModule(.{ + .parts = parts, + .pdf_addon = a.pdf.lib, + .platform = platform, + .root_mod = root_mod, + .snake_shader_lib = a.snake_shader_lib, .target = target, - .optimize = optimize, - .root_source_file = b.path("test/deck/replay.zig"), + .test_build = test_build, + .test_filters = test_filters, + .test_nonce = test_nonce, + .tools = t, + .unit_profile = unit_profile, }); - deck_module.addImport("deck", b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/gui/deck.zig"), - })); - _ = units.add(b, b.addTest(.{ .root_module = deck_module, .filters = test_filters }), null); - - if (platform == .tui or platform == .gui) { - const run_shell_test = units.add(b, b.addTest(.{ .root_module = root_mod, .filters = test_filters }), null); - // The native shell's tests alone, without the perf gate's - // ReleaseFast build: what a -Dtest-filter iteration wants. - b.step("shell-test", "run the native shell's unit tests (src/main.zig's)").dependOn(&run_shell_test.step); - const profile_test = b.addExecutable(.{ - .name = "pardes-unit-profile-test", - .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("test/unit_profile_test.zig"), - }), - }); - const run_profile_test = b.addRunArtifact(profile_test); - run_profile_test.addArtifactArg(unit_profile); - run_profile_test.has_side_effects = true; - b.step("unit-profile-test", "test profiler timing, failures and deadlines").dependOn(&run_profile_test.step); - if (test_filters.len == 0) { - unit_step.dependOn(&run_profile_test.step); - test_build.dependOn(&unit_profile.step); - test_build.dependOn(&profile_test.step); - } - } } // The test-build programs installed rather than run, for a machine the @@ -1836,41 +359,6 @@ pub fn build(b: *std.Build) void { } } -/// What every unit-test program is wired into: test-build, unit-test, and -/// unit-test's one filter check (`match`: a filter need match in one only). -const Units = struct { - nonce: ?*std.Build.Module, - build: *std.Build.Step, - unit: *std.Build.Step, - match: ?*std.Build.Step.Run, - profiler: *std.Build.Step.Compile, - filters: []const []const u8, - - /// `t` wired in, and run by `own` too, with a filter check of its own, - /// when it has a step of its own. - fn add(u: Units, b: *std.Build, t: *std.Build.Step.Compile, own: ?*std.Build.Step) *std.Build.Step.Run { - if (u.nonce) |nonce| t.root_module.addImport("test_rebuild_nonce", nonce); - u.build.dependOn(&t.step); - const run = b.addRunArtifact(t); - run.has_side_effects = true; - u.unit.dependOn(&run.step); - if (u.match) |check| check.addArtifactArg(t); - const step = own orelse return run; - step.dependOn(&run.step); - if (testMatch(b, u.profiler, u.filters, step)) |check| check.addArtifactArg(t); - return run; - } -}; - -fn testMatch(b: *std.Build, profiler: *std.Build.Step.Compile, filters: []const []const u8, step: *std.Build.Step) ?*std.Build.Step.Run { - if (filters.len == 0) return null; - const check = b.addRunArtifact(profiler); - check.addArgs(&.{ "--check-filter", filters[0] }); - check.has_side_effects = true; - step.dependOn(&check.step); - return check; -} - /// Installs `artifact` in the prefix and, given `home_bin`, copies it there /// too (`install` unlinks first, so a running binary is replaced). fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]const u8) void { @@ -1882,525 +370,3 @@ fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]co copy.has_side_effects = true; b.getInstallStep().dependOn(©.step); } - -/// ghostty's kitty graphics loader (src/terminal/kitty/graphics_image.zig), -/// patched at build time so a fresh fetch keeps it, for what a program in a -/// pane may name with t=f, t=t and t=s (test/kitty.zig): -/// - a path is opened for reading only once it is known to be a regular -/// file: ghostty opens first and checks after, and the open of a FIFO -/// waits for a writer (pardes hung) while a device's open may do -/// something. On Linux an O_PATH probe looks, which opens nothing, and -/// the same inode is reopened through /proc/self/fd; elsewhere a stat by -/// path looks first. -/// - shared memory is opened non-blocking and must be a regular file, so -/// a FIFO in /dev/shm (or a symlink there to one) neither hangs nor maps. -/// - an image may be no larger than a screen's storage -/// (TerminalImages.storage_limit) rather than ghostty's 400 MB, which a -/// program could make pardes read and hold before refusing it. -fn patchGhosttyKitty(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, vt: *std.Build.Module) void { - const rel = "src/terminal/kitty/graphics_image.zig"; - var src = configureRead(b, io, dep.builder.root, rel, 1 << 22) catch @panic("read ghostty's graphics_image.zig"); - const edits = [_][2][]const u8{ - .{ - "const max_size = 400 * 1024 * 1024; // 400MB", - "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit", - }, - .{ - \\ var file = std.Io.Dir.cwd().openFile( - \\ io, - \\ path, - \\ .{}, - \\ ) catch |err| { - , - \\ var file = pardesOpenRegular(io, path) catch |err| { - }, - .{ - " const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), @as(u16, 0));", - \\ // pardes (build.zig): a FIFO there must not hang the open, and - \\ // on Linux nothing but a regular file is opened at all. FreeBSD's - \\ // names are no files, and its shm_open refuses O_NONBLOCK. - \\ if (comptime builtin.target.os.tag == .linux) if (path.len > 0 and path[0] == '/') { - \\ var dev: [std.Io.Dir.max_path_bytes]u8 = undefined; - \\ const full = std.fmt.bufPrint(&dev, "/dev/shm{s}", .{path}) catch return error.InvalidData; - \\ const shm_stat = std.Io.Dir.cwd().statFile(io, full, .{}) catch return error.InvalidData; - \\ if (shm_stat.kind != .file) return error.InvalidData; - \\ }; - \\ const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY, .NONBLOCK = builtin.target.os.tag != .freebsd })), @as(u16, 0)); - }, - .{ - " if (stat.size <= 0) return error.InvalidData;", - " if (stat.kind != .file) return error.InvalidData; // pardes (build.zig)\n if (stat.size <= 0) return error.InvalidData;", - }, - }; - for (edits) |edit| { - if (std.mem.count(u8, src, edit[0]) != 1) std.debug.panic("ghostty's {s} changed at `{s}`: redo its patch in build.zig", .{ rel, edit[0] }); - src = std.mem.replaceOwned(u8, b.allocator, src, edit[0], edit[1]) catch @panic("OOM"); - } - const helper = - \\ - \\/// pardes (build.zig): `path`, opened for reading only once it is known - \\/// to be a regular file. Elsewhere than Linux, a stat by path first. - \\fn pardesOpenRegular(io: std.Io, path: []const u8) !std.Io.File { - \\ if (comptime builtin.target.os.tag != .linux) { - \\ if ((try std.Io.Dir.cwd().statFile(io, path, .{})).kind != .file) return error.NotRegularFile; - \\ return std.Io.Dir.cwd().openFile(io, path, .{}); - \\ } - \\ const probe = try std.Io.Dir.cwd().openFile(io, path, .{ .path_only = true }); - \\ defer probe.close(io); - \\ const stat = try probe.stat(io); - \\ if (stat.kind != .file) return error.NotRegularFile; - \\ var buf: [32]u8 = undefined; - \\ const same = std.fmt.bufPrint(&buf, "/proc/self/fd/{d}", .{probe.handle}) catch unreachable; - \\ return std.Io.Dir.cwd().openFile(io, same, .{}); - \\} - \\ - ; - const files = b.addWriteFiles(); - // The rest of src as it is; fonts are the app's, not the library's. - _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", ".ttf", ".otf" } }); - _ = files.add("terminal/kitty/graphics_image.zig", b.fmt("{s}{s}", .{ src, helper })); - vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig"); -} - -/// A file read while configuring, under a package's root. A dependency's is -/// hash-addressed and never changes under the same pin; this repo's are not -/// tracked one by one, since the configure runs again on every build anyway -/// (findProgram and gitCommit poison its cache). -// ponytail: untracked repo reads; b.dependOnFileContents each one if the configure cache ever stays pure. -fn configureRead(b: *std.Build, io: std.Io, root: std.Build.Cache.Path, sub: []const u8, limit: usize) ![]u8 { - return root.root_dir.handle.readFileAlloc(io, b.pathJoin(&.{ root.subPathOrDot(), sub }), b.allocator, .limited(limit)); -} - -/// `sub` under the install prefix, known only when the build runs. -fn installed(sub: []const u8) std.Build.LazyPath { - return .{ .relative = .{ .base = .install_prefix, .sub_path = sub } }; -} - -fn gitCommit(b: *std.Build) ?[]const u8 { - return command(b, &.{ "git", "rev-parse", "--short=12", "HEAD" }); -} - -/// The jj change git HEAD is in, by its commit (jj 0.46 has no revset for -/// git's HEAD), or null without jj. -fn jjChange(b: *std.Build) ?[]const u8 { - const head = command(b, &.{ "git", "rev-parse", "HEAD" }) orelse return null; - return command(b, &.{ "jj", "log", "-r", head, "--no-graph", "-T", "change_id.short()" }); -} - -/// One line a command prints, or null: HEAD, the change, the clock are not -/// files the configure cache can track, so the cache is poisoned. -fn command(b: *std.Build, argv: []const []const u8) ?[]const u8 { - b.graph.poisonCache(); - var code: u8 = 0; - const out = b.runAllowFail(argv, &code, .ignore) catch return null; - const trimmed = std.mem.trim(u8, out, " \t\r\n"); - return if (trimmed.len == 0) null else trimmed; -} - -const ShellConfig = struct { - tree_sitter_grammars: TreeSitterGrammars, - tracy: bool, - /// null = "the platform's own default": the macOS shell hands the row to - /// its native menu bar, every other shell keeps the acme topbar. - workspace_tag: ?bool, - prebuilt_shaders: bool, - embed_sources: bool, - commit: ?[]const u8, - /// The jj change git HEAD is in, and when this configure ran: the - /// `Build` word's, stamped with the commit (see `stamp_commit`). - change: ?[]const u8, - built: ?[]const u8, - /// The library's editor (src/lib_editor.zig): a text with no pane, so - /// the core is not compiled (src/Editor.zig). - lib: bool = false, -}; - -fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options { - const o = b.addOptions(); - o.addOption(Platform, "platform", platform); - o.addOption(bool, "syntax_highlighting", cfg.tree_sitter_grammars != .disabled); - o.addOption(bool, "syntax_zig_grammar", cfg.tree_sitter_grammars != .disabled); - o.addOption(bool, "syntax_minimal_grammars", cfg.tree_sitter_grammars == .minimal or cfg.tree_sitter_grammars == .full); - o.addOption(bool, "syntax_full_grammars", cfg.tree_sitter_grammars == .full); - o.addOption(bool, "enable_tracy", cfg.tracy); - o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); - o.addOption(bool, "embed_sources", cfg.embed_sources); - o.addOption([]const u8, "version", display_version); - // ...and the commit it was built from, when there is one and the build - // is stamped at all (see `stamp_commit`). Read at configure time. - o.addOption(?[]const u8, "commit", cfg.commit); - o.addOption(?[]const u8, "change", cfg.change); - o.addOption(?[]const u8, "built", cfg.built); - o.addOption([]const u8, "deps", deps_text); - o.addOption(bool, "lib", cfg.lib); - return o; -} - -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" }); - const output = run.addOutputFileArg("libpardes.a"); - for (lib.getCompileDependencies(false), 0..) |dep, i| { - if (dep.kind != .lib) continue; - run.addFileArg(reindexed(b, dep.getEmittedBin(), i)); - } - return output; -} - -fn reindexed(b: *std.Build, archive: std.Build.LazyPath, index: usize) std.Build.LazyPath { - const run = std.Build.Step.Run.create(b, b.fmt("ranlib #{d}", .{index})); - run.addArgs(&.{ "/bin/sh", "-c", "/bin/cp \"$1\" \"$2\" && /usr/bin/ranlib \"$2\"", "_" }); - run.addFileArg(archive); - return run.addOutputFileArg(b.fmt("{d}.a", .{index})); -} - -/// glslc <glsl> -fshader-stage=<vertex|fragment> -o <name>.spv, returned as -/// a LazyPath for @embedFile. The stage is the name's own suffix. -fn compileGlsl(b: *std.Build, glsl: std.Build.LazyPath, name: []const u8) std.Build.LazyPath { - const stage = if (std.mem.endsWith(u8, name, ".vert")) "vertex" else "fragment"; - const cmd = b.addSystemCommand(&.{ "glslc", b.fmt("-fshader-stage={s}", .{stage}) }); - cmd.addFileArg(glsl); - cmd.addArg("-o"); - return cmd.addOutputFileArg(b.fmt("{s}.spv", .{name})); -} - -fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { - var names: std.ArrayList([]const u8) = .empty; - var dir = b.root.root_dir.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); - defer dir.close(io); - var it = dir.iterate(); - while (it.next(io) catch @panic("read vendor/themes")) |e| { - if (!std.mem.endsWith(u8, e.name, ".toml") and !std.mem.endsWith(u8, e.name, ".json")) continue; - names.append(b.allocator, b.dupe(e.name)) catch @panic("OOM"); - } - std.mem.sort([]const u8, names.items, {}, struct { - fn lt(_: void, a: []const u8, c: []const u8) bool { - return std.mem.order(u8, a, c) == .lt; - } - }.lt); - return names.items; -} - -/// The vendored palettes as the `generated_themes` module colors.zig folds -/// into its ring, written by tools/gen_themes.zig. -fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize) *std.Build.Module { - const theme_gen = b.addExecutable(.{ - .name = "pardes-gen-themes", - .root_module = b.createModule(.{ - .target = b.graph.host, - .optimize = .debug, - .root_source_file = b.path("tools/gen_themes.zig"), - }), - }); - const run_theme_gen = b.addRunArtifact(theme_gen); - const themes_out = run_theme_gen.addOutputDirectoryArg("themes"); - for (vendoredThemes(b, io)) |name| run_theme_gen.addFileArg(b.path(b.fmt("vendor/themes/{s}", .{name}))); - return b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = themes_out.path(b, "list.zig"), - }); -} - -const TreeSitter = struct { - mod: ?*std.Build.Module, - queries: ?*std.Build.Step.Options, - libs: std.ArrayList(*std.Build.Step.Compile), -}; - -/// tree-sitter's bindings, and for each grammar of the set its queries (the -/// `ts_queries` options syntax.zig reads) and its parser, a static library. -/// A grammar not fetched yet is asked for and left out: the configure runs -/// again once it is there. -fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, tree_sitter_grammars: TreeSitterGrammars) TreeSitter { - var ts_mod: ?*std.Build.Module = null; - var ts_queries_opts: ?*std.Build.Step.Options = null; - var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty; - if (tree_sitter_grammars != .disabled) { - const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter"); - ts_mod = tree_sitter_mod; - - const ts_queries = b.addOptions(); - inline for (grammar_manifest.all) |g| { - if (tree_sitter_grammars == .full or - (tree_sitter_grammars == .minimal and g.tier != .full) or - (tree_sitter_grammars == .zig and g.tier == .zig)) - grammar: { - const dep = b.lazyDependency(g.dep, .{}) orelse break :grammar; - const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); - // the patterns that colour, filtered here once and not in - // every compile, and the whole query, the filter's test's - const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM"); - ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query); - ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM"))); - // helix's textobject queries, vendored (vendor/queries); a - // grammar without one gets none - const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch ""; - ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects); - // and their indent queries, beside them - const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch ""; - ts_queries.addOption([]const u8, g.name ++ "_indents", indents); - - const lib = b.addLibrary(.{ - .name = "tree-sitter-" ++ g.name, - .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 - // runtime's allocator, which syntax.zig points at a Zig one: - // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use - // ts_malloc, and src/tree_sitter_heap.h for the ones that call - // malloc themselves. - const ts_cflags = [_][]const u8{ - "-fno-sanitize=function", - "-DTREE_SITTER_REUSE_ALLOCATOR", - // From the compiler's working directory, the root - // package's: pardes's own, or the one that depends on it. - "-include", - b.root.joinString(b.allocator, "src/tree_sitter_heap.h") catch @panic("OOM"), - }; - 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)); - ts_libs.append(b.allocator, lib) catch @panic("OOM"); - } - } - ts_queries_opts = ts_queries; - } - return .{ .mod = ts_mod, .queries = ts_queries_opts, .libs = ts_libs }; -} - -/// pardes as a library, all a package that depends on it is given: the -/// `pardes-syntax` module (src/lib_syntax.zig), the grammars, highlighting -/// and themes for a program that draws source text itself. It takes -/// tree-sitter and the grammars of its `tree-sitter` option and no other -/// dependency, so nothing else is fetched (build.zig.zon). test/lib is such -/// a package, which `lib-test` builds. -fn library(b: *std.Build) void { - const target = b.standardTargetOptions(.{}); - const optimize = b.standardOptimizeOption(.{}); - const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full; - var threaded: std.Io.Threaded = .init(b.allocator, .{}); - defer threaded.deinit(); - const io = threaded.io(); - const mod = b.addModule("pardes-syntax", .{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/lib_syntax.zig"), - .link_libc = true, - }); - mod.addOptions("pardes_config", shellOptions(b, .{ - .tree_sitter_grammars = tree_sitter_grammars, - .tracy = false, - .workspace_tag = null, - .prebuilt_shaders = false, - .embed_sources = false, - .commit = null, - .change = null, - .built = null, - }, .tui)); - const ts = treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars); - const themes = generatedThemes(b, io, target, optimize); - wireCore(mod, .{ - .themes = themes, - .tree_sitter = ts.mod, - .ts_libs = ts.libs.items, - .ts_queries = ts.queries, - .c_heap = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") }), - }); - // The editor, `pardes-editor`, to a package that asks for it: uucode, - // mvzr and vaxis (with what its build names) are fetched then and only - // then. Of vaxis it takes the grapheme width, which uucode alone feeds. - if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return; - const uucode = uucodeModule(b, target, optimize) orelse return; - const mvzr = patchedMvzr(b, io, b.lazyDependency("mvzr", .{ .target = target, .optimize = optimize }) orelse return, target, optimize); - const vaxis_dep = b.lazyDependency("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) orelse return; - const width = b.addWriteFiles(); - _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig"); - const vaxis = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"), - .imports = &.{.{ .name = "uucode", .module = uucode }}, - }); - _ = editorModule(b, "pardes-editor", target, optimize, .{ - .tree_sitter_grammars = tree_sitter_grammars, - .tracy = false, - .workspace_tag = null, - .prebuilt_shaders = false, - .embed_sources = false, - .commit = null, - .change = null, - .built = null, - }, .{ .themes = themes, .tree_sitter = ts.mod, .ts_libs = ts.libs.items, .ts_queries = ts.queries, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis }); -} - -fn patchedMvzr(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { - const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr"); - const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n"; - const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len; - const spend = - \\ if (steps_left == 0) { - \\ exhausted = true; - \\ return null; - \\ } - \\ steps_left -= 1; - \\ - ; - const budget = - \\ - \\/// pardes's patch (its build.zig): matchPattern entries left before a - \\/// match gives up, and whether one did. Set by the caller per search. - \\pub threadlocal var steps_left: u64 = std.math.maxInt(u64); - \\pub threadlocal var exhausted: bool = false; - \\ - ; - const budgeted = b.fmt("{s}{s}{s}{s}", .{ src[0..at], spend, src[at..], budget }); - // A group's greedy match never gave back to what follows the group: - // on `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the - // group's own `)` as an alternative, so every group with pattern - // after it takes matchGroup's alternatives branch, which tries each - // alternative's one (greedy) match and gives up. When the rest fails - // after it, try that alternative's shorter matches, longest first - // (docs/mvzr-group-backtrack.md is the report for upstream). - const group_anchor = - \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); - \\ if (next_match) |m2| { - \\ // Whole group matches, and we can use m2.j - \\ return m2; - \\ } else { // Try our next pattern, if any. - \\ - ; - const group_backoff = - \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); - \\ if (next_match) |m2| { - \\ // Whole group matches, and we can use m2.j - \\ return m2; - \\ } else { // Try our next pattern, if any. - \\ // pardes's patch (its build.zig): back the group off. - \\ var e = m1.i; - \\ while (e > i) { - \\ e -= 1; - \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue; - \\ if (shorter.i != e) continue; - \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole; - \\ } - \\ - ; - if (std.mem.count(u8, budgeted, group_anchor) != 1) @panic("mvzr's matchGroup changed: redo its group backtracking in build.zig"); - const backed = std.mem.replaceOwned(u8, b.allocator, budgeted, group_anchor, group_backoff) catch @panic("OOM"); - // `$` is refused anywhere but last, so `h$|zz` was a bad pattern - // while `zz|h$` was fine. An alternative or a group ends at `|` and - // `)`, and the matcher's `.end` ends the alternative it is in, so - // `$` may stand before either (docs/mvzr-group-backtrack.md). - const end_anchor = - \\ '$' => { - \\ if (i + 1 < in.len) { - \\ - ; - const end_before_alt = - \\ '$' => { - \\ // pardes's patch (its build.zig): `$` may end an alternative. - \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') { - \\ - ; - if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig"); - var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); - // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream). - // A class's range ending at `\xff` counted to 256 in a u8, an - // overflow (a panic in a safe build, a runaway loop in a fast one): - // `[\x80-\xff]` in any search took the editor down. - for ([_][3][]const u8{ - .{ "for (c1..c2 + 1) |c_range|", "for (c1..@as(usize, c2) + 1) |c_range|", "1" }, - .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" }, - .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" }, - .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" }, - .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" }, - }) |edit| { - if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]}); - patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM"); - } - return b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize }); -} - -/// uucode with pardes's configuration (uucode_config.zig), which ghostty -/// and vaxis share; null while it is still to be fetched. -fn uucodeModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) ?*std.Build.Module { - const uucode_config = b.path("uucode_config.zig"); - const uucode_tables = (b.lazyDependency("uucode", .{ - .target = target, - .optimize = optimize, - .build_config_path = uucode_config, - }) orelse return null).namedLazyPath("tables.zig"); - return (b.lazyDependency("uucode", .{ - .target = target, - .optimize = optimize, - .build_config_path = uucode_config, - .tables_path = uucode_tables, - }) orelse return null).module("uucode"); -} - -/// The editor as a library (src/lib_editor.zig, docs/next-editor.md): the -/// text pane's own code built with `lib`, so no pane and no core, over -/// tree-sitter, uucode and mvzr, with pardes-syntax in it as `.syntax`. -/// `library` exports it to a package that asks; hxdiff runs its cases on it. -fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cfg: ShellConfig, d: struct { - themes: *std.Build.Module, - tree_sitter: ?*std.Build.Module, - ts_libs: []const *std.Build.Step.Compile, - ts_queries: ?*std.Build.Step.Options, - uucode: *std.Build.Module, - mvzr: *std.Build.Module, - /// vaxis's, or a module of its grapheme width alone (`library`): a - /// cell's width for j and k's goal column. - vaxis: *std.Build.Module, -}) *std.Build.Module { - const options: std.Build.Module.CreateOptions = .{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("src/lib_editor.zig"), - .link_libc = true, - }; - const mod = if (name) |n| b.addModule(n, options) else b.createModule(options); - var lib_cfg = cfg; - lib_cfg.lib = true; - mod.addOptions("pardes_config", shellOptions(b, lib_cfg, .tui)); - wireCore(mod, .{ - .plain = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/plain/plain.zig") }), - .themes = d.themes, - .tree_sitter = d.tree_sitter, - .ts_libs = d.ts_libs, - .ts_queries = d.ts_queries, - .mvzr = d.mvzr, - .uucode = d.uucode, - .vaxis = d.vaxis, - .c_heap = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") }), - }); - return mod; -} - -fn wireCore(m: *std.Build.Module, d: struct { - plain: ?*std.Build.Module = null, - kind: ?*std.Build.Module = null, - themes: ?*std.Build.Module = null, - tree_sitter: ?*std.Build.Module = null, - ts_libs: []const *std.Build.Step.Compile = &.{}, - ts_queries: ?*std.Build.Step.Options = null, - mvzr: ?*std.Build.Module = null, - c_heap: ?*std.Build.Module = null, - vaxis: ?*std.Build.Module = null, - uucode: ?*std.Build.Module = null, - xitdb: ?*std.Build.Module = null, -}) void { - if (d.plain) |x| m.addImport("plain", x); - if (d.kind) |x| m.addImport("pardes_addon", x); - if (d.themes) |x| m.addImport("generated_themes", x); - if (d.tree_sitter) |x| m.addImport("tree-sitter", x); - for (d.ts_libs) |lib| m.linkLibrary(lib); - if (d.ts_queries) |x| m.addOptions("ts_queries", x); - if (d.mvzr) |x| m.addImport("mvzr", x); - if (d.c_heap) |x| m.addImport("c_heap", x); - if (d.vaxis) |x| m.addImport("vaxis", x); - if (d.uucode) |x| m.addImport("uucode", x); - if (d.xitdb) |x| m.addImport("xitdb", x); -} diff --git a/build.zig.zon b/build.zig.zon index 0c2b989f..f9e11447 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -48,9 +48,10 @@ .lazy = true, }, // SDL3 (castholm/SDL zig bindings, its release-3.4.x branch for Zig - // 0.17; david-vanderson's fork, pinned before, has no 0.17 build) — only - // fetched/compiled when `-Dsdl` is set. Lazy so the default vaxis build never touches it. The sdl - // package resolves its own linux deps from its own build.zig.zon. + // 0.17; david-vanderson's fork, pinned before, has no 0.17 build): the + // window's, fetched and compiled only by a build with a window (a bare + // `zig build`, or -Dplatform=gui). The sdl package resolves its own + // linux deps from its own build.zig.zon. .sdl = .{ .url = "git+https://github.com/castholm/SDL#dbcb19aa3583c318556ecae3ecbeb29b102d37c5", .hash = "sdl-0.6.0+3.4.18-SDL--p-gqAGWpnfTLlhs0dgjDtc4P4_CHeNLGY_SX_Fv", diff --git a/build/addons.zig b/build/addons.zig new file mode 100644 index 00000000..195255fd --- /dev/null +++ b/build/addons.zig @@ -0,0 +1,114 @@ +const std = @import("std"); +const mupdf_build = @import("mupdf.zig"); + +/// The GPU addons over sketchbook's `gpu_scene`: the snake (addons/snake_shader) +/// and the frame corpus's translucent veil (test/veil.zig). They are the +/// window build's, as sketchbook is: the terminal's configures without +/// sketchbook beside the checkout, and there their steps say so. +pub fn gpu(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, addon_mod: *std.Build.Module, window: bool) ?*std.Build.Step.Compile { + const snake_shader_step = b.step("snake-shader", "build the optional GPU snake addon into zig-out/lib"); + var snake_shader_lib: ?*std.Build.Step.Compile = null; + const veil_step = b.step("veil", "build the frame corpus's translucent GPU test addon (test/veil.zig) into zig-out/lib"); + if (!window) { + const fail = b.addFail("the GPU addons are the window's: -Dplatform=gui (sketchbook beside this checkout)"); + snake_shader_step.dependOn(&fail.step); + veil_step.dependOn(&fail.step); + } else if (b.dependencyLazy("sketchbook", .{ .@"gpu-only" = true })) |sb| { + const files = b.addWriteFiles(); + for ([_][]const u8{ "vert", "frag", "post.frag" }) |stage| { + const compile = b.addSystemCommand(&.{ "glslc", "-O" }); + compile.addFileArg(b.path(b.fmt("addons/snake_shader/snake.{s}", .{stage}))); + compile.addArg("-o"); + _ = files.addCopyFile(compile.addOutputFileArg(b.fmt("snake.{s}.spv", .{stage})), b.fmt("{s}.spv", .{stage})); + } + const shader_module = b.createModule(.{ .root_source_file = files.add("shaders.zig", "const v align(4) = @embedFile(\"vert.spv\").*;\npub const vert: []const u8 = &v;\nconst f align(4) = @embedFile(\"frag.spv\").*;\npub const frag: []const u8 = &f;\nconst p align(4) = @embedFile(\"post.frag.spv\").*;\npub const post: []const u8 = &p;\n") }); + const module = b.createModule(.{ .root_source_file = b.path("addons/snake_shader/snake_shader.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") }, .{ .name = "shaders", .module = shader_module } } }); + const lib = b.addLibrary(.{ .name = "snake_shader", .linkage = .dynamic, .root_module = module }); + snake_shader_lib = lib; + snake_shader_step.dependOn(&b.addInstallArtifact(lib, .{}).step); + snake_shader_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); + // The frame corpus's translucent addon (test/veil.zig), into lib/ beside the snake. + const veil = b.addLibrary(.{ .name = "veil", .linkage = .dynamic, .root_module = b.createModule(.{ .root_source_file = b.path("test/veil.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") } } }) }); + veil_step.dependOn(&b.addInstallArtifact(veil, .{}).step); + } else |_| {} + return snake_shader_lib; +} + +pub const Pdf = struct { + lib: ?*std.Build.Step.Compile, + /// The same module, for a core with the addons compiled in, which + /// exports nothing there (addon.exportLib). + module: ?*std.Build.Module, + /// What a step that needs the addon depends on when it is not built. + no_pdf: ?*std.Build.Step, +}; + +/// The PDF addon (addons/pdf/pdf.zig over MuPDF through pdf_bridge.c), built +/// and installed as the image addon is: compiled only for a step that +/// needs it (`pdf`, the tests). MuPDF is compiled against the build's +/// FreeType and zlib and links them into the library, which holds its +/// own copy of each beside a window's FreeType (docs/shared-libs.md); so +/// all three are position-independent, and the library exports its +/// `pardes_addon` alone. +pub fn pdf(b: *std.Build, c: struct { + addon_mod: *std.Build.Module, + c_optimize: std.lang.Optimize, + enable_jpx: bool, + freetype: ?*std.Build.Step.Compile, + freetype_dep: ?*std.Build.Dependency, + io: std.Io, + mupdf_check: *std.Build.Step, + mupdf_dep: ?*std.Build.Dependency, + pdf_pointer_bench_step: *std.Build.Step, + pdf_scroll_bench_step: *std.Build.Step, + target: std.Build.ResolvedTarget, +}) Pdf { + var pdf_addon: ?*std.Build.Step.Compile = null; + var pdf_module: ?*std.Build.Module = null; + if (c.mupdf_dep) |md| if (c.freetype_dep) |fd| { + // ...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 = fd.builder.dependency("zlib", .{ .target = c.target, .optimize = c.c_optimize }).artifact("z"); + c.freetype.?.root_module.pic = true; + zlib.root_module.pic = true; + const mupdf = mupdf_build.add(b, c.io, md, .{ + .target = c.target, + .optimize = c.c_optimize, + .jpx = c.enable_jpx, + .freetype = c.freetype.?, + .zlib = zlib, + .pic = true, + }); + // The bridge's header translated here for pdf.zig (Zig 0.17 has no + // @cImport), as the kinds' header is for the core. + const bridge_mod = b.addTranslateC(.{ .root_source_file = b.path("addons/pdf/pdf_bridge.h"), .target = c.target, .optimize = c.c_optimize }).createModule(); + const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.c_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); + mupdf.linkTo(pdf_mod); + pdf_mod.addIncludePath(b.path("addons/pdf")); + pdf_mod.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); + const lib = b.addLibrary(.{ .name = "pdf", .linkage = .dynamic, .root_module = pdf_mod }); + lib.setVersionScript(b.addWriteFiles().add("pdf.map", "{ global: pardes_addon; local: *; };\n")); + pdf_addon = lib; + pdf_module = pdf_mod; + c.mupdf_check.dependOn(mupdf_build.addProbe(b, mupdf, .{ + .target = c.target, + .pdf = b.path("docs/design.pdf"), + })); + }; + // Without it, what needs it says how to have it. + const no_pdf: ?*std.Build.Step = if (pdf_addon == null) &b.addFail("this step needs the pdf addon, over MuPDF: add -Dpdf (it is fetched once, and on from then)").step else null; + if (no_pdf) |s| for ([_]*std.Build.Step{ c.mupdf_check, c.pdf_pointer_bench_step, c.pdf_scroll_bench_step }) |step| step.dependOn(s); + return .{ .lib = pdf_addon, .module = pdf_module, .no_pdf = no_pdf }; +} + +/// The image addon (addons/image/image.zig over stb_image, stb.c), +/// installed by its step and handed by path to every test that opens a +/// picture. +pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile { + const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); + image_mod.addIncludePath(zstbi_dep.path("libs/stbi")); + image_mod.addCSourceFile(.{ .file = b.path("addons/image/stb.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); + const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = image_mod }); + return image_addon; +} diff --git a/build/core.zig b/build/core.zig new file mode 100644 index 00000000..1e2801cf --- /dev/null +++ b/build/core.zig @@ -0,0 +1,620 @@ +const std = @import("std"); +const Platform = @import("../build.zig").Platform; +const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars; +const grammar_manifest = @import("../src/grammar_manifest.zig"); +const addons = @import("addons.zig"); +const patches = @import("patches.zig"); +/// The package manifest, imported UNTYPED on purpose — see the `version` +/// option in `shellOptions` for why that word is load-bearing. +const zon = @import("../build.zig.zon"); +/// Releases are numbered 0.N; the zon holds "0.N.0" because it must be semver, +/// and what a user sees drops that ".0". +pub const display_version = if (std.mem.endsWith(u8, zon.version, ".0") and std.mem.count(u8, zon.version, ".") == 2) + zon.version[0 .. zon.version.len - 2] +else + zon.version; + +/// Every dependency the manifest pins, by its content hash: a grammar, +/// ghostty or the Unicode tables steps a core differently, so they are part +/// of a replica's semantics hash (src/wire.zig `semantics`). +const deps_text = blk: { + var text: []const u8 = ""; + for (@typeInfo(@TypeOf(zon.dependencies)).@"struct".field_names) |name| { + const dep = @field(zon.dependencies, name); + text = text ++ name ++ " " ++ (if (@hasField(@TypeOf(dep), "hash")) dep.hash else "path") ++ "\n"; + } + break :blk text; +}; + +/// A file read while configuring, under a package's root. A dependency's is +/// hash-addressed and never changes under the same pin; this repo's are not +/// tracked one by one, since the configure runs again on every build anyway +/// (build.zig poisons its cache). +// ponytail: untracked repo reads; b.dependOnFileContents each one if the configure cache ever stays pure. +pub fn configureRead(b: *std.Build, io: std.Io, root: std.Build.Cache.Path, sub: []const u8, limit: usize) ![]u8 { + return root.root_dir.handle.readFileAlloc(io, b.pathJoin(&.{ root.subPathOrDot(), sub }), b.allocator, .limited(limit)); +} + +pub fn gitCommit(b: *std.Build) ?[]const u8 { + return command(b, &.{ "git", "rev-parse", "--short=12", "HEAD" }); +} + +/// The jj change git HEAD is in, by its commit (jj 0.46 has no revset for +/// git's HEAD), or null without jj. +pub fn jjChange(b: *std.Build) ?[]const u8 { + const head = command(b, &.{ "git", "rev-parse", "HEAD" }) orelse return null; + return command(b, &.{ "jj", "log", "-r", head, "--no-graph", "-T", "change_id.short()" }); +} + +/// One line a command prints, or null: HEAD, the change, the clock are not +/// files the configure cache can track, so the cache is poisoned. +pub fn command(b: *std.Build, argv: []const []const u8) ?[]const u8 { + b.graph.poisonCache(); + const out = switch (b.runFallible(argv, .{ .stderr_behavior = .ignore })) { + .success => |stdout| stdout, + else => return null, + }; + const trimmed = std.mem.trim(u8, out, " \t\r\n"); + return if (trimmed.len == 0) null else trimmed; +} + +pub const ShellConfig = struct { + tree_sitter_grammars: TreeSitterGrammars, + tracy: bool = false, + /// null = "the platform's own default": the macOS shell hands the row to + /// its native menu bar, every other shell keeps the acme topbar. + workspace_tag: ?bool = null, + prebuilt_shaders: bool = false, + embed_sources: bool = false, + commit: ?[]const u8 = null, + /// The jj change git HEAD is in, and when this configure ran: the + /// `Build` word's, stamped with the commit (see `stamp_commit`). + change: ?[]const u8 = null, + built: ?[]const u8 = null, + /// The library's editor (src/lib_editor.zig): a text with no pane, so + /// the core is not compiled (src/Editor.zig). + lib: bool = false, +}; + +pub fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options { + const o = b.addOptions(); + o.addOption(Platform, "platform", platform); + o.addOption(bool, "syntax_highlighting", cfg.tree_sitter_grammars != .disabled); + o.addOption(bool, "syntax_zig_grammar", cfg.tree_sitter_grammars != .disabled); + o.addOption(bool, "syntax_minimal_grammars", cfg.tree_sitter_grammars == .minimal or cfg.tree_sitter_grammars == .full); + o.addOption(bool, "syntax_full_grammars", cfg.tree_sitter_grammars == .full); + o.addOption(bool, "enable_tracy", cfg.tracy); + o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); + o.addOption(bool, "embed_sources", cfg.embed_sources); + o.addOption([]const u8, "version", display_version); + // ...and the commit it was built from, when there is one and the build + // is stamped at all (see `stamp_commit`). Read at configure time. + o.addOption(?[]const u8, "commit", cfg.commit); + o.addOption(?[]const u8, "change", cfg.change); + o.addOption(?[]const u8, "built", cfg.built); + o.addOption([]const u8, "deps", deps_text); + o.addOption(bool, "lib", cfg.lib); + return o; +} + +fn vendoredThemes(b: *std.Build, io: std.Io) []const []const u8 { + var names: std.ArrayList([]const u8) = .empty; + var dir = b.root.root_dir.handle.openDir(io, "vendor/themes", .{ .iterate = true }) catch @panic("open vendor/themes"); + defer dir.close(io); + var it = dir.iterate(); + while (it.next(io) catch @panic("read vendor/themes")) |e| { + if (!std.mem.endsWith(u8, e.name, ".toml") and !std.mem.endsWith(u8, e.name, ".json")) continue; + names.append(b.allocator, b.graph.dupeString(e.name)) catch @panic("OOM"); + } + std.mem.sort([]const u8, names.items, {}, struct { + fn lt(_: void, a: []const u8, c: []const u8) bool { + return std.mem.order(u8, a, c) == .lt; + } + }.lt); + return names.items; +} + +/// The vendored palettes as the `generated_themes` module colors.zig folds +/// into its ring, written by tools/gen_themes.zig. +pub fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize) *std.Build.Module { + const theme_gen = b.addExecutable(.{ + .name = "pardes-gen-themes", + .root_module = b.createModule(.{ + .target = b.graph.host, + .optimize = .debug, + .root_source_file = b.path("tools/gen_themes.zig"), + }), + }); + const run_theme_gen = b.addRunArtifact(theme_gen); + const themes_out = run_theme_gen.addOutputDirectoryArg("themes"); + for (vendoredThemes(b, io)) |name| run_theme_gen.addFileArg(b.path(b.fmt("vendor/themes/{s}", .{name}))); + return b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = themes_out.path(b, "list.zig"), + }); +} + +pub const TreeSitter = struct { + mod: ?*std.Build.Module, + queries: ?*std.Build.Step.Options, + libs: std.ArrayList(*std.Build.Step.Compile), + + /// tree-sitter, the grammars' parsers and their queries, into `m`. + pub fn wire(ts: TreeSitter, m: *std.Build.Module) void { + if (ts.mod) |x| m.addImport("tree-sitter", x); + for (ts.libs.items) |lib| m.linkLibrary(lib); + if (ts.queries) |x| m.addOptions("ts_queries", x); + } +}; + +/// tree-sitter's bindings, and for each grammar of the set its queries (the +/// `ts_queries` options syntax.zig reads) and its parser, a static library. +/// A grammar not fetched yet is asked for and left out: the configure runs +/// again once it is there. +pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, tree_sitter_grammars: TreeSitterGrammars) TreeSitter { + var ts_mod: ?*std.Build.Module = null; + var ts_queries_opts: ?*std.Build.Step.Options = null; + var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty; + if (tree_sitter_grammars != .disabled) { + const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter"); + ts_mod = tree_sitter_mod; + + const ts_queries = b.addOptions(); + inline for (grammar_manifest.all) |g| { + if (tree_sitter_grammars == .full or + (tree_sitter_grammars == .minimal and g.tier != .full) or + (tree_sitter_grammars == .zig and g.tier == .zig)) + grammar: { + const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar; + const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); + // the patterns that colour, filtered here once and not in + // every compile, and the whole query, the filter's test's + const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM"); + ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query); + ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM"))); + // helix's textobject queries, vendored (vendor/queries); a + // grammar without one gets none + const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch ""; + ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects); + // and their indent queries, beside them + const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch ""; + ts_queries.addOption([]const u8, g.name ++ "_indents", indents); + + const lib = b.addLibrary(.{ + .name = "tree-sitter-" ++ g.name, + .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 + // runtime's allocator, which syntax.zig points at a Zig one: + // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use + // ts_malloc, and src/tree_sitter_heap.h for the ones that call + // malloc themselves. + const ts_cflags = [_][]const u8{ + "-fno-sanitize=function", + "-DTREE_SITTER_REUSE_ALLOCATOR", + // From the compiler's working directory, the root + // package's: pardes's own, or the one that depends on it. + "-include", + b.root.joinString(b.allocator, "src/tree_sitter_heap.h") catch @panic("OOM"), + }; + 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)); + ts_libs.append(b.allocator, lib) catch @panic("OOM"); + } + } + ts_queries_opts = ts_queries; + } + return .{ .mod = ts_mod, .queries = ts_queries_opts, .libs = ts_libs }; +} + +/// uucode with pardes's configuration (uucode_config.zig), which ghostty +/// and vaxis share; null while it is still to be fetched. +pub fn uucodeModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) ?*std.Build.Module { + const uucode_config = b.path("uucode_config.zig"); + const uucode_tables = (b.dependencyLazy("uucode", .{ + .target = target, + .optimize = optimize, + .build_config_path = uucode_config, + }) catch return null).namedLazyPath("tables.zig"); + return (b.dependencyLazy("uucode", .{ + .target = target, + .optimize = optimize, + .build_config_path = uucode_config, + .tables_path = uucode_tables, + }) catch return null).module("uucode"); +} + +/// The editor as a library (src/lib_editor.zig, docs/next-editor.md): the +/// text pane's own code built with `lib`, so no pane and no core, over +/// tree-sitter, uucode and mvzr, with pardes-syntax in it as `.syntax`. +/// `library` exports it to a package that asks; hxdiff runs its cases on it. +pub fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, cfg: ShellConfig, d: struct { + themes: *std.Build.Module, + ts: TreeSitter, + uucode: *std.Build.Module, + mvzr: *std.Build.Module, + /// vaxis's, or a module of its grapheme width alone (`library`): a + /// cell's width for j and k's goal column. + vaxis: *std.Build.Module, +}) *std.Build.Module { + const options: std.Build.Module.CreateOptions = .{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("src/lib_editor.zig"), + .link_libc = true, + }; + const m = if (name) |n| b.addModule(n, options) else b.createModule(options); + var lib_cfg = cfg; + lib_cfg.lib = true; + m.addOptions("pardes_config", shellOptions(b, lib_cfg, .tui)); + m.addImport("plain", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/plain/plain.zig") })); + m.addImport("generated_themes", d.themes); + d.ts.wire(m); + m.addImport("mvzr", d.mvzr); + m.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") })); + m.addImport("vaxis", d.vaxis); + m.addImport("uucode", d.uucode); + return m; +} + +/// What every core module is made of: build.zig makes each once. +pub const Parts = struct { + target: std.Build.ResolvedTarget, + optimize: std.lang.Optimize, + cloud9: *std.Build.Module, + /// -Dtracy's checkout, whose client a core that asks compiles in. + tracy: ?[]const u8, + zstd: *std.Build.Step.Compile, + /// The addons, for a core that has them compiled in (Addon.zig); the + /// pdf one only when it is built (-Dpdf=false leaves it out). + image: *std.Build.Module, + pdf: ?*std.Build.Module, + term: *std.Build.Module, + plain: *std.Build.Module, + /// The kinds' C ABI (src/kinds/pardes_addon.h), translated. + kind: *std.Build.Module, + themes: *std.Build.Module, + ts: TreeSitter, + mvzr: *std.Build.Module, + c_heap: *std.Build.Module, + vaxis: *std.Build.Module, + uucode: *std.Build.Module, + xitdb: *std.Build.Module, + doc_typ: *std.Build.Step.Options, + /// One options module for each value of `terminal`, `isolated` and + /// `on`, shared by every core. + term_on: *std.Build.Step.Options, + term_off: *std.Build.Step.Options, + iso_on: *std.Build.Step.Options, + iso_off: *std.Build.Step.Options, + builtin_on: *std.Build.Step.Options, + builtin_off: *std.Build.Step.Options, +}; + +/// Which core: its root and the few ways the products differ. +pub const Core = struct { + /// src/main.zig for a shell, src/pardes.zig for the core, or a file + /// whose tests run on the core's imports. + root: []const u8, + /// The shell's options (`pardes_config`): this build's, or the window's + /// in the bare build. + config: *std.Build.Step.Options, + /// The terminal module; without it (core-test) a shell boot is a scratch pane. + terminal: bool = true, + /// pardes-isolate's: no host but the terminal. + isolated: bool = false, + /// The addons compiled in and registered at start (Addon.zig): the + /// static step's, and every core off Linux, whose loader has no memfd. + builtin_addons: bool = false, + /// Tracy's client with -Dtracy: the shell's and the core's. + tracy: bool = false, + /// libutil, for forkpty on the BSDs: the shell's. + util: bool = false, +}; + +/// A core module, everything it imports and links named here and nowhere else. +pub fn module(b: *std.Build, p: Parts, c: Core) *std.Build.Module { + const m = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true }); + m.addImport("cloud9", p.cloud9); + // forkpty: in libc proper on glibc>=2.34 and darwin; the BSDs keep it in libutil + if (c.util and (p.target.result.os.tag == .freebsd or p.target.result.os.tag == .netbsd or p.target.result.os.tag == .openbsd)) + m.linkSystemLibrary("util", .{}); + if (c.tracy) if (p.tracy) |tracy_path| { + m.addIncludePath(.{ .cwd_relative = tracy_path }); + m.addCSourceFile(.{ + .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) }, + .flags = &.{ + "-DTRACY_ENABLE=1", + "-DTRACY_NO_SAMPLING", + "-DTRACY_NO_CALLSTACK", + "-DTRACY_NO_SYSTEM_TRACING", + "-DTRACY_NO_CRASH_HANDLER", + "-DTRACY_NO_CODE_TRANSFER", + "-fno-sanitize=undefined", + }, + }); + m.link_libcpp = true; + }; + if (c.builtin_addons) if (p.pdf) |pdf| m.addImport("pdf_addon", pdf); + m.linkLibrary(p.zstd); + if (c.builtin_addons) m.addImport("image_addon", p.image); + if (c.terminal) { + m.addImport("term", p.term); + m.addOptions("term_options", p.term_on); + } else m.addOptions("term_options", p.term_off); + m.addImport("plain", p.plain); + m.addImport("pardes_addon", p.kind); + m.addImport("generated_themes", p.themes); + p.ts.wire(m); + m.addImport("mvzr", p.mvzr); + m.addImport("c_heap", p.c_heap); + m.addImport("vaxis", p.vaxis); + m.addImport("uucode", p.uucode); + m.addImport("xitdb", p.xitdb); + // config.zig's test checks the words and keys docs/typ names exist. + m.addOptions("doc_typ", p.doc_typ); + m.addOptions("pardes_config", c.config); + m.addOptions("pardes_isolation", if (c.isolated) p.iso_on else p.iso_off); + m.addOptions("builtin_addons", if (c.builtin_addons) p.builtin_on else p.builtin_off); + return m; +} + +/// What `assemble` makes besides the parts: the shells' options, the +/// addons, and the terminal's pieces the tests and harnesses name. +pub const Assembly = struct { + parts: Parts, + /// The shell's options (`pardes_config`), and the window's in the bare build. + opts: *std.Build.Step.Options, + gui_opts: ?*std.Build.Step.Options, + /// What an addon in Zig imports (src/kinds/addon.zig). + addon_mod: *std.Build.Module, + snake_shader_lib: ?*std.Build.Step.Compile, + pdf: addons.Pdf, + image_addon: *std.Build.Step.Compile, + /// The window's FreeType, which MuPDF is built against too. + freetype: ?*std.Build.Step.Compile, + /// ghostty's emulator, null while it is still to be fetched. + ghostty_vt: ?*std.Build.Module, + ghostty_optimize: std.lang.Optimize, + ghostty_simd: bool, +}; + +/// Every core's parts, the shells' options and the addons, made once and +/// in this order (the configuration numbers what it generates by it): the +/// one-round lazy fetch, tree-sitter and the themes, the patched packages, +/// zstd, the terminal, and the options modules the cores choose between. +pub fn assemble(b: *std.Build, c: struct { + target: std.Build.ResolvedTarget, + optimize: std.lang.Optimize, + c_optimize: std.lang.Optimize, + tree_sitter_grammars: TreeSitterGrammars, + tracy: ?[]const u8, + shell_cfg: ShellConfig, + platform: Platform, + also_gui: bool, + pdf: bool, + enable_jpx: bool, + doc_typ: *std.Build.Step.Options, + mupdf_check: *std.Build.Step, + pdf_pointer_bench_step: *std.Build.Step, + pdf_scroll_bench_step: *std.Build.Step, +}) Assembly { + const target = c.target; + const optimize = c.optimize; + const c_optimize = c.c_optimize; + // build-time IO: slurps the grammars' highlights.scm queries, reads + // vendor/themes to find the theme sources, and walks MuPDF's tree + var threaded: std.Io.Threaded = .init(b.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + // The manifest marks every dependency lazy but tree-sitter's runtime, so + // that a package depending on pardes fetches what `library` takes and + // nothing else. pardes takes these whatever it builds: the missing ones + // are asked for here in one round, the grammars with them, where each + // `b.dependency` below would end the configure to fetch its own alone. + const ts = treeSitter(b, io, target, c_optimize, c.tree_sitter_grammars); + inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| { + // A dependency by path (none of these today) has no hash and is always there. + const dep = @field(zon.dependencies, name); + if (@hasField(@TypeOf(dep), "hash")) if (!std.Build.package_map.get(dep.hash).?.available) { + _ = b.dependencyLazy(name, .{}) catch {}; + }; + } + const cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9"); + + const themes_mod = generatedThemes(b, io, target, optimize); + + const opts = shellOptions(b, c.shell_cfg, c.platform); + const gui_opts: ?*std.Build.Step.Options = if (c.also_gui) shellOptions(b, c.shell_cfg, .gui) else null; + + const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize }); + const zstbi_mod = zstbi_dep.module("root"); + // vaxis, ghostty, mvzr and zstbi are patched as they are fetched + // (build/patches.zig), by one tool made once. + const patch = patches.tool(b); + // mvzr with a step budget, its group backtracking and `$` before `|`. + const mvzr_mod = patches.mvzr(b, patch, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize); + + // The C heap every C library with an allocator hook is handed: the core's + // tree-sitter and fonts, and pdf.zig's MuPDF, which is a module of its own. + const c_heap_mod = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("src/c_heap.zig"), + }); + + // MuPDF and FreeType, lazy (build.zig's `pdf` option has why). + const mupdf_dep = if (c.pdf) b.dependencyLazy("mupdf", .{}) catch null else null; + // One FreeType in a binary: the gui's glyph atlas links it and MuPDF is + // built against it (see build/mupdf.zig). At c_optimize with the rest of the + // vendored C, since MuPDF rasterizes a PDF's text through it. + const freetype_dep = if (c.pdf or c.also_gui or c.platform == .gui) b.dependencyLazy("freetype", .{ + .target = target, + .optimize = c_optimize, + .@"enable-libpng" = false, + }) catch null else null; + const freetype = if (freetype_dep) |d| d.artifact("freetype") else null; + + // The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's + // records are the header's, never a mirror of it. + const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); + // ...and what an addon in Zig imports over it (src/kinds/addon.zig). + const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); + const snake_shader_lib = addons.gpu(b, target, optimize, addon_mod, c.also_gui or c.platform == .gui); + const pdf_built = addons.pdf(b, .{ + .addon_mod = addon_mod, + .c_optimize = c_optimize, + .enable_jpx = c.enable_jpx, + .freetype = freetype, + .freetype_dep = freetype_dep, + .io = io, + .mupdf_check = c.mupdf_check, + .mupdf_dep = mupdf_dep, + .pdf_pointer_bench_step = c.pdf_pointer_bench_step, + .pdf_scroll_bench_step = c.pdf_scroll_bench_step, + .target = target, + }); + + const uucode_mod = uucodeModule(b, target, optimize).?; + + const vaxis_dep = b.dependency("vaxis", .{ + .target = target, + .optimize = optimize, + .external_uucode = true, + }); + const vaxis_mod = vaxis_dep.module("vaxis"); + patches.vaxis(b, patch, vaxis_dep, vaxis_mod); + + var ghostty_vt_for_tests: ?*std.Build.Module = null; + 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.dependencyLazy("ghostty", .{ .target = target, .optimize = ghostty_optimize, .simd = ghostty_simd, .@"app-runtime" = .none, .@"emit-xcframework" = false }) catch null; + if (ghostty_dep) |dep| { + const ghostty_vt = dep.module("ghostty-vt"); + ghostty_vt_for_tests = ghostty_vt; + ghostty_vt.addImport("uucode", uucode_mod); + patches.ghosttyKitty(b, patch, dep, ghostty_vt); + } + // override uucode on vaxis LAST so it wins over ghostty's build() wiring. + vaxis_mod.addImport("uucode", uucode_mod); + + // One PNG decoder (docs/shared-libs.md): ghostty's, wuffs, which + // ghostty-vt links for kitty graphics whatever pardes does; a terminal's + // PNG is decoded through it (TerminalImages.zig), and of zstbi only its + // resize is left, for the PNG's downscale: stb_image and its writer + // (with the deflate it carries) are patched out (build/patches.zig). + // The image addon has its own (addons/image). + const wuffs_mod: ?*std.Build.Module = if (ghostty_vt_for_tests) |vt| vt.import_table.get("wuffs") else null; + patches.zstbi(b, patch, zstbi_dep, zstbi_mod); + + // 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 + // compressor and decompressor alone, single-threaded and without its + // x86 assembly, each context made with ZSTD_customMem over c_heap; of + // 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. + const zstd = zstd: { + const dep = b.dependency("zstd", .{}); + const lib = b.addLibrary(.{ + .name = "zstd", + .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }), + .linkage = .static, + }); + lib.root_module.addCSourceFiles(.{ + .root = dep.path("lib"), + .files = &.{ + "common/debug.c", "common/entropy_common.c", "common/error_private.c", + "common/fse_decompress.c", "common/pool.c", "common/threading.c", + "common/xxhash.c", "common/zstd_common.c", "compress/fse_compress.c", + "compress/hist.c", "compress/huf_compress.c", "compress/zstd_compress.c", + "compress/zstd_compress_literals.c", "compress/zstd_compress_sequences.c", "compress/zstd_compress_superblock.c", + "compress/zstd_double_fast.c", "compress/zstd_fast.c", "compress/zstd_lazy.c", + "compress/zstd_ldm.c", "compress/zstd_opt.c", "compress/zstd_preSplit.c", + "decompress/huf_decompress.c", "decompress/zstd_ddict.c", "decompress/zstd_decompress.c", + "decompress/zstd_decompress_block.c", + }, + .flags = &.{ + "-DXXH_NAMESPACE=ZSTD_", "-DZSTD_DISABLE_ASM", "-DZSTD_LEGACY_SUPPORT=0", + "-DDEBUGLEVEL=0", "-DZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR", + "-DZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR", "-DZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR", + }, + }); + lib.link_function_sections = true; + lib.link_data_sections = true; + break :zstd lib; + }; + + // xitdb keeps what pardes writes to disk (src/Db.zig): pure Zig, no C + // library and no allocator hook of its own (it takes Zig allocators). + const xitdb_mod = b.dependency("xitdb", .{ .target = target, .optimize = optimize }).module("xitdb"); + + const image_addon = addons.image(b, target, c_optimize, addon_mod, zstbi_dep); + // The records the core and the terminal both name (src/plain/plain.zig). + const plain_mod = b.createModule(.{ .root_source_file = b.path("src/plain/plain.zig"), .target = target, .optimize = optimize }); + // The terminal, a module of its own (src/term/term.zig): the emulator and + // what it brings are its, and every core but core-test's is given it. + const term_mod = b.createModule(.{ .root_source_file = b.path("src/term/term.zig"), .target = target, .optimize = optimize, .link_libc = true }); + term_mod.addImport("plain", plain_mod); + if (ghostty_vt_for_tests) |x| term_mod.addImport("ghostty-vt", x); + if (wuffs_mod) |x| term_mod.addImport("wuffs", x); + term_mod.addImport("zstbi", zstbi_mod); + + // One options module for each value a core chooses (`module`). + const term_on = b.addOptions(); + term_on.addOption(bool, "terminal", true); + const term_off = b.addOptions(); + term_off.addOption(bool, "terminal", false); + const iso_off = b.addOptions(); + iso_off.addOption(bool, "isolated", false); + const iso_on = b.addOptions(); + iso_on.addOption(bool, "isolated", true); + const builtin_off = b.addOptions(); + builtin_off.addOption(bool, "on", false); + const builtin_on = b.addOptions(); + builtin_on.addOption(bool, "on", true); + // ...the pdf one only when it is built (-Dpdf=false leaves it out). + builtin_on.addOption(bool, "pdf", pdf_built.lib != null); + return .{ + .parts = .{ + .target = target, + .optimize = optimize, + .cloud9 = cloud9, + .tracy = c.tracy, + .zstd = zstd, + .image = image_addon.root_module, + .pdf = pdf_built.module, + .term = term_mod, + .plain = plain_mod, + .kind = kind_mod, + .themes = themes_mod, + .ts = ts, + .mvzr = mvzr_mod, + .c_heap = c_heap_mod, + .vaxis = vaxis_mod, + .uucode = uucode_mod, + .xitdb = xitdb_mod, + .doc_typ = c.doc_typ, + .term_on = term_on, + .term_off = term_off, + .iso_on = iso_on, + .iso_off = iso_off, + .builtin_on = builtin_on, + .builtin_off = builtin_off, + }, + .opts = opts, + .gui_opts = gui_opts, + .addon_mod = addon_mod, + .snake_shader_lib = snake_shader_lib, + .pdf = pdf_built, + .image_addon = image_addon, + .freetype = freetype, + .ghostty_vt = ghostty_vt_for_tests, + .ghostty_optimize = ghostty_optimize, + .ghostty_simd = ghostty_simd, + }; +} diff --git a/build/docs.zig b/build/docs.zig new file mode 100644 index 00000000..b698da02 --- /dev/null +++ b/build/docs.zig @@ -0,0 +1,79 @@ +const std = @import("std"); +const Platform = @import("../build.zig").Platform; + +/// The docs (docs/typ, docs/site): each output is one typst run, and each +/// reads docs/typ/builtins-*.json; `builtins-json` refreshes this build's from the +/// registry first (the tool is wired below, once the core module is). +pub fn add(b: *std.Build) [3]*std.Build.Step.Run { + // Looked for when a render runs: without typst on PATH, that step + // fails ("program not found") and nothing else does. + const typst = b.findProgramLazy(.{ .names = &.{"typst"} }); + const cheatsheet_step = b.step("cheatsheet", "render docs/typ/cheatsheet-a4.typ to <prefix>/share/doc/pardes/cheatsheet.pdf (needs typst)"); + const book_step = b.step("book", "render docs/typ/book.typ to <prefix>/share/doc/pardes/pardes.pdf (needs typst)"); + // The website: one Typst bundle run writes every page, the stylesheet, + // the fonts and the media (docs/site/site.typ). + const site_step = b.step("site", "render the docs website to <prefix>/share/doc/pardes/site (needs typst)"); + // They read all of docs/typ, docs/site and the tutor, so they always + // run rather than track every file. + const sheet = std.Build.Step.Run.create(b, "run typst (cheatsheet)"); + sheet.addFileArg(typst); + sheet.addArgs(&.{ "compile", "--ignore-system-fonts" }); + sheet.addFileArg(b.path("docs/typ/cheatsheet-a4.typ")); + sheet.has_side_effects = true; + cheatsheet_step.dependOn(&b.addInstallFile(sheet.addOutputFileArg("cheatsheet.pdf"), "share/doc/pardes/cheatsheet.pdf").step); + const book = std.Build.Step.Run.create(b, "run typst (book)"); + book.addFileArg(typst); + book.addArgs(&.{ "compile", "--ignore-system-fonts", "--root", "." }); + book.setCwd(b.path(".")); + book.addFileArg(b.path("docs/typ/book.typ")); + book.has_side_effects = true; + book_step.dependOn(&b.addInstallFile(book.addOutputFileArg("pardes.pdf"), "share/doc/pardes/pardes.pdf").step); + const site = std.Build.Step.Run.create(b, "run typst (site)"); + site.addFileArg(typst); + site.addArgs(&.{ "compile", "--format", "bundle", "--features", "bundle,html", "--root", "." }); + site.setCwd(b.path(".")); + site.addFileArg(b.path("docs/site/site.typ")); + const site_dir = site.addOutputDirectoryArg("site"); + site.has_side_effects = true; + site_step.dependOn(&b.addInstallDirectory(.{ .source_dir = site_dir, .install_dir = .prefix, .install_subdir = "share/doc/pardes/site" }).step); + return .{ sheet, book, site }; +} + +/// docs/typ/builtins-<platform>.json: every builtin, from the registry and the Help +/// rows (src/builtins_json.zig), rewritten in the source tree so a plain +/// `typst compile` reads it too; a unit test fails when it is stale. +/// A terminal build writes builtins-tui.json and a window build +/// builtins-gui.json; style.typ merges the two into one glossary. +pub fn builtinsJson(b: *std.Build, requested_platform: ?Platform, platform: Platform, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, core_module: *std.Build.Module, doc_renders: [3]*std.Build.Step.Run) *std.Build.Step { + const builtins_json_step = b.step("builtins-json", "rewrite docs/typ/builtins-<tui|gui>.json from the builtin registry, and with tui docs/typ/command-line.txt from pardes help --all (-Dplatform=tui or gui)"); + if (requested_platform == .tui or requested_platform == .gui) { + const gen = b.addExecutable(.{ .name = "pardes-gen-builtins-json", .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("tools/gen_builtins_json.zig"), + .imports = &.{.{ .name = "pardes", .module = core_module }}, + }) }); + const run_gen = b.addRunArtifact(gen); + const json = run_gen.addOutputFileArg("builtins.json"); + for ([_][]const u8{ "image/image.zig", "pdf/pdf.zig" }) |f| run_gen.addFileArg(b.path(b.fmt("addons/{s}", .{f}))); + const update = b.addUpdateSourceFiles(); + update.addCopyFileToSource(json, b.fmt("docs/typ/builtins-{s}.json", .{@tagName(platform)})); + builtins_json_step.dependOn(&update.step); + for (doc_renders) |run| run.step.dependOn(&update.step); + } else builtins_json_step.dependOn(&b.addFail("builtins-json writes one build's list: pass -Dplatform=tui or -Dplatform=gui").step); + return builtins_json_step; +} + +/// docs/typ/command-line.txt: `pardes help --all`, the commands' +/// help and the tree's README as this build prints them (never a +/// session's), which the reference's "The pardes command" shows; +/// main.zig's test fails when it is stale. The terminal's build +/// writes it, the window's prints the same. +pub fn commandLine(b: *std.Build, exe: *std.Build.Step.Compile, builtins_json_step: *std.Build.Step, doc_renders: [3]*std.Build.Step.Run) void { + const run_help = b.addRunArtifact(exe); + run_help.addArgs(&.{ "help", "--all" }); + const update = b.addUpdateSourceFiles(); + update.addCopyFileToSource(run_help.captureStdOut(.{}), "docs/typ/command-line.txt"); + builtins_json_step.dependOn(&update.step); + for (doc_renders) |run| run.step.dependOn(&update.step); +} diff --git a/build/gui.zig b/build/gui.zig new file mode 100644 index 00000000..24aa6277 --- /dev/null +++ b/build/gui.zig @@ -0,0 +1,205 @@ +const std = @import("std"); + +const gui_shaders = [_][]const u8{ + "ui.vert", + "ui.frag", + "decor.frag", + "overlay.vert", + "overlay.frag", + "image.vert", + "image.frag", +}; + +/// The window's pieces, made once and wired into each of its shells (the +/// bare build's pardes-gui; -Dplatform=gui's pardes-gui and its static): +/// SDL, gui.zig's `c`, sketchbook's renderer and glyph atlas, FreeType and +/// HarfBuzz; and the renderer's and atlas's own tests, for unit-test. A +/// piece whose lazy package is not fetched yet is null. +pub const Window = struct { + sdl: ?Sdl = null, + sketchbook: ?*std.Build.Dependency, + freetype: ?*std.Build.Step.Compile, + harfbuzz: ?HarfBuzz = null, + darwin: bool, + /// sketchbook's Cells.zig's own tests (the instance ABI). + cells_test: ?*std.Build.Step.Compile = null, + /// sketchbook's Atlas.zig's own tests. + atlas_test: ?*std.Build.Step.Compile = null, + + const Sdl = struct { + lib: *std.Build.Step.Compile, + include: std.Build.LazyPath, + gui_c: *std.Build.Module, + /// sketchbook's renderer by file, over gui_c: sketch_gpu, + /// font_atlas, gpu_cells, gpu_present, gpu_scene. + renderer: ?[5]std.Build.Module.Import = null, + /// The macOS trackpad adapter, compiled apart. + trackpad: ?std.Build.LazyPath = null, + }; + const HarfBuzz = struct { lib: *std.Build.Step.Compile, include: std.Build.LazyPath }; + + /// `gm`, a window shell, given the pieces, in the order it links them. + pub fn wire(w: Window, gm: *std.Build.Module) void { + const b = gm.owner; + if (w.sdl) |sdl| { + gm.linkLibrary(sdl.lib); + gm.addIncludePath(sdl.include); + gm.addImport("gui_c", sdl.gui_c); + if (sdl.renderer) |imports| for (imports) |i| gm.addImport(i.name, i.module); + if (sdl.trackpad) |object| { + gm.addObjectFile(object); + gm.linkFramework("Cocoa", .{}); + } + } + const ft = w.freetype orelse return; + gm.linkLibrary(ft); + if (w.harfbuzz) |hb| { + gm.linkLibrary(hb.lib); + gm.addIncludePath(hb.include); + } + if (w.darwin) + gm.addRPath(.{ .cwd_relative = "/usr/local/lib" }); + if (w.sketchbook) |sb| gm.addCSourceFile(.{ .file = sb.path("vendor/font.c") }); + // the embedded UI font: provided as a build import since assets/ lives + // outside the src/ module root (@embedFile can't escape it) + gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ + .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf"), + }); + } +}; + +pub fn make(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, macos_sdk: ?[]const u8, prebuilt_shaders: bool, freetype: ?*std.Build.Step.Compile, test_filters: []const []const u8) Window { + const sketchbook = b.lazyDependency("sketchbook", .{ .@"gpu-only" = true }); + var w: Window = .{ .sketchbook = sketchbook, .freetype = freetype, .darwin = target.result.os.tag.isDarwin() }; + // SDL's build asks a cross build for macOS for the SDK's paths. + const sdk: ?std.Build.LazyPath = if (macos_sdk) |p| .{ .cwd_relative = p } else null; + const sdl_dep = b.lazyDependency("sdl", .{ .target = target, .optimize = optimize, .sanitize_c = .off, .preferred_linkage = .static, .system_include_path = if (sdk) |p| p.path(b, "usr/include") else null, .system_framework_path = if (sdk) |p| p.path(b, "System/Library/Frameworks") else null, .library_path = if (sdk) |p| p.path(b, "usr/lib") else null }); + if (sdl_dep) |dep| { + const sdl_lib = dep.artifact("SDL3"); + // SDL's own stb_image (SDL_stb.c, for SDL_LoadPNG and a camera's + // MJPEG, neither of which pardes calls) is a second PNG and JPEG + // decoder beside the build's: off (docs/shared-libs.md). + sdl_lib.root_module.addCMacro("SDL_DISABLE_STB", "1"); + // gui.zig's `c`: SDL and the font shim, which @cImport gave it before Zig 0.17. + const header = b.addWriteFiles().add("gui_c.h", + \\#define SDL_DISABLE_OLD_NAMES 1 + \\#include <SDL3/SDL.h> + \\#include "font.h" + \\#include "macos_trackpad.h" + \\ + ); + const gui_c = b.addTranslateC(.{ .root_source_file = header, .target = target, .optimize = optimize }); + gui_c.addIncludePath(dep.path("include")); + gui_c.addIncludePath(b.path("src/gui")); + const gui_c_mod = gui_c.createModule(); + var sdl: Window.Sdl = .{ .lib = sdl_lib, .include = dep.path("include"), .gui_c = gui_c_mod }; + if (sketchbook) |sb| { + const gpu = b.createModule(.{ .root_source_file = sb.path("dev/draw/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } }); + // The glyph atlas (dev/text/Atlas.zig) over the font shim + // (vendor/font.{c,h}), compiled below against pardes's + // FreeType and HarfBuzz. + const atlas_mod = b.createModule(.{ .root_source_file = sb.path("dev/text/Atlas.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} }); + // pardes's renderer, moved to sketchbook (dev/draw/), compiled + // against pardes's SDL; its tests run with unit-test. Its + // SPIR-V is sketchbook's GLSL through glslc, or the prebuilt + // copies with -Dprebuilt-shaders. + const cells_mod = b.createModule(.{ .root_source_file = sb.path("dev/draw/Cells.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }); + for (gui_shaders) |name| cells_mod.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{ + .root_source_file = if (prebuilt_shaders) + sb.path(b.fmt("dev/draw/shaders/prebuilt/{s}.spv", .{name})) + else + compileGlsl(b, sb.path(b.fmt("dev/draw/shaders/{s}.glsl", .{name})), name), + }); + const present = b.createModule(.{ .root_source_file = sb.path("dev/draw/Present.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "gpu_cells", .module = cells_mod } } }); + sdl.renderer = .{ .{ .name = "sketch_gpu", .module = gpu }, .{ .name = "font_atlas", .module = atlas_mod }, .{ .name = "gpu_cells", .module = cells_mod }, .{ .name = "gpu_present", .module = present }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") } }; + w.cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("dev/draw/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }), .filters = test_filters }); + gui_c.addIncludePath(sb.path("vendor")); + } + if (target.result.os.tag == .macos) { + const arch = if (target.result.cpu.arch == .aarch64) "arm64" else @tagName(target.result.cpu.arch); + const shim = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O2", "-target", b.fmt("{s}-apple-macos13.0", .{arch}), "-I" }); + shim.addDirectoryArg(dep.path("include")); + shim.addArg("-c"); + shim.addFileArg(b.path("src/gui/macos_trackpad.m")); + // Header changes invalidate the independently compiled adapter. + shim.addFileInput(b.path("src/gui/macos_trackpad.h")); + shim.addArg("-o"); + sdl.trackpad = shim.addOutputFileArg("macos_trackpad.o"); + } + w.sdl = sdl; + } + const ft = freetype orelse return w; + // 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, + // plus its allocator: gui.zig's ui_malloc and friends, over a Zig + // allocator, as FreeType's is. + if (b.lazyDependency("harfbuzz", .{})) |upstream| { + const harfbuzz = b.addLibrary(.{ + .name = "harfbuzz", + .linkage = .static, + .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .link_libc = true, + .link_libcpp = true, + }), + }); + harfbuzz.root_module.linkLibrary(ft); + harfbuzz.root_module.addIncludePath(upstream.path("src")); + harfbuzz.root_module.addCSourceFile(.{ + .file = upstream.path("src/harfbuzz.cc"), + .flags = &.{ + "-DHAVE_STDBOOL_H", + "-DHAVE_UNISTD_H", + "-DHAVE_SYS_MMAN_H", + "-DHAVE_PTHREAD=1", + "-DHAVE_FREETYPE=1", + "-DHAVE_FT_GET_VAR_BLEND_COORDINATES=1", + "-DHAVE_FT_SET_VAR_BLEND_COORDINATES=1", + "-DHAVE_FT_DONE_MM_VAR=1", + "-DHAVE_FT_GET_TRANSFORM=1", + "-Dhb_malloc_impl=ui_malloc", + "-Dhb_calloc_impl=ui_calloc", + "-Dhb_realloc_impl=ui_realloc", + "-Dhb_free_impl=ui_free", + }, + }); + w.harfbuzz = .{ .lib = harfbuzz, .include = upstream.path("src") }; + // The Atlas's own tests, over the same FreeType, HarfBuzz and + // shim, the embedded face theirs to draw. + if (w.sdl) |sdl| if (sketchbook) |sb| { + const atlas_mod = b.createModule(.{ .root_source_file = sb.path("dev/text/Atlas.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "c", .module = sdl.gui_c }} }); + atlas_mod.linkLibrary(ft); + atlas_mod.linkLibrary(harfbuzz); + atlas_mod.addIncludePath(upstream.path("src")); + atlas_mod.addCSourceFile(.{ .file = sb.path("vendor/font.c") }); + atlas_mod.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf") }); + w.atlas_test = b.addTest(.{ .root_module = atlas_mod, .filters = test_filters }); + }; + } + if (target.result.os.tag == .macos) if (w.sdl) |sdl| { + const adapter_test = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O1", "-framework", "Cocoa", "-I" }); + adapter_test.addDirectoryArg(sdl.include); + adapter_test.addFileArg(b.path("test/macos_trackpad.m")); + adapter_test.addFileInput(b.path("src/gui/macos_trackpad.m")); + adapter_test.addFileInput(b.path("src/gui/macos_trackpad.h")); + adapter_test.addArg("-o"); + const adapter_bin = adapter_test.addOutputFileArg("macos-trackpad-test"); + const run_adapter = std.Build.Step.Run.create(b, "run macos-trackpad-test"); + run_adapter.addFileArg(adapter_bin); + run_adapter.has_side_effects = true; + b.step("macos-trackpad-test", "test native SDL trackpad decoding and haptics without hardware").dependOn(&run_adapter.step); + }; + return w; +} + +/// glslc <glsl> -fshader-stage=<vertex|fragment> -o <name>.spv, returned as +/// a LazyPath for @embedFile. The stage is the name's own suffix. +fn compileGlsl(b: *std.Build, glsl: std.Build.LazyPath, name: []const u8) std.Build.LazyPath { + const stage = if (std.mem.endsWith(u8, name, ".vert")) "vertex" else "fragment"; + const cmd = b.addSystemCommand(&.{ "glslc", b.fmt("-fshader-stage={s}", .{stage}) }); + cmd.addFileArg(glsl); + cmd.addArg("-o"); + return cmd.addOutputFileArg(b.fmt("{s}.spv", .{name})); +} diff --git a/build/library.zig b/build/library.zig new file mode 100644 index 00000000..049b4323 --- /dev/null +++ b/build/library.zig @@ -0,0 +1,49 @@ +const std = @import("std"); +const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars; +const core = @import("core.zig"); +const patches = @import("patches.zig"); + +/// pardes as a library, all a package that depends on it is given: the +/// `pardes-syntax` module (src/lib_syntax.zig), the grammars, highlighting +/// and themes for a program that draws source text itself. It takes +/// tree-sitter and the grammars of its `tree-sitter` option and no other +/// dependency, so nothing else is fetched (build.zig.zon). test/lib is such +/// a package, which `lib-test` builds. +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full; + var threaded: std.Io.Threaded = .init(b.allocator, .{}); + defer threaded.deinit(); + const io = threaded.io(); + const mod = b.addModule("pardes-syntax", .{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("src/lib_syntax.zig"), + .link_libc = true, + }); + // A library's options: its grammars, nothing stamped, no window. + const cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars }; + mod.addOptions("pardes_config", core.shellOptions(b, cfg, .tui)); + const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars); + const themes = core.generatedThemes(b, io, target, optimize); + mod.addImport("generated_themes", themes); + ts.wire(mod); + mod.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") })); + // The editor, `pardes-editor`, to a package that asks for it: uucode, + // mvzr and vaxis (with what its build names) are fetched then and only + // then. Of vaxis it takes the grapheme width, which uucode alone feeds. + if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return; + const uucode = core.uucodeModule(b, target, optimize) orelse return; + const mvzr = patches.mvzr(b, patches.tool(b), b.dependencyLazy("mvzr", .{ .target = target, .optimize = optimize }) catch return, target, optimize); + const vaxis_dep = b.dependencyLazy("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) catch return; + const width = b.addWriteFiles(); + _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig"); + const vaxis = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"), + .imports = &.{.{ .name = "uucode", .module = uucode }}, + }); + _ = core.editorModule(b, "pardes-editor", target, optimize, cfg, .{ .themes = themes, .ts = ts, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis }); +} diff --git a/build/macos.zig b/build/macos.zig new file mode 100644 index 00000000..bcaf4d4c --- /dev/null +++ b/build/macos.zig @@ -0,0 +1,200 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const macos_min_version = @import("../build.zig").macos_min_version; +const display_version = @import("core.zig").display_version; +const testMatch = @import("tests.zig").testMatch; + +/// `-Dplatform=macos`: libpardes.a under a Swift host, pardes.app, the dmg, +/// the AppKit snapshot suite and the C-ABI unit tests. +pub fn add(b: *std.Build, c: struct { + macos_identity: []const u8, + optimize: std.lang.Optimize, + root_mod: *std.Build.Module, + target: std.Build.ResolvedTarget, + test_build: *std.Build.Step, + test_filters: []const []const u8, + test_nonce: ?*std.Build.Module, + unit_profile: *std.Build.Step.Compile, +}) void { + const header = b.addTranslateC(.{ + .root_source_file = b.path("src/macos/pardes.h"), + .target = c.target, + .optimize = c.optimize, + }); + c.root_mod.addImport("pardes.h", header.createModule()); + + const lib = b.addLibrary(.{ + .name = "pardes", + .linkage = .static, + .root_module = c.root_mod, + }); + lib.bundle_compiler_rt = true; + lib.bundle_ubsan_rt = true; + const archive: ?std.Build.LazyPath = + if (builtin.os.tag.isDarwin() and c.target.result.os.tag.isDarwin()) fatArchive(b, lib) else null; + const install_lib: *std.Build.Step = if (archive) |a| + &b.addInstallLibFile(a, "libpardes.a").step + else + &b.addInstallArtifact(lib, .{}).step; + b.getInstallStep().dependOn(install_lib); + b.installFile("src/macos/pardes.h", "include/pardes.h"); + + const app_step = b.step("macos-app", "assemble zig-out/pardes.app (needs macOS + swiftc)"); + const dmg_step = b.step("macos-dmg", "package zig-out/pardes.dmg for distribution (needs macOS + swiftc)"); + if (archive) |lib_archive| { + const apple_arch: []const u8 = + if (c.target.result.cpu.arch == .aarch64) "arm64" else @tagName(c.target.result.cpu.arch); + const triple = b.fmt("{s}-apple-macos{d}.{d}", .{ + apple_arch, macos_min_version.major, macos_min_version.minor, + }); + const min_version = b.fmt("{d}.{d}", .{ macos_min_version.major, macos_min_version.minor }); + + const swift_mode: []const u8 = switch (c.optimize) { + .debug => "-Onone", + .small => "-Osize", + .fast, .safe => "-O", + }; + + const link = b.addSystemCommand(&.{ "swiftc", swift_mode, "-target", triple, "-import-objc-header" }); + link.addFileArg(b.path("src/macos/pardes.h")); + link.addArg("-o"); + const app_bin = link.addOutputFileArg("pardes"); + for ([_][]const u8{ + "main.swift", + "AppDelegate.swift", + "PardesView.swift", + "ScenePostprocessor.swift", + "FileWatcher.swift", + }) |src| + link.addFileArg(b.path(b.fmt("src/macos/Sources/{s}", .{src}))); + link.addFileArg(lib_archive); + link.addArgs(&.{ + "-lc++", + "-framework", + "AppKit", + "-framework", + "CoreText", + "-framework", + "CoreGraphics", + "-framework", + "CoreImage", + "-framework", + "Metal", + }); + + const icon_build = b.addSystemCommand(&.{ "swiftc", "-O", "-target", triple, "-o" }); + const icon_bin = icon_build.addOutputFileArg("pardes-icon"); + icon_build.addFileArg(b.path("src/macos/icon.swift")); + const icon_run = std.Build.Step.Run.create(b, "pardes-icon"); + icon_run.addFileArg(icon_bin); + icon_run.addFileArg(b.path("src/macos/icon.png")); + const icon_dir = icon_run.addOutputDirectoryArg("Resources"); + + const plist = b.addSystemCommand(&.{ + "plutil", "-replace", "LSMinimumSystemVersion", "-string", min_version, "-o", + }); + const plist_out = plist.addOutputFileArg("Info.plist"); + plist.addFileArg(b.path("src/macos/Info.plist")); + + const version_plist = b.addSystemCommand(&.{ + "plutil", "-replace", "CFBundleShortVersionString", "-string", display_version, "-o", + }); + const version_plist_out = version_plist.addOutputFileArg("Info.plist"); + version_plist.addFileArg(plist_out); + + const install_app_bin = b.addInstallFileWithDir(app_bin, .{ .custom = "pardes.app/Contents/MacOS" }, "pardes"); + const install_plist = b.addInstallFileWithDir(version_plist_out, .{ .custom = "pardes.app/Contents" }, "Info.plist"); + const install_scene_kernel = b.addInstallFileWithDir( + b.path("shaders/crt.ci.metal"), + .{ .custom = "pardes.app/Contents/Resources" }, + "crt.ci.metal", + ); + // CFBundleIconFile names this without its extension; without both + // halves the Dock shows the generic blank page. + const install_icon = b.addInstallFileWithDir(icon_dir.path(b, "pardes.icns"), .{ .custom = "pardes.app/Contents/Resources" }, "pardes.icns"); + + const sign = b.addSystemCommand(&.{ "codesign", "--force", "--sign", c.macos_identity }); + if (!std.mem.eql(u8, c.macos_identity, "-")) sign.addArgs(&.{ "--options", "runtime", "--timestamp" }); + sign.setCwd(installed("")); + sign.addArg("pardes.app"); + sign.has_side_effects = true; + sign.step.dependOn(&install_app_bin.step); + sign.step.dependOn(&install_plist.step); + sign.step.dependOn(&install_icon.step); + sign.step.dependOn(&install_scene_kernel.step); + app_step.dependOn(&sign.step); + + const dmg = b.addSystemCommand(&.{ "hdiutil", "create", "-volname", "pardes", "-ov", "-format", "UDZO", "-srcfolder" }); + dmg.setCwd(installed("")); + dmg.addArgs(&.{ "pardes.app", "pardes.dmg" }); + dmg.has_side_effects = true; + dmg.step.dependOn(&sign.step); + dmg_step.dependOn(&dmg.step); + + b.getInstallStep().dependOn(&sign.step); + } else { + const why = b.addFail("pardes.app needs a Darwin host and target; drop -Dtarget= or pass -Dtarget=native"); + app_step.dependOn(&why.step); + dmg_step.dependOn(&why.step); + } + + const e2e_step = b.step("macos-e2e", "run the offscreen AppKit snapshot suite (needs macOS + swiftc)"); + if (archive) |lib_archive| { + const arch = if (c.target.result.cpu.arch == .aarch64) "arm64" else @tagName(c.target.result.cpu.arch); + const triple = b.fmt("{s}-apple-macos{d}.{d}", .{ arch, macos_min_version.major, macos_min_version.minor }); + const e2e = b.addSystemCommand(&.{ "swiftc", "-O", "-target", triple, "-import-objc-header" }); + e2e.addFileArg(b.path("src/macos/pardes.h")); + e2e.addArg("-o"); + const e2e_bin = e2e.addOutputFileArg("pardes-macos-e2e"); + for ([_][]const u8{ + "src/macos/Sources/PardesView.swift", + "src/macos/Sources/ScenePostprocessor.swift", + "src/macos/Sources/FileWatcher.swift", + "src/macos/Sources/AppDelegate.swift", + "test/macos_e2e.swift", + }) |source| e2e.addFileArg(b.path(source)); + e2e.addFileArg(lib_archive); + e2e.addArgs(&.{ "-lc++", "-framework", "AppKit", "-framework", "CoreText", "-framework", "CoreGraphics", "-framework", "CoreImage", "-framework", "Metal" }); + const files = b.addWriteFiles(); + const runnable = files.addCopyFile(e2e_bin, "pardes-macos-e2e"); + _ = files.addCopyFile(b.path("shaders/crt.ci.metal"), "crt.ci.metal"); + const run_e2e = std.Build.Step.Run.create(b, "run macos-e2e"); + run_e2e.addFileArg(runnable); + run_e2e.setCwd(b.path(".")); + run_e2e.addPassthruArgs(); + run_e2e.has_side_effects = true; + e2e_step.dependOn(&run_e2e.step); + } else e2e_step.dependOn(&b.addFail("macos-e2e needs a Darwin host and target").step); + + const unit_step = b.step("unit-test", "run the C-ABI guard and core unit tests"); + const unit_tests = b.addTest(.{ .root_module = c.root_mod, .filters = c.test_filters }); + if (c.test_nonce) |nonce| unit_tests.root_module.addImport("test_rebuild_nonce", nonce); + c.test_build.dependOn(&unit_tests.step); + const run_unit = b.addRunArtifact(unit_tests); + run_unit.has_side_effects = true; + unit_step.dependOn(&run_unit.step); + if (testMatch(b, c.unit_profile, c.test_filters, unit_step)) |check| check.addArtifactArg(unit_tests); +} + +/// `sub` under the install prefix, known only when the build runs. +fn installed(sub: []const u8) std.Build.LazyPath { + return .{ .relative = .{ .base = .install_prefix, .sub_path = sub } }; +} + +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" }); + const output = run.addOutputFileArg("libpardes.a"); + for (lib.getCompileDependencies(false), 0..) |dep, i| { + if (dep.kind != .lib) continue; + run.addFileArg(reindexed(b, dep.getEmittedBin(), i)); + } + return output; +} + +fn reindexed(b: *std.Build, archive: std.Build.LazyPath, index: usize) std.Build.LazyPath { + const run = std.Build.Step.Run.create(b, b.fmt("ranlib #{d}", .{index})); + run.addArgs(&.{ "/bin/sh", "-c", "/bin/cp \"$1\" \"$2\" && /usr/bin/ranlib \"$2\"", "_" }); + run.addFileArg(archive); + return run.addOutputFileArg(b.fmt("{d}.a", .{index})); +} diff --git a/mupdf.zig b/build/mupdf.zig index 48dca46b..8ade36a5 100644 --- a/mupdf.zig +++ b/build/mupdf.zig @@ -242,7 +242,7 @@ pub fn addProbe(b: *std.Build, result: Result, options: struct { .name = "pardes-mupdf-probe", .root_module = b.createModule(.{ .target = options.target, - .optimize = .ReleaseSafe, + .optimize = .safe, .link_libc = true, }), }); @@ -350,7 +350,7 @@ fn makeSources(b: *std.Build, makelists: []const u8, variable: []const u8) []con if (!std.mem.startsWith(u8, assignment, "+=")) continue; const path = std.mem.trim(u8, assignment[2..], " \t\r"); if (!std.mem.endsWith(u8, path, ".c")) continue; - files[file_i] = b.dupe(path); + files[file_i] = b.graph.dupeString(path); file_i += 1; } return files; diff --git a/build/patches.zig b/build/patches.zig new file mode 100644 index 00000000..b6b6b86d --- /dev/null +++ b/build/patches.zig @@ -0,0 +1,338 @@ +const std = @import("std"); + +/// The upstream patches: each a table of edits to one fetched file, applied +/// at make time by tools/patch.zig, with what it appends a file of its own +/// in build/patches/. Each is applied so that a fresh fetch keeps it, and a +/// bump that moves an anchor fails that file's step. +const Edit = struct { old: []const u8, new: []const u8, count: u8 = 1 }; + +/// tools/patch.zig, made once and handed to each patch below. +pub fn tool(b: *std.Build) *std.Build.Step.Compile { + return b.addExecutable(.{ .name = "pardes-patch", .root_module = b.createModule(.{ + .root_source_file = b.path("tools/patch.zig"), + .target = b.graph.host, + }) }); +} + +/// `file` of `dep` with `edits` applied, and build/patches/`append` after them. +fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, file: []const u8, edits: []const Edit, append: ?[]const u8) std.Build.LazyPath { + const run = b.addRunArtifact(patch); + run.setName(b.fmt("patch {s}", .{file})); + run.addFileArg(dep.path(file)); + const out = run.addOutputFileArg(std.fs.path.basename(file)); + if (append) |name| { + run.addArg("--append"); + run.addFileArg(b.path(b.fmt("build/patches/{s}", .{name}))); + } + for (edits) |e| run.addArgs(&.{ b.fmt("{d}", .{e.count}), e.old, e.new }); + return out; +} + +/// vaxis's input parser: no reply, split read or malformed sequence may +/// reach the editor as typed text, and none may panic or end input. +/// - A cursor position report that no F3 could have sent is no key: the +/// startup width queries' `CSI 1;1R` arrived as two F3s, which a shell +/// pane took for text (build/patches/vaxis_parser.zig). +/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key, +/// not Alt+Escape followed by `[A` as text. +/// - An X10 mouse report and a kitty graphics reply cut short by a read +/// wait for their rest: the first became three bytes of text, the +/// second sliced past its input. +/// - A byte no UTF-8 starts with is dropped instead of failing the parse, +/// which stopped input. (vaxis itself now drops a malformed color or +/// clipboard reply and ends an OSC at its first terminator.) +/// - A device report's fields are sought in the sequence, not past it. +const vaxis_parser = [_]Edit{ + .{ + .old = + \\ 0x5F => return parseApc(input), + \\ else => { + , + .new = + \\ 0x5F => return parseApc(input), + \\ // pardes's patch (its build.zig): ESC before a key's sequence is Alt on the key. + \\ 0x1B => if (input.len > 2 and (input[2] == '[' or input[2] == 'O')) { + \\ var inner = if (input[2] == '[') parseCsi(input[1..], &self.buf, self.cursor_position_requests) else parseSs3(input[1..]); + \\ if (inner.n == 0) return inner; + \\ if (inner.event) |*event| switch (event.*) { + \\ .key_press, .key_release => |*key| key.mods.alt = true, + \\ else => {}, + \\ }; + \\ inner.n += 1; + \\ return inner; + \\ } else return .{ .event = .{ .key_press = .{ .codepoint = Key.escape, .mods = .{ .alt = true } } }, .n = 2 }, + \\ else => { + , + }, + .{ + .old = " const first_cp = iter.next() orelse return error.InvalidUTF8;\n", + .new = " const first_cp = iter.next() orelse return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n", + }, + .{ + .old = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return error.InvalidUTF8;\n", + .new = " n = std.unicode.utf8CodepointSequenceLength(first_cp) catch return .{ .event = null, .n = 1 }; // pardes's patch (its build.zig)\n", + }, + .{ + .old = + \\ const sequence = input[0 .. end + 1 + 1]; + \\ + \\ switch (input[2]) { + , + .new = + \\ // pardes's patch (its build.zig): an ESC that ends the input is half an ST. + \\ if (input.len < end + 2) return .{ .event = null, .n = 0 }; + \\ const sequence = input[0 .. end + 1 + 1]; + \\ + \\ switch (input[2]) { + , + }, + .{ + .old = + \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { + \\ // Legacy keys + \\ + , + .new = + \\ 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'R', 'S' => { + \\ // pardes's patch (its build.zig): a cursor position report is no key. + \\ if (final == 'R' and cursorReport(sequence)) return null_event; + \\ // Legacy keys + \\ + , + }, + .{ + .old = " std.debug.assert(sequence.len >= 4); // ESC [ ? c == 4 bytes\n", + .new = " if (sequence.len < 4) return null_event; // pardes's patch (its build.zig)\n", + }, + .{ + .old = "const delim_idx = std.mem.indexOfScalarPos(u8, input, 3, ';')", + .new = "const delim_idx = std.mem.indexOfScalarPos(u8, sequence, 3, ';')", + .count = 2, + }, + .{ + .old = "input[delim_idx + 1 .. sequence.len - 2]", + .new = "sequence[@min(delim_idx + 1, sequence.len - 2) .. sequence.len - 2]", + }, + .{ + .old = " if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) {\n", + .new = + \\ // pardes's patch (its build.zig): an X10 report still arriving is incomplete, not text. + \\ if (input.len == 3 and input[2] == 'M' and full_input.len < 6) return .{ .event = null, .n = 0 }; + \\ if (input.len == 3 and (input[2] == 'M') and full_input.len >= 6) { + \\ + , + }, +}; + +/// vaxis's render: a blank whose ink alone changed is not sent, since a +/// blank's ink shows nowhere (build/patches/vaxis_render.zig). A fade +/// (InactiveDim on a focus change) sent every blank of every pane it +/// touched again: 7 KB a click for three shell panes. The terminal keeps +/// the old ink there, and so does vaxis's last frame. And the secondary +/// cursors count as changed when they differ, not when they are the +/// same: read the other way round, every render started a frame, ~40 +/// bytes to the terminal with nothing changed. +const vaxis_render = [_]Edit{ + .{ + .old = + \\ if ((!self.refresh and + \\ last.eql(cell) and + , + .new = + \\ if ((!self.refresh and + \\ (last.eql(cell) or blankInkOnly(&last, &cell)) and // pardes's patch (its build.zig) + \\ + , + }, + .{ + .old = " std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary);\n", + .new = " !std.meta.eql(self.screen.cursor_secondary, self.state.cursor_secondary); // pardes's patch (its build.zig)\n", + }, +}; + +/// vaxis's event queue: a pop that makes room woke one blocked writer, and +/// only on the pop from full. The tui has two writers (a pane's pty +/// reader, and the input reader posting the frame ack's wake), so when the +/// loop emptied a full queue in one batch the writer not woken waited on +/// for good: under `yes` the pane stopped being read, its program blocked +/// on the pty, while keys went on working. Every blocked writer is woken now. +const vaxis_queue = [_]Edit{ + .{ .old = "self.not_full.signal(self.io);", .new = "self.not_full.broadcast(self.io); // pardes's patch (its build.zig)", .count = 2 }, +}; + +pub fn vaxis(b: *std.Build, patch: *std.Build.Step.Compile, vaxis_dep: *std.Build.Dependency, vaxis_mod: *std.Build.Module) void { + const files = b.addWriteFiles(); + _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/Parser.zig", &vaxis_parser, "vaxis_parser.zig"), "Parser.zig"); + _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/Vaxis.zig", &vaxis_render, "vaxis_render.zig"), "Vaxis.zig"); + _ = files.addCopyFile(apply(b, patch, vaxis_dep, "src/queue.zig", &vaxis_queue, null), "queue.zig"); + _ = files.addCopyFile(vaxis_dep.path("src/widgets/terminal/Parser.zig"), "widgets/terminal/Parser.zig"); + // Suffixes: this leaves out both Parser.zig files, Vaxis.zig and + // queue.zig, written above. + _ = files.addCopyDirectory(vaxis_dep.path("src"), "", .{ .exclude_extensions = &.{ "Parser.zig", "Vaxis.zig", "queue.zig" } }); + vaxis_mod.root_source_file = files.getDirectory().path(b, "main.zig"); +} + +/// zstbi with stb_image and its writer cut out: of it only its resize is +/// left, for a terminal PNG's downscale (build/core.zig, "One PNG +/// decoder"). zstbi.deinit still resets the reader's and the writer's flip +/// flags, and Image.deinit frees the resize's output. +const zstbi_cut = [_]Edit{ + .{ .old = "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", .new = "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" }, + .{ .old = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", .new = "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" }, +}; + +pub fn zstbi(b: *std.Build, patch: *std.Build.Step.Compile, zstbi_dep: *std.Build.Dependency, zstbi_mod: *std.Build.Module) void { + var sources: usize = 0; + for (zstbi_mod.link_objects.items) |obj| switch (obj) { + .c_source_file => |csf| { + sources += 1; + csf.file = apply(b, patch, zstbi_dep, "src/zstbi.c", &zstbi_cut, null); + }, + else => {}, + }; + if (sources != 1) @panic("zstbi's build no longer compiles one C file: redo its patch in build/patches.zig"); +} + +/// ghostty's kitty graphics loader (src/terminal/kitty/graphics_image.zig), +/// for what a program in a pane may name with t=f, t=t and t=s +/// (test/kitty.zig): +/// - a path is opened for reading only once it is known to be a regular +/// file: ghostty opens first and checks after, and the open of a FIFO +/// waits for a writer (pardes hung) while a device's open may do +/// something. On Linux an O_PATH probe looks, which opens nothing, and +/// the same inode is reopened through /proc/self/fd; elsewhere a stat by +/// path looks first (build/patches/ghostty_kitty.zig). +/// - shared memory is opened non-blocking and must be a regular file, so +/// a FIFO in /dev/shm (or a symlink there to one) neither hangs nor maps. +/// - an image may be no larger than a screen's storage +/// (TerminalImages.storage_limit) rather than ghostty's 400 MB, which a +/// program could make pardes read and hold before refusing it. +const ghostty_kitty = [_]Edit{ + .{ + .old = "const max_size = 400 * 1024 * 1024; // 400MB", + .new = "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit", + }, + .{ + .old = + \\ var file = std.Io.Dir.cwd().openFile( + \\ io, + \\ path, + \\ .{}, + \\ ) catch |err| { + , + .new = + \\ var file = pardesOpenRegular(io, path) catch |err| { + , + }, + .{ + .old = " const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), @as(u16, 0));", + .new = + \\ // pardes (build.zig): a FIFO there must not hang the open, and + \\ // on Linux nothing but a regular file is opened at all. FreeBSD's + \\ // names are no files, and its shm_open refuses O_NONBLOCK. + \\ if (comptime builtin.target.os.tag == .linux) if (path.len > 0 and path[0] == '/') { + \\ var dev: [std.Io.Dir.max_path_bytes]u8 = undefined; + \\ const full = std.fmt.bufPrint(&dev, "/dev/shm{s}", .{path}) catch return error.InvalidData; + \\ const shm_stat = std.Io.Dir.cwd().statFile(io, full, .{}) catch return error.InvalidData; + \\ if (shm_stat.kind != .file) return error.InvalidData; + \\ }; + \\ const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY, .NONBLOCK = builtin.target.os.tag != .freebsd })), @as(u16, 0)); + , + }, + .{ + .old = " if (stat.size <= 0) return error.InvalidData;", + .new = " if (stat.kind != .file) return error.InvalidData; // pardes (build.zig)\n if (stat.size <= 0) return error.InvalidData;", + }, +}; + +pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, vt: *std.Build.Module) void { + const files = b.addWriteFiles(); + // The rest of src as it is; fonts are the app's, not the library's. + _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", ".ttf", ".otf" } }); + _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/kitty/graphics_image.zig", &ghostty_kitty, "ghostty_kitty.zig"), "terminal/kitty/graphics_image.zig"); + vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig"); +} + +/// mvzr, whose matcher pardes searches with while holding the editor: +/// - A step budget (build/patches/mvzr_budget.zig): 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), so each entry to matchPattern, +/// which its backtracking recurses through, spends a step, and with none +/// left the match fails and says so (src/regexp.zig). +/// - A group's greedy match never gave back to what follows the group: on +/// `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the group's +/// own `)` as an alternative, so every group with pattern after it takes +/// matchGroup's alternatives branch, which tries each alternative's one +/// (greedy) match and gives up. When the rest fails after it, try that +/// alternative's shorter matches, longest first +/// (docs/mvzr-group-backtrack.md is the report for upstream). +/// - `$` is refused anywhere but last, so `h$|zz` was a bad pattern while +/// `zz|h$` was fine. An alternative or a group ends at `|` and `)`, and +/// the matcher's `.end` ends the alternative it is in, so `$` may stand +/// before either (docs/mvzr-group-backtrack.md). +/// - Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it +/// upstream). A class's range ending at `\xff` counted to 256 in a u8, an +/// overflow (a panic in a safe build, a runaway loop in a fast one): +/// `[\x80-\xff]` in any search took the editor down. +const mvzr_edits = [_]Edit{ + .{ + .old = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n", + .new = + \\fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch { + \\ if (steps_left == 0) { + \\ exhausted = true; + \\ return null; + \\ } + \\ steps_left -= 1; + \\ + , + }, + .{ + .old = + \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); + \\ if (next_match) |m2| { + \\ // Whole group matches, and we can use m2.j + \\ return m2; + \\ } else { // Try our next pattern, if any. + \\ + , + .new = + \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); + \\ if (next_match) |m2| { + \\ // Whole group matches, and we can use m2.j + \\ return m2; + \\ } else { // Try our next pattern, if any. + \\ // pardes's patch (its build.zig): back the group off. + \\ var e = m1.i; + \\ while (e > i) { + \\ e -= 1; + \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue; + \\ if (shorter.i != e) continue; + \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole; + \\ } + \\ + , + }, + .{ + .old = + \\ '$' => { + \\ if (i + 1 < in.len) { + \\ + , + .new = + \\ '$' => { + \\ // pardes's patch (its build.zig): `$` may end an alternative. + \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') { + \\ + , + }, + .{ .old = "for (c1..c2 + 1) |c_range|", .new = "for (c1..@as(usize, c2) + 1) |c_range|" }, + .{ .old = "[1]RegOp{.{ .unused = {} }} ** ops", .new = "@splat(.{ .unused = {} })" }, + .{ .old = "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", .new = "@splat(.{ .low = 0, .hi = 0 })" }, + .{ .old = "\"a\" ** 2048", .new = "&@as([2048]u8, @splat('a'))", .count = 2 }, + .{ .old = "\"12345,\" ** 255", .new = "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))" }, +}; + +pub fn mvzr(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + return b.createModule(.{ .root_source_file = apply(b, patch, dep, "src/mvzr.zig", &mvzr_edits, "mvzr_budget.zig"), .target = target, .optimize = optimize }); +} diff --git a/build/patches/ghostty_kitty.zig b/build/patches/ghostty_kitty.zig new file mode 100644 index 00000000..a86d62d3 --- /dev/null +++ b/build/patches/ghostty_kitty.zig @@ -0,0 +1,15 @@ +/// pardes (build.zig): `path`, opened for reading only once it is known +/// to be a regular file. Elsewhere than Linux, a stat by path first. +fn pardesOpenRegular(io: std.Io, path: []const u8) !std.Io.File { + if (comptime builtin.target.os.tag != .linux) { + if ((try std.Io.Dir.cwd().statFile(io, path, .{})).kind != .file) return error.NotRegularFile; + return std.Io.Dir.cwd().openFile(io, path, .{}); + } + const probe = try std.Io.Dir.cwd().openFile(io, path, .{ .path_only = true }); + defer probe.close(io); + const stat = try probe.stat(io); + if (stat.kind != .file) return error.NotRegularFile; + var buf: [32]u8 = undefined; + const same = std.fmt.bufPrint(&buf, "/proc/self/fd/{d}", .{probe.handle}) catch unreachable; + return std.Io.Dir.cwd().openFile(io, same, .{}); +} diff --git a/build/patches/mvzr_budget.zig b/build/patches/mvzr_budget.zig new file mode 100644 index 00000000..e1d14c12 --- /dev/null +++ b/build/patches/mvzr_budget.zig @@ -0,0 +1,4 @@ +/// pardes's patch (its build.zig): matchPattern entries left before a +/// match gives up, and whether one did. Set by the caller per search. +pub threadlocal var steps_left: u64 = std.math.maxInt(u64); +pub threadlocal var exhausted: bool = false; diff --git a/build/patches/vaxis_parser.zig b/build/patches/vaxis_parser.zig new file mode 100644 index 00000000..90b09025 --- /dev/null +++ b/build/patches/vaxis_parser.zig @@ -0,0 +1,13 @@ +/// pardes's patch (its build.zig): whether `CSI ... R` answers a cursor +/// position query. Only `CSI 1 ; mods R` with mods past 1 is a modified F3 +/// (a bare F3 is `SS3 R`); a report has another row, or col 1 (mods 1). +fn cursorReport(sequence: []const u8) bool { + const params = sequence[2 .. sequence.len - 1]; + if (params.len > 0 and params[0] == '?') return true; + var fields = std.mem.splitScalar(u8, params, ';'); + const row = fields.first(); + const col = fields.next() orelse return false; + if (fields.next() != null or row.len == 0 or col.len == 0) return false; + for (params) |c| if (c != ';' and !std.ascii.isDigit(c)) return false; + return !std.mem.eql(u8, row, "1") or std.mem.eql(u8, col, "1"); +} diff --git a/build/patches/vaxis_render.zig b/build/patches/vaxis_render.zig new file mode 100644 index 00000000..b6c56f4e --- /dev/null +++ b/build/patches/vaxis_render.zig @@ -0,0 +1,25 @@ +/// pardes's patch (its build.zig): a blank cell (a space, no underline, +/// strike or reverse) that differs from the last frame's blank in its +/// ink alone, which shows nowhere. +inline fn blankInkOnly(last: *const InternalScreen.InternalCell, cell: *const Cell) bool { + if (!(cell.char.grapheme.len == 1 and cell.char.grapheme[0] == ' ')) return false; + if (last.default or cell.default) return false; + if (!(last.char.items.len == 1 and last.char.items[0] == ' ')) return false; + const s = cell.style; + if (s.reverse or s.strikethrough or s.ul_style != .off) return false; + if (!std.mem.eql(u8, last.uri.items, cell.link.uri)) return false; + // Field by field: Style.eql is slow, and this runs for every blank + // a scrolling shell moves. + const l = last.style; + return sameColor(l.bg, s.bg) and sameColor(l.ul, s.ul) and l.ul_style == s.ul_style and + l.bold == s.bold and l.dim == s.dim and l.italic == s.italic and l.blink == s.blink and + !l.reverse and !l.strikethrough and l.invisible == s.invisible; +} + +inline fn sameColor(a: Cell.Color, b: Cell.Color) bool { + return switch (a) { + .default => b == .default, + .index => |i| b == .index and b.index == i, + .rgb => |rgb| b == .rgb and rgb[0] == b.rgb[0] and rgb[1] == b.rgb[1] and rgb[2] == b.rgb[2], + }; +} diff --git a/build/process.zig b/build/process.zig index 1968aaab..16f9b48b 100644 --- a/build/process.zig +++ b/build/process.zig @@ -6,6 +6,8 @@ const std = @import("std"); /// window's own, run in full when asked. pub fn add(b: *std.Build, opts: struct { exe: *std.Build.Step.Compile, + /// The language server a tty case's `.rs` files speak to (test/lspmock.zig). + lspmock: *std.Build.Step.Compile, /// The addons the build made (image, pdf), which every session loads: /// each `--addon=<lib>`, linked into its data directory's addons. addons: []const *std.Build.Step.Compile, @@ -23,16 +25,6 @@ pub fn add(b: *std.Build, opts: struct { .link_libc = true, }); ninep_client.addImport("cloud9", opts.cloud9); - // The language server a tty case's `.rs` files speak to. - const lspmock = b.addExecutable(.{ - .name = "pardes-lspmock", - .root_module = b.createModule(.{ - .target = opts.target, - .optimize = opts.optimize, - .root_source_file = b.path("test/lspmock.zig"), - .link_libc = true, - }), - }); const process_test = b.addExecutable(.{ .name = "pardes-process-test", .root_module = b.createModule(.{ @@ -52,7 +44,7 @@ pub fn add(b: *std.Build, opts: struct { const run_process_test = b.addRunArtifact(process_test); run_process_test.addArtifactArg(opts.exe); for (opts.addons) |a| run_process_test.addPrefixedFileArg("--addon=", a.getEmittedBin()); - run_process_test.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); + run_process_test.addPrefixedFileArg("--lspmock=", opts.lspmock.getEmittedBin()); run_process_test.addArg(if (opts.gui) "--backend=gui" else "--backend=tui"); run_process_test.addPassthruArgs(); // The tty cases' goldens are test/snapshots/'s, from the build root. diff --git a/build/tests.zig b/build/tests.zig new file mode 100644 index 00000000..d8bce18d --- /dev/null +++ b/build/tests.zig @@ -0,0 +1,264 @@ +const std = @import("std"); +const Platform = @import("../build.zig").Platform; +const core = @import("core.zig"); +const tools = @import("tools.zig"); +const program = tools.program; + +/// unit-test and the test roots it runs, each with its own step where it +/// has one: core-test, shell-test, term-test, pane-test, behaviour-test, +/// addon-test (and the addons it loads), kitty-test, the 9P roots. +pub fn add(b: *std.Build, c: struct { + addon_mod: *std.Build.Module, + atlas_test: ?*std.Build.Step.Compile, + cells_test: ?*std.Build.Step.Compile, + core_lean: *std.Build.Module, + core_module: *std.Build.Module, + /// core_module's configuration, for the test roots that run on its imports. + core_cfg: core.Core, + exe: *std.Build.Step.Compile, + ghostty_vt_for_tests: ?*std.Build.Module, + image_addon: *std.Build.Step.Compile, + /// The scripted language server the sessions' language words ask. + lspmock: *std.Build.Step.Compile, + mupdf_check: *std.Build.Step, + optimize: std.lang.Optimize, + parts: core.Parts, + pdf_addon: ?*std.Build.Step.Compile, + platform: Platform, + root_mod: *std.Build.Module, + snake_shader_lib: ?*std.Build.Step.Compile, + target: std.Build.ResolvedTarget, + test_build: *std.Build.Step, + test_filters: []const []const u8, + test_nonce: ?*std.Build.Module, + tools: tools.Tools, + unit_profile: *std.Build.Step.Compile, +}) void { + const unit_step = b.step("unit-test", "run native shell and module unit tests"); + // One copy of each codec in the binary (docs/shared-libs.md): the + // linked symbol table, read for the families the build chose against. + // ELF only; it runs with every unit-test, like the perf gate. + if (c.target.result.ofmt == .elf) { + const libs_check = b.addExecutable(.{ + .name = "pardes-shared-libs-check", + .root_module = b.createModule(.{ + .target = b.graph.host, + .optimize = .debug, + .root_source_file = b.path("tools/shared_libs_check.zig"), + .link_libc = true, + }), + }); + const run_libs_check = b.addRunArtifact(libs_check); + run_libs_check.addArtifactArg(c.exe); + const libs_check_step = b.step("shared-libs-check", "fail when the binary links a second copy of a codec the build chose one of (docs/shared-libs.md)"); + libs_check_step.dependOn(&run_libs_check.step); + unit_step.dependOn(&run_libs_check.step); + } + // The perf gate runs with every unit-test (a regression like a + // contrast search per grapheme costs 100x, far past the gate). + unit_step.dependOn(c.tools.perf_gate_step); + unit_step.dependOn(c.tools.lib_test_step); + const units: Units = .{ .nonce = c.test_nonce, .build = c.test_build, .unit = unit_step, .match = testMatch(b, c.unit_profile, c.test_filters, unit_step), .profiler = c.unit_profile, .filters = c.test_filters, .target = c.target, .optimize = c.optimize }; + // The perf and fs bench programs' own tests: they compile no editor. + _ = units.add(b, units.root(b, "test/perf.zig", true, &.{.{ .name = "perf_options", .module = c.tools.perf_options.createModule() }}), null); + _ = units.add(b, units.root(b, "test/fs_bench.zig", null, &.{}), null); + if (c.cells_test) |t| _ = units.add(b, t, null); + if (c.atlas_test) |t| _ = units.add(b, t, null); + const core_test = b.addTest(.{ .root_module = c.core_lean, .filters = c.test_filters }); + const run_core_test = b.addRunArtifact(core_test); + run_core_test.has_side_effects = true; + const core_test_step = b.step("core-test", "run core tests without native shell tests, on the core without a terminal (a test that needs one skips)"); + core_test_step.dependOn(&run_core_test.step); + if (testMatch(b, c.unit_profile, c.test_filters, core_test_step)) |check| check.addArtifactArg(core_test); + // The terminal module's own tests (src/term/): the emulator without a core. + const run_term_test = units.add(b, b.addTest(.{ .root_module = c.parts.term, .filters = c.test_filters }), null); + b.step("term-test", "run the terminal module's own tests (src/term/)").dependOn(&run_term_test.step); + // test/terminal.zig reads the emulator behind a core's terminal. + const pane_tests = units.root(b, "test/panes.zig", true, &.{ .{ .name = "pardes", .module = c.core_module }, .{ .name = "term", .module = c.parts.term }, .{ .name = "plain", .module = c.parts.plain } }); + if (c.ghostty_vt_for_tests) |x| pane_tests.root_module.addImport("ghostty-vt", x); + // The core's own options module, not another over the same file: + // a file is in one module of a compilation. + pane_tests.root_module.addImport("pardes_config", c.core_module.import_table.get("pardes_config").?); + const test_addons = b.addOptions(); + test_addons.addOptionPath("image", c.image_addon.getEmittedBin()); + test_addons.addOption(bool, "has_pdf", c.pdf_addon != null); + if (c.pdf_addon) |l| test_addons.addOptionPath("pdf", l.getEmittedBin()); + pane_tests.root_module.addOptions("test_addons", test_addons); + _ = units.add(b, pane_tests, b.step("pane-test", "run pane, output and namespace integration tests")); + + // The behavioural tests (docs/next-tests.md): their module has the + // session alone, so none can reach past what a 9P client sees. + const session_module = b.createModule(.{ + .target = c.target, + .optimize = c.optimize, + .root_source_file = b.path("test/session.zig"), + .link_libc = true, + }); + session_module.addImport("pardes", c.core_module); + // The scripted language server its language words ask + // (Session.initLanguage), as the tty cases do. + const session_options = b.addOptions(); + session_options.addOptionPath("lspmock", c.lspmock.getEmittedBin()); + var fake_addon_lib: ?*std.Build.Step.Compile = null; + // The fake addon (addons/fake/fake.c) and three copies of it built + // wrong, which the loader must refuse (test/behaviour/addons.zig). + for ([_]struct { []const u8, []const u8 }{ + .{ "fake_addon", "-DFAKE_PLAIN" }, + .{ "fake_addon_abi", "-DFAKE_ABI=0x20002" }, + .{ "fake_addon_no_export", "-DFAKE_NO_EXPORT" }, + .{ "fake_addon_core_word", "-DFAKE_WORD=\"Save\"" }, + .{ "fake_addon_no_dump", "-DFAKE_NO_DUMP" }, + }) |variant| { + const lib = b.addLibrary(.{ .name = variant[0], .linkage = .dynamic, .root_module = b.createModule(.{ .target = c.target, .optimize = c.optimize, .link_libc = true }) }); + lib.root_module.addIncludePath(b.path("src/kinds")); + const name_flag = if (std.mem.eql(u8, variant[0], "fake_addon_abi")) "-DFAKE_NAME=\"fakeabi\"" else if (std.mem.eql(u8, variant[0], "fake_addon_core_word")) "-DFAKE_NAME=\"fakeword\"" else "-DFAKE_PLAIN"; + // The header is the whole contract: it compiles clean under every warning. + lib.root_module.addCSourceFile(.{ .file = b.path("addons/fake/fake.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-override-init", variant[1], name_flag } }); + session_options.addOptionPath(variant[0], lib.getEmittedBin()); + if (std.mem.eql(u8, variant[0], "fake_addon")) fake_addon_lib = lib; + } + session_options.addOptionPath("image_addon", c.image_addon.getEmittedBin()); + session_options.addOption(bool, "has_pdf_addon", c.pdf_addon != null); + if (c.pdf_addon) |l| session_options.addOptionPath("pdf_addon", l.getEmittedBin()); + session_module.addOptions("session_options", session_options); + // The build's options alone (platform), never the core: a test of a + // window's word knows which build it runs in. + const behaviour_tests = units.root(b, "test/behaviour.zig", true, &.{ .{ .name = "session", .module = session_module }, .{ .name = "pardes_config", .module = c.core_module.import_table.get("pardes_config").? } }); + const behaviour_test_step = b.step("behaviour-test", "run the behavioural tests, through the 9P tree alone (test/behaviour/), and the T1 runner (-- [--seed N]... | --monkey <seeds> | --replay)"); + _ = units.add(b, behaviour_tests, behaviour_test_step); + // An addon's own test: `--addon-test` over the fake (the template) + // and the snake (a shipped example, built but not installed), each + // with its script, compared with what it printed when written. + const addon_test_step = b.step("addon-test", "pardes --addon-test over the fake, snake and pdf addons, against addons/*/*.out, and the Zig addons' own tests"); + const snake_mod = b.createModule(.{ .root_source_file = b.path("addons/snake/snake.zig"), .target = c.target, .optimize = c.optimize, .imports = &.{.{ .name = "addon", .module = c.addon_mod }} }); + const snake_lib = b.addLibrary(.{ .name = "snake", .linkage = .dynamic, .root_module = snake_mod }); + const life_mod = b.createModule(.{ .root_source_file = b.path("addons/life/life.zig"), .target = c.target, .optimize = c.optimize, .imports = &.{.{ .name = "addon", .module = c.addon_mod }} }); + const life_lib = b.addLibrary(.{ .name = "life", .linkage = .dynamic, .root_module = life_mod }); + for ([_]*std.Build.Module{ snake_mod, life_mod, c.parts.image }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + // ...and the pdf addon's, which mupdf-check runs too (its script + // opens docs/design.pdf, from the build root). + const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ c.snake_shader_lib, "addons/snake_shader/snake_shader" }, .{ life_lib, "addons/life/life" }, .{ c.pdf_addon, "addons/pdf/pdf" } }; + for (libs) |t| if (t[0]) |lib| { + const run_addon_test = b.addRunArtifact(c.exe); + run_addon_test.setCwd(b.path(".")); + run_addon_test.addArg("--addon-test"); + run_addon_test.addArtifactArg(lib); + run_addon_test.addFileArg(b.path(b.fmt("{s}.script", .{t[1]}))); + const compare = b.addSystemCommand(&.{ "diff", "-u" }); + compare.addFileArg(b.path(b.fmt("{s}.out", .{t[1]}))); + compare.addFileArg(run_addon_test.captureStdOut(.{})); + behaviour_test_step.dependOn(&compare.step); + addon_test_step.dependOn(&compare.step); + if (lib == c.pdf_addon) c.mupdf_check.dependOn(&compare.step); + }; + // The T1 runner (test/monkey9p.zig): its modes over an in-process + // session, random 9P requests with the documented rules checked + // after each, random input hunting panics (`-- --monkey <seeds>`), + // and its seeds' tapes replayed (`-- --replay`). Bare, a short + // fixed-seed run of the first, part of behaviour-test. + const t1_runner = program(b, "pardes-monkey-session", "test/monkey9p.zig", c.target, c.optimize, &.{.{ .name = "session", .module = session_module }}); + const run_t1_runner = b.addRunArtifact(t1_runner); + run_t1_runner.addPassthruArgs(); + run_t1_runner.has_side_effects = true; + if (c.test_filters.len == 0) behaviour_test_step.dependOn(&run_t1_runner.step); + + // Kitty graphics conformance at the core: what a terminal pane's + // program sends, what it reads back, what ghostty stores and what a + // frame draws (test/kitty.zig). The end-to-end arm, through a real + // pty and the shell's output, is the kitty-harness step. + _ = units.add(b, units.root(b, "test/kitty.zig", true, &.{.{ .name = "pardes", .module = c.core_module }}), b.step("kitty-test", "run the kitty graphics conformance cases for terminal panes")); + + // 9p_io.zig's and fs.zig's tests as roots of their own, on the + // core's imports and C libraries: native transport integration + // stays reachable even when Zig's filter leaves the core's + // anonymous test-import block out. + for ([_]struct { path: []const u8, step: []const u8, about: []const u8, filters: []const []const u8 }{ + .{ .path = "src/9p_io.zig", .step = "9p-io-test", .about = "run native 9P transport and client integration tests", .filters = &.{ "Unix and TCP", "one fetch", "expired sessions", "posts itself" } }, + .{ .path = "src/fs.zig", .step = "fs-unit-test", .about = "run filesystem unit tests", .filters = c.test_filters }, + }) |t| { + var cfg = c.core_cfg; + cfg.root = t.path; + const m = core.module(b, c.parts, cfg); + b.step(t.step, t.about).dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = t.filters })).step); + } + + const cloud9: []const std.Build.Module.Import = &.{.{ .name = "cloud9", .module = c.parts.cloud9 }}; + _ = units.add(b, units.root(b, "test/history.zig", false, cloud9), null); + const protocol_tests = units.root(b, "src/9p.zig", false, cloud9); + const protocol_step = b.step("9p-test", "run freestanding 9P protocol tests"); + protocol_step.dependOn(&units.add(b, protocol_tests, null).step); + if (testMatch(b, c.unit_profile, c.test_filters, protocol_step)) |check| check.addArtifactArg(protocol_tests); + _ = units.add(b, units.root(b, "src/fonts.zig", true, cloud9), null); + _ = units.add(b, units.root(b, "src/c_heap.zig", false, cloud9), null); + // Its lookup goes wrong only where the optimizer folds it. + _ = units.add(b, b.addTest(.{ .root_module = b.createModule(.{ .target = c.target, .optimize = .safe, .root_source_file = b.path("src/c_heap.zig"), .link_libc = false, .imports = cloud9 }), .filters = c.test_filters }), null); + + _ = units.add(b, units.root(b, "test/deck/replay.zig", null, &.{.{ .name = "deck", .module = b.createModule(.{ .target = c.target, .optimize = c.optimize, .root_source_file = b.path("src/gui/deck.zig") }) }}), null); + + if (c.platform == .tui or c.platform == .gui) { + const run_shell_test = units.add(b, b.addTest(.{ .root_module = c.root_mod, .filters = c.test_filters }), null); + // The native shell's tests alone, without the perf gate's + // ReleaseFast build: what a -Dtest-filter iteration wants. + b.step("shell-test", "run the native shell's unit tests (src/main.zig's)").dependOn(&run_shell_test.step); + const profile_test = b.addExecutable(.{ + .name = "pardes-unit-profile-test", + .root_module = b.createModule(.{ + .target = c.target, + .optimize = c.optimize, + .root_source_file = b.path("test/unit_profile_test.zig"), + }), + }); + const run_profile_test = b.addRunArtifact(profile_test); + run_profile_test.addArtifactArg(c.unit_profile); + run_profile_test.has_side_effects = true; + b.step("unit-profile-test", "test profiler timing, failures and deadlines").dependOn(&run_profile_test.step); + if (c.test_filters.len == 0) { + unit_step.dependOn(&run_profile_test.step); + c.test_build.dependOn(&c.unit_profile.step); + c.test_build.dependOn(&profile_test.step); + } + } +} + +/// What every unit-test program is wired into: test-build, unit-test, and +/// unit-test's one filter check (`match`: a filter need match in one only). +const Units = struct { + nonce: ?*std.Build.Module, + build: *std.Build.Step, + unit: *std.Build.Step, + match: ?*std.Build.Step.Run, + profiler: *std.Build.Step.Compile, + filters: []const []const u8, + target: std.Build.ResolvedTarget, + optimize: std.lang.Optimize, + + /// A test program over `path` with `imports`, at this build's target + /// and optimization, filtered by -Dtest-filter. + fn root(u: Units, b: *std.Build, path: []const u8, link_libc: ?bool, imports: []const std.Build.Module.Import) *std.Build.Step.Compile { + return b.addTest(.{ .root_module = b.createModule(.{ .target = u.target, .optimize = u.optimize, .root_source_file = b.path(path), .link_libc = link_libc, .imports = imports }), .filters = u.filters }); + } + + /// `t` wired in, and run by `own` too, with a filter check of its own, + /// when it has a step of its own. + fn add(u: Units, b: *std.Build, t: *std.Build.Step.Compile, own: ?*std.Build.Step) *std.Build.Step.Run { + if (u.nonce) |nonce| t.root_module.addImport("test_rebuild_nonce", nonce); + u.build.dependOn(&t.step); + const run = b.addRunArtifact(t); + run.has_side_effects = true; + u.unit.dependOn(&run.step); + if (u.match) |check| check.addArtifactArg(t); + const step = own orelse return run; + step.dependOn(&run.step); + if (testMatch(b, u.profiler, u.filters, step)) |check| check.addArtifactArg(t); + return run; + } +}; + +pub fn testMatch(b: *std.Build, profiler: *std.Build.Step.Compile, filters: []const []const u8, step: *std.Build.Step) ?*std.Build.Step.Run { + if (filters.len == 0) return null; + const check = b.addRunArtifact(profiler); + check.addArgs(&.{ "--check-filter", filters[0] }); + check.has_side_effects = true; + step.dependOn(&check.step); + return check; +} diff --git a/build/tools.zig b/build/tools.zig new file mode 100644 index 00000000..bcf073ef --- /dev/null +++ b/build/tools.zig @@ -0,0 +1,303 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const Platform = @import("../build.zig").Platform; +const PerfBuild = @import("../build.zig").PerfBuild; +const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars; +const core = @import("core.zig"); +const testMatch = @import("tests.zig").testMatch; + +/// A program of this build's, from `root`, with libc and `imports`: the +/// harnesses, benches and runners below and in tests.zig. +pub fn program(b: *std.Build, name: []const u8, root: []const u8, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, imports: []const std.Build.Module.Import) *std.Build.Step.Compile { + return b.addExecutable(.{ .name = name, .root_module = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path(root), .link_libc = true, .imports = imports }) }); +} + +/// What unit-test runs of what these make. +pub const Tools = struct { + perf_gate_step: *std.Build.Step, + /// The perf program's build identity, which its own tests read too. + perf_options: *std.Build.Step.Options, + lib_test_step: *std.Build.Step, +}; + +/// The harnesses, the helix comparisons, the benches and the perf gate, the +/// syntax snapshots and their tests, the library's package test and history. +pub fn add(b: *std.Build, c: struct { + c_optimize: std.lang.Optimize, + core_module: *std.Build.Module, + enable_jpx: bool, + exe: *std.Build.Step.Compile, + ghostty_optimize: std.lang.Optimize, + ghostty_simd: bool, + ghostty_vt_for_tests: ?*std.Build.Module, + image_addon: *std.Build.Step.Compile, + /// core-test's core: the syntax module's tests run on it. + lean: core.Core, + no_pdf: ?*std.Build.Step, + optimize: std.lang.Optimize, + parts: core.Parts, + pdf_addon: ?*std.Build.Step.Compile, + platform: Platform, + prebuilt_shaders: bool, + shell_cfg: core.ShellConfig, + target: std.Build.ResolvedTarget, + test_filters: []const []const u8, + tracy: ?[]const u8, + tree_sitter_grammars: TreeSitterGrammars, + unit_profile: *std.Build.Step.Compile, +}) Tools { + const image_harness = program(b, "pardes-image-harness", "test/image_harness.zig", c.target, c.optimize, &.{}); + if (c.ghostty_vt_for_tests) |vt| image_harness.root_module.addImport("ghostty-vt", vt); + switch (c.target.result.os.tag) { + .freebsd, .netbsd, .openbsd => image_harness.root_module.linkSystemLibrary("util", .{}), + else => {}, + } + const run_image_harness = b.addRunArtifact(image_harness); + run_image_harness.addArtifactArg(c.exe); + run_image_harness.addArtifactArg(c.image_addon); + run_image_harness.addArg(if (c.platform == .gui) "gui" else "tui"); + run_image_harness.has_side_effects = true; + b.step("image-harness", "exercise native Kitty/SDL image rendering end to end").dependOn(&run_image_harness.step); + + // Kitty graphics through a terminal pane, end to end: a client in + // the pane's bash (and kitten icat, chafa when installed), a kitty + // terminal outside (tui) or the GPU capture (gui). test/kitty.zig + // is the same protocol at the core. + const kitty_client = program(b, "pardes-kitty-client", "test/kitty_client.zig", c.target, c.optimize, &.{}); + const kitty_harness = program(b, "pardes-kitty-harness", "test/kitty_harness.zig", c.target, c.optimize, &.{}); + if (c.ghostty_vt_for_tests) |vt| kitty_harness.root_module.addImport("ghostty-vt", vt); + switch (c.target.result.os.tag) { + .freebsd, .netbsd, .openbsd => kitty_harness.root_module.linkSystemLibrary("util", .{}), + else => {}, + } + const run_kitty_harness = b.addRunArtifact(kitty_harness); + run_kitty_harness.addArtifactArg(c.exe); + run_kitty_harness.addArtifactArg(kitty_client); + run_kitty_harness.addArg(if (c.platform == .gui) "gui" else "tui"); + run_kitty_harness.has_side_effects = true; + b.step("kitty-harness", "kitty graphics through a terminal pane end to end (a client inside, a kitty terminal or the GPU capture outside)").dependOn(&run_kitty_harness.step); + + const pdf_harness_step = b.step("pdf-harness", "exercise continuous PDF rendering, search, and sections navigation end to end"); + if (c.no_pdf) |s| pdf_harness_step.dependOn(s) else { + const run_pdf_harness = b.addRunArtifact(image_harness); + run_pdf_harness.addArtifactArg(c.exe); + run_pdf_harness.addArtifactArg(c.image_addon); + run_pdf_harness.addArg(if (c.platform == .gui) "gui" else "tui"); + run_pdf_harness.addArg("pdf"); + run_pdf_harness.addArtifactArg(c.pdf_addon.?); + run_pdf_harness.has_side_effects = true; + pdf_harness_step.dependOn(&run_pdf_harness.step); + } + + const hxdiff = program(b, "pardes-hxdiff", "test/hxdiff.zig", c.target, c.optimize, &.{.{ .name = "pardes", .module = c.core_module }}); + const run_hxdiff = b.addRunArtifact(hxdiff); + run_hxdiff.has_side_effects = true; + // Bare, it runs the checked-in suite (test/hxdiff.zig); `-- --parity` + // runs each case in a file pane and a pty pane and compares the two. + run_hxdiff.addPassthruArgs(); + run_hxdiff.setCwd(b.path(".")); + // the new line's indent per file type, against the reference helix + // with its grammars (test/hxcases/hx_indent.py): before the suite, + // whose count stays the last line + const run_hxindent = b.addRunArtifact(hxdiff); + run_hxindent.has_side_effects = true; + run_hxindent.addArgs(&.{ "--strict", "test/hxcases/indent.jsonl", "test/hxcases/indent-goldens.jsonl" }); + run_hxindent.setCwd(b.path(".")); + run_hxdiff.step.dependOn(&run_hxindent.step); + const hxdiff_step = b.step("hxdiff", "compare Helix results (-- --strict cases reference [waivers]; cases alone emits; --parity: a pty pane against a file pane)"); + hxdiff_step.dependOn(&run_hxdiff.step); + + // The same cases on the library (src/lib_editor.zig): test/hxlib.zig + // types them into an editor value and prints its results, which + // hxdiff holds against helix's goldens, or with `-- --parity` + // against the file pane, so the library cannot drift from either. + const hxlib = program(b, "pardes-hxlib", "test/hxlib.zig", c.target, c.optimize, &.{}); + hxlib.root_module.addImport("pardes-editor", core.editorModule(b, null, c.target, c.optimize, c.shell_cfg, .{ .themes = c.parts.themes, .ts = c.parts.ts, .uucode = c.parts.uucode, .mvzr = c.parts.mvzr, .vaxis = c.parts.vaxis })); + const run_hxlib = b.addRunArtifact(hxlib); + run_hxlib.addArgs(&.{ "test/hxcases/cases.jsonl", "test/hxcases/parity.jsonl" }); + run_hxlib.setCwd(b.path(".")); + run_hxlib.has_side_effects = true; + const run_hxdiff_lib = b.addRunArtifact(hxdiff); + run_hxdiff_lib.has_side_effects = true; + run_hxdiff_lib.addPrefixedFileArg("--actual=", run_hxlib.captureStdOut(.{})); + run_hxdiff_lib.addPassthruArgs(); + run_hxdiff_lib.setCwd(b.path(".")); + b.step("hxlib", "hxdiff's cases on the library, against helix's goldens (-- --parity: against the file pane)").dependOn(&run_hxdiff_lib.step); + + const helix_harness = b.option([]const u8, "helix-harness", "path to the reference hx-harness executable") orelse + b.graph.environ_map.get("HX_HARNESS") orelse "hx-harness"; + const reference = b.addSystemCommand(&.{helix_harness}); + reference.addFileArg(b.path("test/hxcases/cases.jsonl")); + reference.has_side_effects = true; + const reference_results = reference.captureStdOut(.{}); + const live_diff = b.addRunArtifact(hxdiff); + live_diff.addArg("--strict"); + live_diff.addFileArg(b.path("test/hxcases/cases.jsonl")); + live_diff.addFileArg(reference_results); + live_diff.addFileArg(b.path("test/hxcases/waivers.jsonl")); + live_diff.has_side_effects = true; + b.step("hxdiff-live", "compare the editor against a freshly run Helix reference").dependOn(&live_diff.step); + const update_reference = b.addUpdateSourceFiles(); + update_reference.addCopyFileToSource(reference_results, "test/hxcases/goldens.jsonl"); + update_reference.step.dependOn(&live_diff.step); + b.step("hxdiff-update", "replace checked-in Helix goldens after the live comparison passes").dependOn(&update_reference.step); + + // every helix-golf example, one case per step of its walkthrough + const run_hxgolf = b.addRunArtifact(hxdiff); + run_hxgolf.has_side_effects = true; + run_hxgolf.addArgs(&.{ "--strict", "test/hxcases/golf.jsonl", "test/hxcases/golf-goldens.jsonl", "test/hxcases/golf-waivers.jsonl" }); + run_hxgolf.setCwd(b.path(".")); + b.step("hxgolf", "compare the helix-golf examples against their Helix results").dependOn(&run_hxgolf.step); + + const lspbench = program(b, "pardes-lspbench", "test/lspbench.zig", c.target, .fast, &.{.{ .name = "pardes", .module = c.core_module }}); + const run_lspbench = b.addRunArtifact(lspbench); + run_lspbench.addPassthruArgs(); + run_lspbench.setCwd(b.path(".")); + run_lspbench.has_side_effects = true; + const lspbench_step = b.step("lspbench", "language-backend latency + feature matrix (-- [--json] [--check] [repo-root]), or one query (-- probe <kind> <file> <line>:<col> [arg] [--reps N])"); + lspbench_step.dependOn(&run_lspbench.step); + + const rollback_bench = program(b, "pardes-rollback-bench", "test/rollback_bench.zig", c.target, c.optimize, &.{.{ .name = "pardes", .module = c.core_module }}); + const run_rollback_bench = b.addRunArtifact(rollback_bench); + run_rollback_bench.has_side_effects = true; + b.step("rollback-bench", "a replica's rollback copy (walked state, pinned blobs, walk time) for a typical and a big session, and a fork of the big one (-Doptimize=ReleaseFast)").dependOn(&run_rollback_bench.step); + + const replicas = program(b, "pardes-replicas", "test/replicas.zig", c.target, c.optimize, &.{ .{ .name = "pardes", .module = c.core_module }, .{ .name = "term", .module = c.parts.term } }); + const run_replicas = b.addRunArtifact(replicas); + run_replicas.addPassthruArgs(); + run_replicas.has_side_effects = true; + b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); + + const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); + if (c.optimize != .fast) { + locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); + } else { + const locations_bench_module = b.createModule(.{ + .target = c.target, + .optimize = .fast, + .root_source_file = b.path("test/locations_bench.zig"), + .link_libc = true, + }); + locations_bench_module.addImport("pardes", c.core_module); + const locations_bench = b.addTest(.{ .root_module = locations_bench_module, .filters = &.{"locations benchmark cold and warm formatting"} }); + const run_locations_bench = b.addRunArtifact(locations_bench); + run_locations_bench.has_side_effects = true; + locations_bench_step.dependOn(&run_locations_bench.step); + } + + const perf_optimize: std.lang.Optimize = .fast; + const perf_options = b.addOptions(); + const perf_target = std.Target.Query.fromTarget(&c.target.result); + perf_options.addOption(PerfBuild, "identity", .{ + .compiler = builtin.zig_version_string, + .target = perf_target.zigTriple(b.allocator) catch @panic("out of memory"), + .cpu = perf_target.serializeCpuAlloc(b.allocator) catch @panic("out of memory"), + .driver_optimize = @tagName(perf_optimize), + .core_optimize = @tagName(c.optimize), + .c_optimize = @tagName(c.c_optimize), + .terminal_optimize = @tagName(c.ghostty_optimize), + .platform = @tagName(c.platform), + .grammars = @tagName(c.tree_sitter_grammars), + .mupdf = c.pdf_addon != null, + .jpx = c.enable_jpx, + .tracy = c.tracy != null, + .terminal_simd = c.ghostty_simd, + .prebuilt_shaders = c.platform == .gui and c.prebuilt_shaders, + }); + perf_options.addOptionPath("image_addon", c.image_addon.getEmittedBin()); + perf_options.addOption(bool, "has_pdf_addon", c.pdf_addon != null); + if (c.pdf_addon) |l| perf_options.addOptionPath("pdf_addon", l.getEmittedBin()); + const perf = program(b, "pardes-perf", "test/perf.zig", c.target, perf_optimize, &.{.{ .name = "pardes", .module = c.core_module }}); + // --live drives the real binary through a pty (test/e2e_harness.zig). + if (c.ghostty_vt_for_tests) |vt| perf.root_module.addImport("ghostty-vt", vt); + perf.root_module.addOptions("perf_options", perf_options); + const run_perf = b.addRunArtifact(perf); + run_perf.has_side_effects = true; + run_perf.addPassthruArgs(); + run_perf.setCwd(b.path(".")); + const perf_step = b.step("perf", "gesture latency or bounded terminal stress (-- [--json] [--reps N] [--base old.json] [--terminal-mib N])"); + perf_step.dependOn(&run_perf.step); + // The gate: the 50k-line file's gestures against the baseline this + // build shape recorded, each within 3x of its best. Record one with + // `zig build perf -Dplatform=P [-Doptimize=O] -- --only medium + // --reps 10 --json > test/perf-baseline-P-O.json` (a build that is + // known good). ponytail: the numbers are this machine's; another + // machine records its own. + const perf_gate = b.addRunArtifact(perf); + perf_gate.has_side_effects = true; + perf_gate.setCwd(b.path(".")); + perf_gate.addArgs(&.{ "--only", "medium", "--reps", "10", "--base", b.fmt("test/perf-baseline-{t}-{t}.json", .{ c.platform, c.optimize }), "--max-ratio", "3" }); + const perf_gate_step = b.step("perf-gate", "fail when a gesture on the 50k-line file takes over 3x its recorded baseline (test/perf-baseline-<platform>-<optimize>.json)"); + perf_gate_step.dependOn(&perf_gate.step); + + const fs_bench = program(b, "pardes-fs-bench", "test/fs_bench.zig", c.target, .fast, &.{.{ .name = "pardes", .module = c.core_module }}); + const run_fs_bench = b.addRunArtifact(fs_bench); + run_fs_bench.has_side_effects = true; + run_fs_bench.addPassthruArgs(); + run_fs_bench.setCwd(b.path(".")); + const fs_bench_step = b.step("fs-bench", "9P filesystem request cost and allocation count (-- [--json] [--reps N])"); + fs_bench_step.dependOn(&run_fs_bench.step); + + // The syntax module's own tests and snapshots, on the core without + // a terminal: its tests reach the editor's modes (modal.zig). + var syntax_cfg = c.lean; + syntax_cfg.root = "src/syntax.zig"; + const syntax_module = core.module(b, c.parts, syntax_cfg); + const syntax_runner = program(b, "pardes-syntax", "test/syntax.zig", c.target, c.optimize, &.{.{ .name = "syntax", .module = syntax_module }}); + const run_syntax = b.addRunArtifact(syntax_runner); + run_syntax.addPassthruArgs(); + run_syntax.has_side_effects = true; + b.step("syntax", "emit deterministic syntax snapshots (-- --bench: highlighting latency and allocations)").dependOn(&run_syntax.step); + const syntax_test = b.addTest(.{ + .root_module = syntax_module, + .filters = if (c.test_filters.len == 0) &.{"syntax "} else c.test_filters, + }); + const run_syntax_test = b.addRunArtifact(syntax_test); + run_syntax_test.has_side_effects = true; + const syntax_test_step = b.step("syntax-test", "test syntax correctness without building the editor"); + syntax_test_step.dependOn(&run_syntax_test.step); + if (testMatch(b, c.unit_profile, c.test_filters, syntax_test_step)) |check| check.addArtifactArg(syntax_test); + + // The library as a package that depends on pardes is given it + // (`library`): test/lib's own `zig build test`, over the packages + // this checkout has fetched. + const lib_test = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "test", "--pkg-dir", "../../zig-pkg" }); + lib_test.setCwd(b.path("test/lib")); + lib_test.has_side_effects = true; + const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/lib)"); + lib_test_step.dependOn(&lib_test.step); + + const history = b.addExecutable(.{ + .name = "pardes-history", + .root_module = b.createModule(.{ + .target = c.target, + .optimize = c.optimize, + .root_source_file = b.path("test/history.zig"), + }), + }); + const run_history = b.addRunArtifact(history); + run_history.addPassthruArgs(); + run_history.has_side_effects = true; + b.step("history", "compare command output and test/build runtime across jj revisions").dependOn(&run_history.step); + return .{ .perf_gate_step = perf_gate_step, .perf_options = perf_options, .lib_test_step = lib_test_step }; +} + +/// The PDF benches: the core over the pdf addon, a pane of it. +pub fn pdfBenches(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, core_module: *std.Build.Module, lib: *std.Build.Step.Compile, pointer_step: *std.Build.Step, scroll_step: *std.Build.Step) void { + const config = b.addOptions(); + config.addOption(bool, "release_fast_core", optimize == .fast); + config.addOption([]const u8, "core_optimize", @tagName(optimize)); + config.addOptionPath("pdf_addon", lib.getEmittedBin()); + for ([_]struct { step: *std.Build.Step, exe: []const u8, file: []const u8, optimize: std.lang.Optimize }{ + .{ .step = pointer_step, .exe = "pardes-pdf-pointer-bench", .file = "test/pdf_pointer_bench.zig", .optimize = .fast }, + .{ .step = scroll_step, .exe = "pardes-pdf-scroll-bench", .file = "test/pdf_scroll_bench.zig", .optimize = optimize }, + }) |bench| { + const exe = b.addExecutable(.{ .name = bench.exe, .root_module = b.createModule(.{ .target = target, .optimize = bench.optimize, .root_source_file = b.path(bench.file), .link_libc = true }) }); + exe.root_module.addImport("pardes", core_module); + exe.root_module.addOptions("pdf_bench_config", config); + const run = b.addRunArtifact(exe); + run.addPassthruArgs(); + run.setCwd(b.path(".")); + bench.step.dependOn(&run.step); + } +} diff --git a/docs/shared-libs.md b/docs/shared-libs.md index 73d6a73a..79d393e7 100644 --- a/docs/shared-libs.md +++ b/docs/shared-libs.md @@ -94,7 +94,7 @@ and gui columns are the two binaries. | GIF, BMP, TGA, PSD, HDR, PIC, PNM | stb_image | image panes | 1 → 1 | 22.3 KiB | Zig allocator (`zstbi.init`) | | Image resize | stb_image_resize | image panes (downscale) | 1 → 1 | 28.4 KiB | Zig allocator | | Image write (and its deflate) | stb_image_write | nothing | 1 → **0** (patched out of zstbi.c) | 30.6 KiB → 0 | removed | -| Inflate | zlib (allyourcodebase) | FreeType gzip, MuPDF `FlateDecode` | 1 → 1 (MuPDF links FreeType's, mupdf.zig) | 15.5 + 9.7 + 4.6 KiB | per stream: MuPDF's `fz_zlib_alloc`, FreeType's `FT_Memory` | +| Inflate | zlib (allyourcodebase) | FreeType gzip, MuPDF `FlateDecode` | 1 → 1 (MuPDF links FreeType's, build/mupdf.zig) | 15.5 + 9.7 + 4.6 KiB | per stream: MuPDF's `fz_zlib_alloc`, FreeType's `FT_Memory` | | Inflate | wuffs zlib/deflate | ghostty-vt: kitty `o=z` | 1 → 1 | 17.2 KiB | Zig allocator | | Inflate | stb_image's own | stb PNG | 1 / 2 → **0** | 1.1 / 2.3 KiB → 0 (most of it was inlined into the PNG decoder) | removed | | Fonts | FreeType (allyourcodebase) | gui glyph atlas, MuPDF (built against it, not its slim bundle) | 1 → 1 | 331 KiB | gui: `ui_malloc` (c_heap); MuPDF's library: `FT_MemoryRec` on fz | @@ -142,7 +142,7 @@ Text section: tty 61,369,343 → 61,294,855 bytes (**−74,488**); gui 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 + build/mupdf.zig builds all of `source/fitz`. They are reachable only through `fz_new_image_from_buffer`, which PDF rendering does not call. Dropping them means stubbing fitz's image-type dispatch (`image.c`) at build time. Left in. diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 738b4ff0..6b0e812a 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -41,10 +41,11 @@ system takes the SDK SDL needs with `-Dmacos-sdk=<path>`. A bare `zig build` installs into the prefix (`zig-out`, or `--prefix <dir>`) and copies the binaries into `~/.local/bin`; `-Dhome-install=false` leaves that copy out. Zig 0.17 keeps the prefix from the build script, so -`--prefix` alone no longer stops it. With `-Dplatform` binaries are not copied. The `image`, `pdf` and -`addons` steps also install into `$XDG_DATA_HOME/pardes/addons` (else -`~/.local/share/pardes/addons`); `-Dhome-install=false` skips that copy. -Pass `-Dplatform` and `-Dhome-install=false` while developing. Test, benchmark and run steps build what they need +`--prefix` alone no longer stops it. The `image`, `pdf` and `addons` steps +of a bare `zig build` also install into `$XDG_DATA_HOME/pardes/addons` +(else `~/.local/share/pardes/addons`); `-Dhome-install=false` skips that +copy too. With `-Dplatform` neither is copied, but `-Dhome-install=true` +copies the addons. Test, benchmark and run steps build what they need without installing. `pardes --version` prints `pardes <version>` (from `build.zig.zon`), plus the commit for release builds and the `~/.local` install, and on a second line the build's semantics hash, which a replica @@ -60,9 +61,8 @@ must share with its session; `pardes --help` lists every flag. [`-Djpx`], [bool, `true`: JPEG 2000, and with it scanned PDFs], [`-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], + [`-Dhome-install`], [bool: a bare `zig build` also copies the binaries into `~/.local/bin` and the addon steps theirs into `$XDG_DATA_HOME/pardes/addons`, default true; with `-Dplatform` only `true` copies, and the addons alone], [`-Dstamp-commit`], [bool: the git commit in `--version` and crash records; on for release builds and the `~/.local` install], - [`-Dtheme-animation`], [bool, `true`], [`-Dworkspace-tag`], [bool: draw the workspace tag row; on except for macOS, whose menu bar carries it], [`-Dmacos-sdk`], [path: the macOS SDK SDL's headers and frameworks come from, for a gui built for macOS elsewhere], [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; the shaders are sketchbook's (`dev/draw/shaders/`), and its `zig build shaders` refreshes the SPIR-V with glslc], @@ -170,8 +170,8 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt zig build syntax-test tree-sitter tests without building the editor zig build syntax deterministic per-byte highlighting snapshots zig build lib-test the library, from a package that depends on pardes (test/lib); -zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane); unit-test runs it too +zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane) zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/), and the T1 runner's short run of random 9P requests zig build process-test real sessions over their sockets: mounts, flags, shells (test/process/), diff --git a/tools/patch.zig b/tools/patch.zig new file mode 100644 index 00000000..a72624ff --- /dev/null +++ b/tools/patch.zig @@ -0,0 +1,39 @@ +//! One upstream file patched at make time, for build/patches.zig: +//! `patch <in> <out> [--append <file>] [<count> <old> <new>]...`. +//! Each `old` must occur exactly `count` times, and every occurrence is +//! replaced by `new`, in order; then `file` follows after an empty line. +//! An `old` that moved or doubled writes nothing and fails the step. +const std = @import("std"); + +pub fn main(init: std.process.Init) !void { + const io = init.io; + const arena = init.arena.allocator(); + var args = init.minimal.args.iterate(); + _ = args.skip(); + const in_path = args.next() orelse return error.Usage; + const out_path = args.next() orelse return error.Usage; + const cwd = std.Io.Dir.cwd(); + + var source = try cwd.readFileAlloc(io, in_path, arena, .limited(4 << 20)); + var append: []const u8 = ""; + var failed = false; + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--append")) { + append = try cwd.readFileAlloc(io, args.next() orelse return error.Usage, arena, .limited(1 << 20)); + continue; + } + const count = try std.fmt.parseInt(usize, arg, 10); + const old = args.next() orelse return error.Usage; + const new = args.next() orelse return error.Usage; + const found = std.mem.count(u8, source, old); + if (found != count) { + std.log.err("{s} changed: the text to replace occurs {d} times, not {d} (redo its patch in build/patches.zig):\n{s}", .{ in_path, found, count, old }); + failed = true; + continue; + } + source = try std.mem.replaceOwned(u8, arena, source, old, new); + } + if (failed) std.process.exit(1); + const out = if (append.len == 0) source else try std.mem.concat(arena, u8, &.{ source, "\n", append }); + try cwd.writeFile(io, .{ .sub_path = out_path, .data = out }); +} |
