diff options
| -rw-r--r-- | build.zig | 42 | ||||
| -rw-r--r-- | build/snap.zig | 6 | ||||
| -rw-r--r-- | src/Addon.zig | 13 | ||||
| -rw-r--r-- | src/Core.zig | 44 | ||||
| -rw-r--r-- | src/Effect.zig | 2 | ||||
| -rw-r--r-- | src/Kind.zig | 48 | ||||
| -rw-r--r-- | src/TerminalImages.zig | 55 | ||||
| -rw-r--r-- | src/addon_test.zig | 2 | ||||
| -rw-r--r-- | src/builtins.zig | 2 | ||||
| -rw-r--r-- | src/config.zig | 3 | ||||
| -rw-r--r-- | src/gui/gui.zig | 16 | ||||
| -rw-r--r-- | src/host_io.zig | 4 | ||||
| -rw-r--r-- | src/image.zig | 558 | ||||
| -rw-r--r-- | src/keys.zig | 1 | ||||
| -rw-r--r-- | src/look.zig | 3 | ||||
| -rw-r--r-- | src/macos.zig | 19 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 40 | ||||
| -rw-r--r-- | src/panes.zig | 3 | ||||
| -rw-r--r-- | src/pardes.zig | 5 | ||||
| -rw-r--r-- | src/pdf_view.zig | 177 | ||||
| -rw-r--r-- | src/surface.zig | 73 | ||||
| -rw-r--r-- | src/tape.zig | 6 | ||||
| -rw-r--r-- | src/tui/tui.zig | 16 | ||||
| -rw-r--r-- | test/behaviour/addons.zig | 71 | ||||
| -rw-r--r-- | test/fs_namespace.zig | 20 | ||||
| -rw-r--r-- | test/image_harness.zig | 20 | ||||
| -rw-r--r-- | test/kitty.zig | 12 | ||||
| -rw-r--r-- | test/mode.zig | 2 | ||||
| -rw-r--r-- | test/panes.zig | 56 | ||||
| -rw-r--r-- | test/pdf.zig | 13 | ||||
| -rw-r--r-- | test/process.zig | 7 | ||||
| -rw-r--r-- | test/process_test.zig | 4 | ||||
| -rw-r--r-- | test/session.zig | 2 | ||||
| -rw-r--r-- | test/snapshot.zig | 13 |
34 files changed, 577 insertions, 781 deletions
@@ -758,28 +758,29 @@ pub fn build(b: *std.Build) void { // override uucode on vaxis LAST so it wins over ghostty's build() wiring. vaxis_mod.addImport("uucode", uucode_mod); - // One PNG and one JPEG decoder (docs/shared-libs.md): ghostty's, wuffs, - // which ghostty-vt links for kitty graphics whatever pardes does (its - // decoders stay in through wuffs's function tables). Where it is in the - // build, image.zig decodes PNG and JPEG through it, and stb_image is - // compiled without them, so without the inflate only its PNG used. Its - // writer goes too, and the deflate it carries: pardes writes no image - // through stb. A fresh fetch keeps both: the flags and the patch are - // applied here, at build time. + // 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; - for ([_]?*std.Build.Step.Options{ opts, gui_opts }) |o| if (o) |x| x.addOption(bool, "wuffs_images", wuffs_mod != null); - if (wuffs_mod != null) { + { var sources: usize = 0; for (zstbi_mod.link_objects.items) |obj| switch (obj) { .c_source_file => |csf| { sources += 1; - const src = configureRead(b, io, zstbi_dep.builder.root, "src/zstbi.c", 1 << 20) catch @panic("read zstbi.c"); - const writer = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n"; - if (std.mem.count(u8, src, writer) != 1) std.debug.panic("zstbi.c changed at `{s}`: redo its patch in build.zig", .{writer}); - // zstbi.deinit still resets the writer's flip flag. - const patched = std.mem.replaceOwned(u8, b.allocator, src, writer, "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n") catch @panic("OOM"); - csf.file = b.addWriteFiles().add("zstbi.c", patched); - csf.flags = std.mem.concat(b.allocator, []const u8, &.{ csf.flags, &.{ "-DSTBI_NO_PNG", "-DSTBI_NO_JPEG" } }) catch @panic("OOM"); + 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 => {}, }; @@ -1171,6 +1172,7 @@ pub fn build(b: *std.Build) void { snap_build.addTty(b, .{ .exe = exe, + .image_addon = image_addon, .target = target, .optimize = optimize, .ghostty_vt = ghostty_vt_for_snap, @@ -1194,6 +1196,7 @@ pub fn build(b: *std.Build) void { } 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); @@ -1236,6 +1239,7 @@ pub fn build(b: *std.Build) void { if (enable_mupdf) { const run_pdf_harness = b.addRunArtifact(image_harness); run_pdf_harness.addArtifactArg(exe); + run_pdf_harness.addArtifactArg(image_addon); run_pdf_harness.addArg(if (platform == .gui) "gui" else "tui"); run_pdf_harness.addArg("pdf"); run_pdf_harness.has_side_effects = true; @@ -1521,6 +1525,9 @@ pub fn build(b: *std.Build) void { }); pane_module.addImport("pardes", core_module); pane_module.addImport("pardes_config", core_module.import_table.get("pardes_config").?); + const test_addons = b.addOptions(); + test_addons.addOptionPath("image", image_addon.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, PDF and namespace integration tests")); @@ -1563,6 +1570,7 @@ pub fn build(b: *std.Build) void { 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_module.addOptions("session_options", session_options); const behaviour_module = b.createModule(.{ .target = target, diff --git a/build/snap.zig b/build/snap.zig index ec705b5f..981aec64 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -2,6 +2,8 @@ const std = @import("std"); pub fn addTty(b: *std.Build, opts: struct { exe: *std.Build.Step.Compile, + /// The image addon, which every session that opens a picture loads. + image_addon: *std.Build.Step.Compile, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, ghostty_vt: ?*std.Build.Module, @@ -61,6 +63,7 @@ pub fn addTty(b: *std.Build, opts: struct { } const run_process_test = b.addRunArtifact(process_test); run_process_test.addArtifactArg(opts.exe); + run_process_test.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); run_process_test.addArg(if (opts.gui) "--backend=gui" else "--backend=tui"); run_process_test.addPassthruArgs(); run_process_test.has_side_effects = true; @@ -73,12 +76,14 @@ pub fn addTty(b: *std.Build, opts: struct { if (opts.gui) { const run_monkey_gui = b.addRunArtifact(process_test); run_monkey_gui.addArtifactArg(opts.exe); + run_monkey_gui.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); run_monkey_gui.addArgs(&.{ "--backend=gui", "window: a monkey" }); run_monkey_gui.setEnvironmentVariable("PARDES_GUI_MONKEY", "all"); run_monkey_gui.has_side_effects = true; monkey_gui_step.dependOn(&run_monkey_gui.step); const run_gui_golden = b.addRunArtifact(process_test); run_gui_golden.addArtifactArg(opts.exe); + run_gui_golden.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); run_gui_golden.addArgs(&.{ "--backend=gui", "window: its scenes" }); run_gui_golden.setEnvironmentVariable("PARDES_GUI_GOLDEN", b.graph.environ_map.get("PARDES_GUI_GOLDEN") orelse "check"); run_gui_golden.setCwd(b.path(".")); @@ -91,6 +96,7 @@ pub fn addTty(b: *std.Build, opts: struct { const run_snap = b.addRunArtifact(snap); run_snap.addArtifactArg(opts.exe); run_snap.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); + run_snap.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); run_snap.addPassthruArgs(); // scripts fork children and drive real ptys: never cached, never "up to date" run_snap.has_side_effects = true; diff --git a/src/Addon.zig b/src/Addon.zig index 4a387afa..6955741d 100644 --- a/src/Addon.zig +++ b/src/Addon.zig @@ -294,7 +294,7 @@ pub const Loaded = struct { name: []const u8 = "", version: u32 = 0, abi: u32 = 0, - /// The library file's BLAKE3; zero for a kind compiled in. + /// The library file's BLAKE3; zero for one never read. hash: [32]u8 = @splat(0), caps: Kind.Caps = .{}, path: []const u8 = "", @@ -372,7 +372,7 @@ pub fn take(r: *Kind.Registry, l: Loaded, except: []const u8) ?[]const u8 { r.n += 1; return e.why.slice(); } - e.why.set(if (e.compiledIn()) "static" else "loaded"); + e.why.set("loaded"); r.ops[r.n] = if (tape.replaying()) null else @ptrFromInt(l.ops); for (l.words) |w| { r.words[r.nwords] = .{ .kind = r.n, .arg = w.arg, .opens = w.opens }; @@ -462,7 +462,7 @@ pub fn run(p: *Pardes, id: usize, arg: ?[]const u8) void { if (a.len == 0) { var w: std.Io.Writer = .fixed(&said); w.writeAll("addons:") catch {}; - for (p.kinds.kinds[0..p.kinds.n]) |*e| if (!e.refused) w.print(" {s} {d}{s}", .{ e.nameOf(), e.version, if (e.compiledIn()) " (compiled in)" else "" }) catch {}; + for (p.kinds.kinds[0..p.kinds.n]) |*e| if (!e.refused) w.print(" {s} {d}", .{ e.nameOf(), e.version }) catch {}; return p.setMessage(id, w.buffered()); } const takes = "Addon takes load <path>, unload <name> or reload <name>"; @@ -478,7 +478,6 @@ pub fn run(p: *Pardes, id: usize, arg: ?[]const u8) void { } const k = p.kinds.byName(rest) orelse return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: no addon brought kind {s}", .{ op, rest }) catch takes); const e = &p.kinds.kinds[k]; - if (e.compiledIn()) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: {s} is compiled in", .{ op, rest }) catch takes); if (op == .reload) return p.emit(.{ .addon = .{ .op = .reload, .pane = @intCast(id), .arg = .from(e.path.slice()) } }); const n = openPanes(p, rest); if (n > 0) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon unload: {d} {s} pane{s} open", .{ n, rest, if (n == 1) " is" else "s are" }) catch takes); @@ -551,7 +550,7 @@ pub fn reopenWaiting(p: *Pardes, name: []const u8) usize { /// generation (a job the old one asked for is dropped as it answers). fn swap(p: *Pardes, l: Loaded, why: *Why) bool { const k = for (p.kinds.kinds[0..p.kinds.n], 0..) |*e, i| { - if (!e.refused and !e.compiledIn() and std.mem.eql(u8, e.path.slice(), l.path)) break @as(u8, @intCast(i)); + if (!e.refused and std.mem.eql(u8, e.path.slice(), l.path)) break @as(u8, @intCast(i)); } else return fail(why, "no addon was loaded from it", .{}); const name = p.kinds.kinds[k].nameOf(); if (l.why.len > 0) return fail(why, "{s}", .{l.why}); @@ -612,12 +611,12 @@ fn fail(why: *Why, comptime fmt: []const u8, args: anytype) bool { } /// /addons: `<kind> <version> <abi> <panes open> <path> <blake3> -/// static|loaded|refused: why` a line (`-` for no path, no hash). +/// loaded|refused: why` a line (`-` for no path, no hash). pub fn list(p: *const Pardes, out: *std.ArrayList(u8), gpa: std.mem.Allocator) !void { for (p.kinds.kinds[0..p.kinds.n]) |*e| { const name = if (e.nameOf().len > 0) e.nameOf() else std.fs.path.basename(e.path.slice()); try out.print(gpa, "{s} {d} {d}.{d} {d} {s} ", .{ name, e.version, e.abi >> 16, e.abi & 0xffff, if (e.refused) 0 else openPanes(p, name), if (e.path.len > 0) e.path.slice() else "-" }); - if (e.compiledIn()) try out.append(gpa, '-') else try out.print(gpa, "{x}", .{e.hash}); + if (std.mem.allEqual(u8, &e.hash, 0)) try out.append(gpa, '-') else try out.print(gpa, "{x}", .{e.hash}); try out.print(gpa, " {s}\n", .{e.why.slice()}); } } diff --git a/src/Core.zig b/src/Core.zig index 4584e395..b1195ac2 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -64,7 +64,6 @@ const font_picker = pardes.font_picker; const fonts = pardes.fonts; const frame_ns = pardes.frame_ns; const host_io = pardes.host_io; -const image = pardes.image; const layout = pardes.layout; const limits = memory.limits; const locations = @import("locations.zig"); @@ -2499,7 +2498,7 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane" try testing.expect(!first.tty_filter); const doc_id = p.freeSlot().?; - const doc = try pardes.Kind.open(p, doc_id, pardes.Kind.image, "/tmp/filter-inert.ppm", ""); + const doc = try pardes.Kind.open(p, doc_id, pardes.Kind.test_kind.of(p), "/tmp/filter-inert.ppm", ""); try testing.expect(!doc.tty_filter); try testing.expect(p.executeBuiltinLine(doc_id, "Filter")); try testing.expect(!doc.tty_filter); @@ -2669,7 +2668,7 @@ test "unknown Exec from a document runs as a command pane in its directory, type // A terminal free at a prompt in the same directory is not borrowed. p.setCwd(0, "/tmp/pardes-image-dir"); - const image_doc = try pardes.Kind.open(p, 1, pardes.Kind.image, "/tmp/pardes-image-dir/pic.ppm", null); + const image_doc = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pardes-image-dir/pic.ppm", null); try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_doc)); const dst = exec.execute(p, 1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun; try std.testing.expect(dst != 0 and dst != 1); @@ -2723,7 +2722,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} - _ = try pardes.Kind.open(p, 1, pardes.Kind.image, "/tmp/pic.ppm", null); + _ = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pic.ppm", null); const two = "def greet(name):\n return name\n\nprint(greet(\"x\"))\n"; const dst = exec.execute(p, 1, two) orelse return error.NoCommandPane; while (p.nextEffect()) |_| {} @@ -3071,7 +3070,7 @@ test "a command pane shows how its command ended, and the next command there run defer p.deinit(); while (p.nextEffect()) |_| {} p.setCwd(0, "/tmp/pardes-cmd"); - _ = try pardes.Kind.open(p, 1, pardes.Kind.image, "/tmp/pardes-cmd/pic.ppm", null); + _ = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pardes-cmd/pic.ppm", null); const dst = exec.execute(p, 1, "make -j8") orelse return error.NoCommandPane; while (p.nextEffect()) |_| {} @@ -3163,41 +3162,6 @@ test "a command pane shows how its command ended, and the next command there run try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long)); } -test "image dump restores source bytes renderer choices and exact custom tail" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - try pardes.panes.deinitPane(p, p.panes[0].?); - p.panes[0] = null; - - const source = "\x00embedded image bytes\xff"; - const pane = try pardes.Kind.open(p, 0, pardes.Kind.image, "/missing/restored-image.ppm", source); - pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false }; - if (pane.tag.own) |own| p.gpa.free(own); - pane.tag.own = try p.gpa.dupe(u8, " Keep Del"); - try dump.dumpState(p); - - const restored = try dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); - defer restored.deinit(); - const restored_pane = restored.panes[0].?; - const art = restored_pane.addon.?.art; - try std.testing.expect(art.glyph); - try std.testing.expectEqual(image.PaletteMode.terminal, art.palette); - try std.testing.expect(!art.ascii); - try std.testing.expect(restored_pane.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane)); - var kept: [64]u8 = undefined; - const slot = restored_pane.addon.?; - try std.testing.expectEqualSlices(u8, source, kept[0..image.kind.dump.?(slot.st, &kept, kept.len)]); - - // And dumped again, its bytes still there. - try dump.dumpState(restored); - const again = try dump.load(gpa, .{ .tty_only = true }, restored.dump_out.?, null); - defer again.deinit(); - // Loaded as a replica loads it: a placeholder holding the record. - try std.testing.expectEqualSlices(u8, source, again.panes[0].?.addon.?.record.?); -} - test "a terminal its program gave back takes command lines again" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{}); diff --git a/src/Effect.zig b/src/Effect.zig index 31187751..f5ee7ff9 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -615,7 +615,7 @@ test "Save reaches every tagline with text behind it and no other" { // An image's bytes on disk already are what they are: nothing of the // pane's own is unwritten, so the word is absent and inert. const img_id = p.freeSlot().?; - const img = try pardes.Kind.open(p, img_id, pardes.Kind.image, "/tmp/pardes-tag.ppm", ""); + const img = try pardes.Kind.open(p, img_id, pardes.Kind.test_kind.of(p), "/tmp/pardes-tag.ppm", ""); try std.testing.expectEqualStrings(" Term Collapse Del", tagline.curTail(img)); try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); try std.testing.expect(img.prompt != .save); diff --git a/src/Kind.zig b/src/Kind.zig index 241acf4b..60d86778 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -2,7 +2,7 @@ //! anything an addon (a library, Addon.zig) brings. Its records and //! functions are the C ABI of src/kinds/pardes_addon.h (translated, the //! one copy); this file is the core's side of it: the kinds a core has -//! (`Registry`, compiled in or brought, with their words and extensions), +//! (`Registry`, what libraries brought, with their words and extensions), //! and a pane's `Slot`, the state the core keeps round the kind's own. //! //! The core is deterministic and a kind is only the authority's: a @@ -47,8 +47,6 @@ comptime { // ---- the kinds a core has ---- pub const max_kinds = 16; -/// The kinds compiled in come first in every core: the image is kind 0. -pub const image: u8 = 0; /// Which of its functions a kind has: what both cores decide by. pub const Caps = packed struct(u8) { @@ -77,17 +75,13 @@ pub const Entry = struct { pub fn nameOf(e: *const Entry) []const u8 { return std.mem.sliceTo(&e.name, 0); } - pub fn compiledIn(e: *const Entry) bool { - return std.mem.allEqual(u8, &e.hash, 0); - } }; pub const Word = struct { kind: u8, name: Buf(32) = .{}, leader: Buf(8) = .{}, arg: u8 = 0, opens: u8 = 0, doc: Buf(96) = .{} }; pub const Ext = struct { kind: u8, ext: Buf(16) = .{} }; -/// A core's kinds: the compiled-in ones every core starts with, then what -/// libraries brought (Addon.zig), as data both cores hold alike; and each -/// one's code here, which a replica has none of for a library's. +/// A core's kinds: what libraries brought (Addon.zig), as data both cores +/// hold alike; and each one's code here, which a replica has none of. pub const Registry = struct { pub const replica = .{ .local = .{"ops"}, @@ -101,17 +95,9 @@ pub const Registry = struct { nexts: u8 = 0, ops: [max_kinds]?*const Ops = @splat(null), - /// The kinds compiled in. - pub fn init() Registry { - var r: Registry = .{}; - var words: [64]LoadedWord = undefined; - _ = r.take(loadedOf(&@import("image.zig").kind, "", @splat(0), &words), ""); - return r; - } - - /// The kinds compiled in and what the scan at start found. + /// What the scan at start found. pub fn started(found: []const Loaded) Registry { - var r: Registry = .init(); + var r: Registry = .{}; for (found) |l| _ = r.take(l, ""); return r; } @@ -793,6 +779,25 @@ fn textPane(p: *Pardes, id: usize, slot: *const Slot, name: []const u8, text: [] @import("exec.zig").placeNew(p, id, id, free, .doc); } +/// A kind for tests of the core's side of a kind's pane, no library: a +/// picture of one pixel over its body. +pub const test_kind = struct { + const pixel = [4]u8{ 255, 0, 0, 255 }; + fn picture(_: ?*anyopaque, win: [*c]const c.pa_window, out: [*c]c.pa_paint) callconv(.c) void { + out.*.placements[0] = std.mem.zeroInit(c.pa_placement, .{ .rgba = &pixel, .w = 1, .h = 1, .src = .{ .x = 0, .y = 0, .w = 1, .h = 1 }, .dst = .{ .x = 0, .y = 0, .w = win.*.cols, .h = win.*.rows } }); + out.*.n = 1; + } + const ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .name = "test".* ++ @as([12]u8, @splat(0)), .version = 1 }), .paint = picture }); + + /// Its index in `p`'s kinds, taken in at the first ask. + pub fn of(p: *Pardes) u8 { + if (p.kinds.byName("test")) |k| return k; + var words: [64]LoadedWord = undefined; + _ = p.kinds.take(loadedOf(&ops, "", @splat(0), &words), ""); + return p.kinds.n - 1; + } +}; + // ---- small things ---- pub fn Buf(comptime n: usize) type { @@ -824,14 +829,13 @@ test "a kind's head is checked before a core takes it, and a core's kinds are it }; var ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .version = 3 }), .paint = Fake.paint }); @memcpy(ops.head.name[0..5], "zzzab"); - var a: Registry = .init(); - var b: Registry = .init(); + var a: Registry = .{}; + var b: Registry = .{}; var words: [64]LoadedWord = undefined; try std.testing.expect(a.take(loadedOf(&ops, "", @splat(1), &words), "") == null); try std.testing.expect(a.byName("zzzab") != null); try std.testing.expect(b.byName("zzzab") == null); try std.testing.expectEqualStrings("refused: kind zzzab is here already", a.take(loadedOf(&ops, "", @splat(1), &words), "").?); - try std.testing.expectEqualStrings("refused: kind image is here already", b.take(loadedOf(&@import("image.zig").kind, "", @splat(1), &words), "").?); a.drop(a.byName("zzzab").?); try std.testing.expect(a.byName("zzzab") == null); } diff --git a/src/TerminalImages.zig b/src/TerminalImages.zig index 0aee6b52..c352c2a4 100644 --- a/src/TerminalImages.zig +++ b/src/TerminalImages.zig @@ -10,11 +10,12 @@ const std = @import("std"); const ghostty_vt = @import("ghostty-vt"); const pardes = @import("pardes.zig"); -const image = @import("image.zig"); +const zstbi = @import("zstbi"); +const wuffs = @import("wuffs"); const TerminalImages = @This(); const gfx = ghostty_vt.kitty.graphics; -const PixelRect = image.PixelRect; +const PixelRect = @import("surface.zig").RectPx; /// The bytes ghostty-vt may hold for one screen's images (it evicts the /// oldest past this): a 4K picture in RGBA, with room for a second. @@ -59,25 +60,25 @@ const PlaceholderRuns = struct { continue; } var run: ?gfx.unicode.IncompletePlacement = null; - var start: usize = 0; + var first: usize = 0; const cells = row.cells(.all); while (self.x < cells.len) : (self.x += 1) { const cell = &cells[self.x]; if (cell.codepoint() != gfx.unicode.placeholder) { - if (run) |done| return complete(row, start, done); + if (run) |done| return complete(row, first, done); continue; } const style = row.style(cell); const curr: gfx.unicode.IncompletePlacement = .init(&style, row.grapheme(cell) orelse &.{}); if (run) |*prev| { - if (!prev.append(&curr)) return complete(row, start, prev.*); + if (!prev.append(&curr)) return complete(row, first, prev.*); } else { run = curr.start(); - start = self.x; + first = self.x; } } self.advance(); - if (run) |done| return complete(row, start, done); + if (run) |done| return complete(row, first, done); } return null; } @@ -109,14 +110,48 @@ pub fn deinit(ti: *TerminalImages, gpa: std.mem.Allocator) void { } /// Accept PNG (`f=100`) as well as raw pixels: ghostty-vt built as a -/// library decodes none itself. stb_image does it, as for image panes. +/// library decodes none itself. wuffs does it (ghostty's, linked for it). pub fn installPngDecoder() void { ghostty_vt.sys.decode_png = &decodePng; } +/// The longest side a PNG is kept at: a pane is at most a screenful of +/// cells, and a multi-thousand-pixel picture only costs its memory. +const max_dim: u32 = 1280; + +/// stb_image_resize has its allocator (`start`): before, a PNG is refused. +var started = false; + +/// Once at startup and exit, with what the resize allocates from. +pub fn start(io: std.Io, gpa: std.mem.Allocator) void { + zstbi.init(io, gpa); + started = true; +} +pub fn stop() void { + started = false; + zstbi.deinit(); +} + fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeError!ghostty_vt.sys.Image { - const decoded = image.decode(gpa, bytes) orelse return error.InvalidData; - return .{ .width = @intCast(decoded.w), .height = @intCast(decoded.h), .data = decoded.rgba }; + if (!started) return error.InvalidData; + // Bounded before decoding: a few KB of PNG can name gigapixels. The + // signature, then IHDR first: its length, type, width and height. + if (bytes.len < 24 or !std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") or !std.mem.eql(u8, bytes[12..16], "IHDR")) return error.InvalidData; + const w = std.mem.readInt(u32, bytes[16..20], .big); + const h = std.mem.readInt(u32, bytes[20..24], .big); + if (@as(u64, w) * h > pardes.memory.limits.image_decode_pixels) return error.InvalidData; + const got = wuffs.png.decode(gpa, bytes) catch return error.InvalidData; + if (got.data.len != @as(usize, got.width) * got.height * 4) { + gpa.free(got.data); + return error.InvalidData; + } + const longest = @max(got.width, got.height); + if (longest <= max_dim) return .{ .width = got.width, .height = got.height, .data = got.data }; + defer gpa.free(got.data); + const img: zstbi.Image = .{ .data = got.data, .width = got.width, .height = got.height, .num_components = 4, .bytes_per_component = 1, .bytes_per_row = got.width * 4, .is_hdr = false }; + var scaled = img.resize(@intCast(@max(1, @as(u64, got.width) * max_dim / longest)), @intCast(@max(1, @as(u64, got.height) * max_dim / longest))); + defer scaled.deinit(); + return .{ .width = scaled.width, .height = scaled.height, .data = gpa.dupe(u8, scaled.data) catch return error.InvalidData }; } /// Draw the active screen's images. `rows_of[v]` is the body row the diff --git a/src/addon_test.zig b/src/addon_test.zig index 9acd319b..a4788109 100644 --- a/src/addon_test.zig +++ b/src/addon_test.zig @@ -45,8 +45,6 @@ fn run(io: std.Io, gpa: std.mem.Allocator, lib: []const u8, script_path: ?[]cons // The regions and the C libraries' allocators a frontend sets up. const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); - pardes.image.start(io, allocs.image); - defer pardes.image.stop(); pardes.syntax.start(allocs.tree_sitter); defer pardes.syntax.stop(); const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .image_allocator = allocs.image, .pdf_allocator = allocs.pdf, .tree_sitter_allocator = allocs.tree_sitter, .frame_allocator = allocs.frame }); diff --git a/src/builtins.zig b/src/builtins.zig index 643fe5bb..68730166 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1023,7 +1023,7 @@ pub const Palette = struct { pub fn run(c: Ctx) void { const art = &(c.pane.addon orelse return).art; if (c.arg != null) { - const want = stateArg(c, panes.Image.PaletteMode, "Palette", "commodore or terminal") orelse return; + const want = stateArg(c, pardes.Placement.Art.Palette, "Palette", "commodore or terminal") orelse return; if (want == art.palette) return; } art.palette = if (art.palette == .commodore) .terminal else .commodore; diff --git a/src/config.zig b/src/config.zig index ae9b774a..f9fd336f 100644 --- a/src/config.zig +++ b/src/config.zig @@ -301,7 +301,6 @@ pub const dir_pane_builtins_str = "Get Term Collapse Del"; pub const tag_normal = " "; pub const tag_insert = "^"; pub const tag_tty = "$"; -pub const tag_image = "img"; pub const command_line: []const Chord = &.{.{ .cp = ':' }}; @@ -468,8 +467,6 @@ pub const pane_addr = "@p"; pub const url_schemes = [_][]const u8{ "http://", "https://" }; -pub const image_exts = [_][]const u8{ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ppm", ".pgm", ".tga" }; - // Match Helix's fallback for unknown languages and languages without line comments. pub const comment_token_default = "#"; pub const comment_tokens: []const struct { exts: []const []const u8, token: []const u8 } = &.{ diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 0d8c53ca..1125ff03 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2030,12 +2030,16 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ const have: ?*replica.Have = if (far) &have_store else null; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); - pardes.image.start(io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.start(io, allocs.image); + pardes.pdf.start(allocs.pdf); + } pardes.syntax.start(allocs.tree_sitter); defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.stop(); + pardes.pdf.stop(); + } pardes.syntax.stop(); } var o = opts_in; @@ -5028,11 +5032,11 @@ fn validImageBytes(place: pardes.Placement) ?u32 { /// Where the placement's pixels go in its cells: where it says, or fitted /// there (no larger than it is, at the top left). -fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.image.NativeGeometry { +fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.NativeGeometry { if (place.at) |at| return .{ .src = place.src, .dst = at }; const bound_w = std.math.mul(u32, place.dst.w, g.cell_w) catch return null; const bound_h = std.math.mul(u32, place.dst.h, g.cell_h) catch return null; - const fit = pardes.image.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null; + const fit = pardes.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null; return .{ .src = place.src, .dst = fit.dst }; } diff --git a/src/host_io.zig b/src/host_io.zig index 2320077e..9cc34465 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -171,8 +171,8 @@ pub fn testClock() ?u64 { /// on `allocs` (pardes.memory.init); PDF pages render on lanes off the /// loop (pdf_view.workers). `stopWorkers` is its defer. pub fn startWorkers(io: std.Io, allocs: pardes.memory.Allocators) void { - pardes.image.start(io, allocs.image); if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.start(io, allocs.image); pardes.pdf.start(allocs.pdf); pardes.panes.Pdf.workers = io; } @@ -180,8 +180,8 @@ pub fn startWorkers(io: std.Io, allocs: pardes.memory.Allocators) void { } pub fn stopWorkers() void { - pardes.image.stop(); if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.stop(); pardes.panes.Pdf.dropKept(); pardes.pdf.stop(); } diff --git a/src/image.zig b/src/image.zig deleted file mode 100644 index b5efc5fd..00000000 --- a/src/image.zig +++ /dev/null @@ -1,558 +0,0 @@ -//! Image decoding, pixel placement, and the image pane. -const std = @import("std"); -const builtin = @import("builtin"); -const zstbi = @import("zstbi"); -const pdf_enabled = @import("pardes_config").mupdf; -const pardes = @import("pardes.zig"); -const Kind = @import("Kind.zig"); -const config = @import("config.zig"); -const filesystem = @import("fs.zig"); -/// cap the longest side before keeping/transmitting: a pane is at most a -/// screenful of cells, multi-thousand-pixel photos waste decode/transmit time -const MAX_DIM: u32 = 1280; - -pub const PaletteMode = pardes.Placement.Art.Palette; - -/// How a native pixel attachment is placed in its pane body. `contain` is the -/// historical image-pane policy: shrink only when necessary and keep the -/// image at the top left. The axis-specific modes may enlarge, letterbox the -/// unconstrained axis, or crop it when it overflows. -pub const NativeFit = if (pdf_enabled) enum { contain, width, height } else enum { contain }; - -pub const PixelRect = struct { - x: u32 = 0, - y: u32 = 0, - w: u32 = 0, - h: u32 = 0, -}; - -pub const PixelPoint = struct { x: u32, y: u32 }; - -/// Source pixels and their destination inside a pane body's pixel rectangle. -/// Both rectangles are half-open. Rounding is always toward the inside, so a -/// backend can draw this result without a backend-specific overflow clip. -pub const NativeGeometry = struct { - src: PixelRect, - dst: PixelRect, - - /// Map a destination pixel back into the retained source crop. This is the - /// same integer transform the texture rectangle describes; points in a - /// letterbox return null. - pub fn sourcePoint(self: NativeGeometry, x: u32, y: u32) ?PixelPoint { - if (self.src.w == 0 or self.src.h == 0 or self.dst.w == 0 or self.dst.h == 0) return null; - if (x < self.dst.x or y < self.dst.y) return null; - const dx = x - self.dst.x; - const dy = y - self.dst.y; - if (dx >= self.dst.w or dy >= self.dst.h) return null; - return .{ - .x = self.src.x + @as(u32, @intCast(@as(u64, dx) * self.src.w / self.dst.w)), - .y = self.src.y + @as(u32, @intCast(@as(u64, dy) * self.src.h / self.dst.h)), - }; - } -}; - -fn panOffset(overflow: u32, pan: u16) u32 { - if (overflow == 0 or pan == 0) return 0; - if (pan == std.math.maxInt(u16)) return overflow; - // Round, rather than truncate, so the midpoint is the visual midpoint. - return @intCast((@as(u64, overflow) * pan + std.math.maxInt(u16) / 2) / std.math.maxInt(u16)); -} - -fn fitWidth(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_y: u16) ?NativeGeometry { - const scaled_h = @as(u64, src_h) * body_w; - if (scaled_h <= @as(u64, body_h) * src_w) { - const full_h: u32 = @intCast(@max(1, scaled_h / src_w)); - return .{ - .src = .{ .w = src_w, .h = src_h }, - .dst = .{ .y = (body_h - full_h) / 2, .w = body_w, .h = full_h }, - }; - } - - // Retain the largest whole source-pixel crop which cannot extend beyond - // the body at this scale. The sub-pixel remainder becomes at most a small - // centered letterbox instead of leaking into an adjacent cell in Kitty. - const crop_h_wide = @as(u64, body_h) * src_w / body_w; - if (crop_h_wide == 0) return null; - const crop_h: u32 = @min(src_h, @as(u32, @intCast(crop_h_wide))); - const dst_h: u32 = @min(body_h, @max(1, @as(u32, @intCast(@as(u64, crop_h) * body_w / src_w)))); - return .{ - .src = .{ - .y = panOffset(src_h - crop_h, pan_y), - .w = src_w, - .h = crop_h, - }, - .dst = .{ .y = (body_h - dst_h) / 2, .w = body_w, .h = dst_h }, - }; -} - -fn fitHeight(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_x: u16) ?NativeGeometry { - const scaled_w = @as(u64, src_w) * body_h; - if (scaled_w <= @as(u64, body_w) * src_h) { - const full_w: u32 = @intCast(@max(1, scaled_w / src_h)); - return .{ - .src = .{ .w = src_w, .h = src_h }, - .dst = .{ .x = (body_w - full_w) / 2, .w = full_w, .h = body_h }, - }; - } - - const crop_w_wide = @as(u64, body_w) * src_h / body_h; - if (crop_w_wide == 0) return null; - const crop_w: u32 = @min(src_w, @as(u32, @intCast(crop_w_wide))); - const dst_w: u32 = @min(body_w, @max(1, @as(u32, @intCast(@as(u64, crop_w) * body_h / src_h)))); - return .{ - .src = .{ - .x = panOffset(src_w - crop_w, pan_x), - .w = crop_w, - .h = src_h, - }, - .dst = .{ .x = (body_w - dst_w) / 2, .w = dst_w, .h = body_h }, - }; -} - -/// Compute native image placement without floating point. Source dimensions -/// are limited to u32 because SDL's texture API and Kitty's crop parameters -/// cannot describe anything larger. Kitty applies the stricter u16 check at -/// its protocol boundary. -pub fn nativeGeometry( - iw: usize, - ih: usize, - body_pixel_w: u32, - body_pixel_h: u32, - fit: NativeFit, - pan_x: u16, - pan_y: u16, -) ?NativeGeometry { - if (comptime !pdf_enabled) { - return containGeometry(iw, ih, body_pixel_w, body_pixel_h); - } - if (iw == 0 or ih == 0 or body_pixel_w == 0 or body_pixel_h == 0 or - iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null; - - const src_w: u32 = @intCast(iw); - const src_h: u32 = @intCast(ih); - return switch (fit) { - .width => fitWidth(src_w, src_h, body_pixel_w, body_pixel_h, pan_y), - .height => fitHeight(src_w, src_h, body_pixel_w, body_pixel_h, pan_x), - // Pan is not contain's: it keeps the top-left placement. - .contain => containGeometry(iw, ih, body_pixel_w, body_pixel_h), - }; -} - -/// The ordinary image-pane policy: shrunk only when it must be, at the top -/// left. The scale ratios are compared without floating point: the tighter -/// bound is exact, the other rounded inward. -pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeometry { - if (iw == 0 or ih == 0 or max_w == 0 or max_h == 0 or - iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null; - - const src_w: u32 = @intCast(iw); - const src_h: u32 = @intCast(ih); - if (src_w <= max_w and src_h <= max_h) return .{ - .src = .{ .w = src_w, .h = src_h }, - .dst = .{ .w = src_w, .h = src_h }, - }; - const dst: PixelRect = if (@as(u64, max_w) * src_h <= @as(u64, max_h) * src_w) - .{ - .w = max_w, - .h = @intCast(@max(1, @as(u64, src_h) * max_w / src_w)), - } - else - .{ - .w = @intCast(@max(1, @as(u64, src_w) * max_h / src_h)), - .h = max_h, - }; - return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst }; -} - -test "native image contain keeps aspect, bounds, top-left, and small-image size" { - try std.testing.expectEqual(PixelRect{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst); - try std.testing.expectEqual(PixelRect{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst); - try std.testing.expectEqual(PixelRect{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst); - try std.testing.expect(containGeometry(17, 9, 0, 40) == null); - - const odd = containGeometry(403, 211, 101, 47).?; - try std.testing.expectEqual(PixelRect{ .w = 89, .h = 47 }, odd.dst); - try std.testing.expectEqual(PixelRect{ .w = 403, .h = 211 }, odd.src); -} - -test "native fit width handles portrait crop, pan extrema, and landscape letterbox" { - if (comptime !pdf_enabled) return; - const top = nativeGeometry(600, 1000, 800, 600, .width, 0, 0).?; - try std.testing.expectEqual(PixelRect{ .w = 600, .h = 450 }, top.src); - try std.testing.expectEqual(PixelRect{ .w = 800, .h = 600 }, top.dst); - - const middle = nativeGeometry(600, 1000, 800, 600, .width, 0, 32768).?; - try std.testing.expectEqual(@as(u32, 275), middle.src.y); - const bottom = nativeGeometry(600, 1000, 800, 600, .width, 65535, 65535).?; - try std.testing.expectEqual(@as(u32, 550), bottom.src.y); - - const landscape = nativeGeometry(1000, 600, 800, 600, .width, 0, 65535).?; - try std.testing.expectEqual(PixelRect{ .w = 1000, .h = 600 }, landscape.src); - try std.testing.expectEqual(PixelRect{ .y = 60, .w = 800, .h = 480 }, landscape.dst); -} - -test "native fit height handles portrait letterbox and landscape crop" { - if (comptime !pdf_enabled) return; - const portrait = nativeGeometry(600, 1000, 800, 600, .height, 65535, 0).?; - try std.testing.expectEqual(PixelRect{ .w = 600, .h = 1000 }, portrait.src); - try std.testing.expectEqual(PixelRect{ .x = 220, .w = 360, .h = 600 }, portrait.dst); - - const left = nativeGeometry(1000, 600, 800, 600, .height, 0, 0).?; - try std.testing.expectEqual(PixelRect{ .w = 800, .h = 600 }, left.src); - try std.testing.expectEqual(PixelRect{ .w = 800, .h = 600 }, left.dst); - const right = nativeGeometry(1000, 600, 800, 600, .height, 65535, 0).?; - try std.testing.expectEqual(@as(u32, 200), right.src.x); -} - -test "native fit odd ratios round inward and map points through letterboxes and crops" { - if (comptime !pdf_enabled) return; - const width = nativeGeometry(403, 211, 101, 47, .width, 0, 32768).?; - try std.testing.expectEqual(PixelRect{ .y = 12, .w = 403, .h = 187 }, width.src); - try std.testing.expectEqual(PixelRect{ .w = 101, .h = 46 }, width.dst); - const mapped = width.sourcePoint(100, 45).?; - try std.testing.expect(mapped.x < width.src.x + width.src.w); - try std.testing.expect(mapped.y < width.src.y + width.src.h); - try std.testing.expect(width.sourcePoint(101, 46) == null); - - const height = nativeGeometry(403, 211, 101, 47, .height, 32768, 0).?; - try std.testing.expectEqual(PixelRect{ .w = 403, .h = 211 }, height.src); - try std.testing.expectEqual(PixelRect{ .x = 6, .w = 89, .h = 47 }, height.dst); - try std.testing.expect(height.sourcePoint(5, 20) == null); - try std.testing.expect(height.sourcePoint(6, 20) != null); -} - -test "native geometry rejects dimensions which its backend contract cannot represent" { - try std.testing.expect(containGeometry(0, 10, 20, 20) == null); - if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null); - if (comptime pdf_enabled) { - try std.testing.expect(nativeGeometry(10, 10, 0, 20, .width, 0, 0) == null); - if (@bitSizeOf(usize) > 32) - try std.testing.expect(nativeGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20, .height, 0, 0) == null); - } -} - -test "native geometry is total at extreme accepted aspect ratios" { - if (comptime !pdf_enabled) return; - const largest = std.math.maxInt(u32); - try std.testing.expect(nativeGeometry(1, largest, largest, 1, .width, 0, 65535) == null); - try std.testing.expect(nativeGeometry(largest, 1, 1, largest, .height, 65535, 0) == null); - - const wide = nativeGeometry(largest, 1, largest, 1, .width, 0, 0).?; - try std.testing.expectEqual(PixelRect{ .w = largest, .h = 1 }, wide.dst); - const tall = nativeGeometry(1, largest, 1, largest, .height, 0, 0).?; - try std.testing.expectEqual(PixelRect{ .w = 1, .h = largest }, tall.dst); -} - -/// call once at startup / exit (stb_image's allocator shim) -pub fn start(io: std.Io, gpa: std.mem.Allocator) void { - zstbi.init(io, gpa); - decode_gpa = gpa; - started = true; -} -pub fn stop() void { - started = false; - decode_gpa = null; - zstbi.deinit(); -} - -/// What a decode allocates from: the image region `start` was given. -var decode_gpa: ?std.mem.Allocator = null; - -/// stb_image has its allocator (`start`): before, nothing of it may run. -var started = false; - -extern fn stbi_info_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int) c_int; - -/// stb_image's header reader. -fn stbiInfo(bytes: []const u8, w: *c_int, h: *c_int, c: *c_int) bool { - return stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), w, h, c) == 1; -} - -/// PNG and JPEG are ghostty's decoders (wuffs, which ghostty-vt links for -/// kitty graphics) wherever ghostty-vt is in the build; stb_image is then -/// compiled without them, and without the inflate only its PNG used -/// (build.zig, docs/shared-libs.md). Other formats, and builds without -/// ghostty-vt, are stb_image's. -const wuffs_images = @hasDecl(@import("pardes_config"), "wuffs_images") and @import("pardes_config").wuffs_images; -const wuffs = if (wuffs_images) @import("wuffs") else struct {}; - -const Format = enum { png, jpeg, other }; - -fn format(bytes: []const u8) Format { - if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) return .png; - if (bytes.len >= 3 and bytes[0] == 0xff and bytes[1] == 0xd8 and bytes[2] == 0xff) return .jpeg; - return .other; -} - -const Size = struct { w: usize, h: usize }; - -/// An image's size from its header alone, before anything is decoded. -fn headerSize(bytes: []const u8) ?Size { - if (comptime wuffs_images) switch (format(bytes)) { - .png => { - // The signature, then IHDR first: length, type, width, height. - if (bytes.len < 24 or !std.mem.eql(u8, bytes[12..16], "IHDR")) return null; - return .{ .w = std.mem.readInt(u32, bytes[16..20], .big), .h = std.mem.readInt(u32, bytes[20..24], .big) }; - }, - .jpeg => return jpegSize(bytes), - .other => {}, - }; - var iw: c_int = 0; - var ih: c_int = 0; - var ic: c_int = 0; - if (!stbiInfo(bytes, &iw, &ih, &ic)) return null; - return .{ .w = @intCast(@max(0, iw)), .h = @intCast(@max(0, ih)) }; -} - -/// A JPEG's size, from its first start-of-frame segment (any SOFn but the -/// DHT, JPG and DAC markers that share their range). -fn jpegSize(bytes: []const u8) ?Size { - var at: usize = 2; - while (at + 4 <= bytes.len) { - if (bytes[at] != 0xff) return null; - const marker = bytes[at + 1]; - // Fill bytes, and the markers that stand alone. - if (marker == 0xff) { - at += 1; - continue; - } - if (marker == 0x01 or (marker >= 0xd0 and marker <= 0xd7)) { - at += 2; - continue; - } - const len = std.mem.readInt(u16, bytes[at + 2 ..][0..2], .big); - if (len < 2) return null; - const sof = marker >= 0xc0 and marker <= 0xcf and marker != 0xc4 and marker != 0xc8 and marker != 0xcc; - if (sof) { - if (at + 9 > bytes.len) return null; - return .{ .w = std.mem.readInt(u16, bytes[at + 7 ..][0..2], .big), .h = std.mem.readInt(u16, bytes[at + 5 ..][0..2], .big) }; - } - if (marker == 0xda) return null; // scan data before any frame - at += 2 + len; - } - return null; -} - -/// Whether `bytes` are an image `decode` can read, from its header alone. -pub fn readable(bytes: []const u8) bool { - if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return false; - var w: c_int = 0; - var h: c_int = 0; - var c: c_int = 0; - if (!started) return true; // ponytail: no stb_image yet (a unit test), so no judging - if (comptime wuffs_images) if (format(bytes) != .other) return headerSize(bytes) != null; - return stbiInfo(bytes, &w, &h, &c); -} - -/// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the -/// pane then simply shows a blank body. -const Decoded = struct { rgba: []u8, w: usize, h: usize }; - -pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?Decoded { - // stb_image allocates through what `start` gave it: before that, a call - // jumps through a null pointer (a terminal's PNG in a core no shell set up). - if (!started) return null; - if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null; - // Bounded before decoding: a few KB of PNG can name gigapixels. - const size = headerSize(bytes) orelse return null; - const pixels = std.math.mul(usize, size.w, size.h) catch return null; - if (pixels > @import("memory.zig").limits.image_decode_pixels) return null; - if (comptime wuffs_images) switch (format(bytes)) { - inline .png, .jpeg => |f| { - const got = @field(wuffs, @tagName(f)).decode(gpa, bytes) catch return null; - defer gpa.free(got.data); - if (got.data.len != @as(usize, got.width) * got.height * 4) return null; - return finish(gpa, .{ - .data = got.data, - .width = got.width, - .height = got.height, - .num_components = 4, - .bytes_per_component = 1, - .bytes_per_row = got.width * 4, - .is_hdr = false, - }); - }, - .other => {}, - }; - var img = zstbi.Image.loadFromMemory(bytes, 4) catch return null; // 4 = RGBA - defer img.deinit(); - return finish(gpa, img); -} - -/// The decoded RGBA, scaled to MAX_DIM at most, in a gpa copy. -fn finish(gpa: std.mem.Allocator, img: zstbi.Image) ?Decoded { - var scaled: ?zstbi.Image = null; - defer if (scaled) |*s| s.deinit(); - const longest = @max(img.width, img.height); - const src: *const zstbi.Image = if (longest > MAX_DIM) blk: { - const nw = @max(1, img.width * MAX_DIM / longest); - const nh = @max(1, img.height * MAX_DIM / longest); - scaled = img.resize(nw, nh); - break :blk &scaled.?; - } else &img; - const rgba = gpa.dupe(u8, src.data) catch return null; - return .{ .rgba = rgba, .w = src.width, .h = src.height }; -} - -test "PNG and JPEG decode through wuffs, sized from their headers first; other formats through stb_image" { - const gpa = std.testing.allocator; - start(std.testing.io, gpa); - defer stop(); - const dec = std.base64.standard.Decoder; - const Fixture = struct { b64: []const u8, w: usize, h: usize, rgb: [3]u8, tolerance: u8 }; - const fixtures = [_]Fixture{ - // 4x2, red left, blue right (a hand-built PNG). - .{ .b64 = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAIAAADwyuo0AAAAE0lEQVR4nGP4z8AARGDiPwMyBwBnsgf5Q2OaZwAAAABJRU5ErkJggg==", .w = 4, .h = 2, .rgb = .{ 255, 0, 0 }, .tolerance = 0 }, - // 16x8 of (200,30,30), baseline and progressive (Pillow, quality 95). - .{ .b64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAAIABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5Dooor8LP9VD/2Q==", .w = 16, .h = 8, .rgb = .{ 200, 30, 30 }, .tolerance = 6 }, - .{ .b64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wgARCAAIABADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAVAQEBAAAAAAAAAAAAAAAAAAAGCP/aAAwDAQACEAMQAAABkIC1V//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAQUCP//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Bf//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEABj8CP//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAT8hP//aAAwDAQACAAMAAAAQA//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Qf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Qf//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAT8QP//Z", .w = 16, .h = 8, .rgb = .{ 200, 30, 30 }, .tolerance = 6 }, - }; - for (fixtures) |f| { - const bytes = try gpa.alloc(u8, try dec.calcSizeForSlice(f.b64)); - defer gpa.free(bytes); - try dec.decode(bytes, f.b64); - try std.testing.expect(readable(bytes)); - const size = headerSize(bytes).?; - try std.testing.expectEqual(Size{ .w = f.w, .h = f.h }, size); - const got = decode(gpa, bytes) orelse return error.NotDecoded; - defer gpa.free(got.rgba); - try std.testing.expectEqual(f.w, got.w); - try std.testing.expectEqual(f.h, got.h); - for (got.rgba[0..3], f.rgb) |have, want| try std.testing.expect(@max(have, want) - @min(have, want) <= f.tolerance); - try std.testing.expectEqual(@as(u8, 255), got.rgba[3]); - } - // A PPM still goes through stb_image. - const ppm = "P6\n2 1\n255\n\x0d\x4d\xe7\x0d\x4d\xe7"; - try std.testing.expectEqual(Format.other, format(ppm)); - const got = decode(gpa, ppm) orelse return error.NotDecoded; - defer gpa.free(got.rgba); - try std.testing.expectEqualSlices(u8, &.{ 0x0d, 0x4d, 0xe7, 255 }, got.rgba[0..4]); - // Truncated headers are no image, never a read past the end. - try std.testing.expect(headerSize("\x89PNG\r\n\x1a\n\x00\x00") == null); - try std.testing.expect(headerSize("\xff\xd8\xff\xe0\x00\x10JFIF") == null); - try std.testing.expect(decode(gpa, "\xff\xd8\xff\xe0\x00\x10JFIF") == null); -} - -// ---- the image kind (kinds/pardes_addon.h), compiled in ---- - -/// A picture: its file's bytes decoded on a job, shown as one placement -/// over the body that a frontend fits (or draws as glyph art). -pub const kind: Kind.Ops = std.mem.zeroInit(Kind.Ops, .{ - .head = std.mem.zeroInit(Kind.c.pa_head, .{ - .size = @sizeOf(Kind.c.pa_head), - .abi = Kind.abi, - .name = "image".* ++ @as([11]u8, @splat(0)), - .version = 1, - .exts = exts, - }), - .open = open, - .paint = paint, - .job_run = jobRun, - .job_done = jobDone, - .dump = dump, - .load = load, -}); - -const exts = blk: { - var all: []const u8 = ""; - for (config.image_exts, 0..) |e, i| all = all ++ (if (i == 0) "" else " ") ++ e; - break :blk all ++ ""; -}; - -const State = struct { - path: []const u8, - /// The file's bytes, as a dump keeps them. - raw: []const u8 = &.{}, - rgba: []const u8 = &.{}, - w: u32 = 0, - h: u32 = 0, -}; - -fn alloc(comptime T: type, n: usize) ?[]T { - const mem = Kind.api.alloc.?(n * @sizeOf(T)) orelse return null; - return @as([*]T, @ptrCast(@alignCast(mem)))[0..n]; -} - -fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque { - const st = &(alloc(State, 1) orelse return null)[0]; - const p = if (path == null) "" else std.mem.span(path); - const kept = alloc(u8, p.len) orelse return null; - @memcpy(kept, p); - st.* = .{ .path = kept }; - if (bytes != null) { - const raw = bytes[0..@intCast(len)]; - // One it cannot read (corrupt, truncated, not what its name says) - // is refused, rather than shown as a blank pane. - if (!readable(raw)) { - const why = "not an image pardes can read"; - Kind.api.say.?(why, why.len, 1); - return st; - } - keep(st, raw); - } - return st; -} - -/// The file's bytes kept, and decoded on a job. -fn keep(st: *State, raw: []const u8) void { - const copy = alloc(u8, raw.len) orelse return; - @memcpy(copy, raw); - st.raw = copy; - if (raw.len > 0) _ = Kind.api.job.?(copy.ptr, @intCast(copy.len)); -} - -fn paint(ctx: ?*anyopaque, win: [*c]const Kind.c.pa_window, out: [*c]Kind.c.pa_paint) callconv(.c) void { - const st: *const State = @ptrCast(@alignCast(ctx orelse return)); - const w = win.*; - const o = &out.*; - // `img`, which the core follows with its art words and the path. - @memcpy(o.prefix[0..config.tag_image.len], config.tag_image); - o.prefix_len = config.tag_image.len; - if (st.rgba.len == 0 or o.cap == 0) return; - o.placements[0] = std.mem.zeroInit(Kind.c.pa_placement, .{ - .rgba = st.rgba.ptr, - .w = st.w, - .h = st.h, - .src = .{ .x = 0, .y = 0, .w = st.w, .h = st.h }, - .dst = .{ .x = 0, .y = 0, .w = w.cols, .h = w.rows }, - }); - o.n = 1; -} - -/// Off the loop (80 ms in ReleaseSafe, 290 in Debug, for the docs' -/// screenshot): width and height, then the RGBA. -fn jobRun(in: [*c]const u8, n: u32, out: [*c]Kind.c.pa_out) callconv(.c) u32 { - const got = decode(decode_gpa orelse return 0, in[0..n]) orelse return 0; - defer decode_gpa.?.free(got.rgba); - const len = 8 + got.rgba.len; - const buf: [*]u8 = @ptrCast(out.*.alloc.?(out, len) orelse return 0); - std.mem.writeInt(u32, buf[0..4], @intCast(got.w), .little); - std.mem.writeInt(u32, buf[4..8], @intCast(got.h), .little); - @memcpy(buf[8..len], got.rgba); - return @intCast(len); -} - -fn jobDone(ctx: ?*anyopaque, _: u32, out: [*c]const u8, n: u32) callconv(.c) void { - const st: *State = @ptrCast(@alignCast(ctx orelse return)); - if (n < 8) return; - const w = std.mem.readInt(u32, out[0..4], .little); - const h = std.mem.readInt(u32, out[4..8], .little); - if (@as(u64, w) * h * 4 != n - 8) return; - const rgba = alloc(u8, n - 8) orelse return; - @memcpy(rgba, out[8..n]); - st.rgba = rgba; - st.w = w; - st.h = h; -} - -fn dump(ctx: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { - const st: *const State = @ptrCast(@alignCast(ctx orelse return 0)); - if (st.raw.len <= n) @memcpy(buf[0..st.raw.len], st.raw); - return @intCast(st.raw.len); -} - -fn load(ctx: ?*anyopaque, buf: [*c]const u8, n: u32, _: u32) callconv(.c) c_int { - const st: *State = @ptrCast(@alignCast(ctx orelse return 1)); - keep(st, buf[0..n]); - return 0; -} diff --git a/src/keys.zig b/src/keys.zig index 06566714..ee14a48a 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -14,7 +14,6 @@ const layout = @import("layout.zig"); const tagline = @import("tagline.zig"); const mouse = @import("mouse.zig"); const builtins = @import("builtins.zig"); -const image = @import("image.zig"); const ctlfs = @import("ninep/tree.zig"); const Macro = @import("Macro.zig"); const Pipe = @import("Pipe.zig"); diff --git a/src/look.zig b/src/look.zig index b2fb5ae9..42ed0fb1 100644 --- a/src/look.zig +++ b/src/look.zig @@ -371,8 +371,7 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu .at = pl.at, .kind = .pdf, } }; - var compiled_in: Kind.Registry = if (p == null) .init() else .{}; - if ((if (p) |pp| &pp.kinds else &compiled_in).forPath(found.path)) |k| return .{ .kind = .{ .path = found.path, .kind = k } }; + if (p) |pp| if (pp.kinds.forPath(found.path)) |k| return .{ .kind = .{ .path = found.path, .kind = k } }; return .{ .file = .{ .path = found.path, .at = pl.at } }; } diff --git a/src/macos.zig b/src/macos.zig index 3ba5f52a..685e9d2f 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -14,7 +14,6 @@ const message = pardes.Messages.Message; const layout = @import("layout.zig"); const animation = @import("animation.zig"); const file_watch = @import("file_watch.zig"); -const image = if (pardes.pdf_enabled) @import("image.zig") else struct {}; const host_io = @import("host_io.zig"); const fonts = @import("fonts.zig"); // the shared fallback preference order const tracy = @import("tracy.zig"); // no-op unless -Dtracy names a checkout @@ -511,10 +510,14 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { if (found.dir) |d| crash.setDir(d); } - pardes.image.start(io, allocs.image); - errdefer pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); - errdefer if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.start(io, allocs.image); + pardes.pdf.start(allocs.pdf); + } + errdefer if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.stop(); + pardes.pdf.stop(); + }; pardes.syntax.start(allocs.tree_sitter); errdefer pardes.syntax.stop(); @@ -604,8 +607,10 @@ export fn pardes_deinit() void { if (st.changed_cells.len > 0) st.gpa.free(st.changed_cells); if (st.images.len > 0) st.gpa.free(st.images); st.core.deinit(); - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.stop(); + pardes.pdf.stop(); + } pardes.syntax.stop(); st.config_arena.deinit(); st.prompt_rcs.deinit(); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 9b87d9aa..42d9f3bd 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1539,7 +1539,7 @@ test "an address looked at in an image pane names the image, never an empty subj const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const id = p.freeSlot().?; - const doc = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/pardes-pic.ppm", null); + const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null); _ = wr(p, Node.of(doc.serial, .look), ":/x/\n"); try testing.expect(th.logHas(p, "look: /tmp/pardes-pic.ppm is no text to address")); } @@ -1548,7 +1548,7 @@ test "Save and Save path on an image pane are refused with why, never a silent s const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const id = p.freeSlot().?; - const doc = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/pardes-pic.ppm", null); + const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null); for ([_][]const u8{ "Save\n", "Save /tmp/pardes-copy.ppm\n" }) |line| { const r = wr(p, Node.of(doc.serial, .ctl), line); try testing.expectEqual(Status.err, r.reply.status); @@ -1579,9 +1579,7 @@ test "a builtin for one kind of pane is refused on another, and still acts on it }; const id = p.freeSlot().?; // A picture shown: the core's art words follow the kind's prefix. - pardes.image.start(testing.io, testing.allocator); - defer pardes.image.stop(); - const doc = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/pardes-pic.ppm", "P6\n1 1\n255\n\x01\x02\x03"); + const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", "P6\n1 1\n255\n\x01\x02\x03"); while (p.nextEffect()) |e| p.perform(e); pardes.exec.placeNew(p, 0, 0, id, .doc); _ = try p.render(p.scratch.allocator()); @@ -2158,32 +2156,10 @@ test "a language server question that finds nothing, cannot be answered, or is a try testing.expectEqual(@as(u16, 0), p.fs.late_failure_len); // An image's body takes no write. const slot = p.freeSlot().?; - const img = try pardes.Kind.open(p, slot, pardes.Kind.image, "/tmp/pardes-no-such.png", "not a png"); + const img = try pardes.Kind.open(p, slot, pardes.Kind.test_kind.of(p), "/tmp/pardes-no-such.png", "not a png"); try testing.expectEqual(E.INVAL, wr(p, Node.of(img.serial, .body), "text\n").errno()); } -test "a corrupt image fails its look with an err, and no pane is made" { - pardes.image.start(testing.io, testing.allocator); - defer pardes.image.stop(); - const p = try withFile(testing.allocator, "x\n"); - defer p.deinit(); - var tmp = testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(testing.io, .{ .sub_path = "bad.png", .data = "\x89PNG not really" }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; - var line: [4200]u8 = undefined; - var count: usize = 0; - for (p.panes) |slot| count += @intFromBool(slot != null); - const r = wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/bad.png\n", .{dir})); - try testing.expectEqual(E.IO, r.errno()); - try testing.expect(std.mem.endsWith(u8, r.reply.ename, "bad.png: not an image pardes can read")); - p.sync(); - var after: usize = 0; - for (p.panes) |slot| after += @intFromBool(slot != null); - try testing.expectEqual(count, after); -} - test "a truncated PDF fails its look with its path and why" { if (comptime !pardes.pdf_enabled) return; const p = try withFile(testing.allocator, "x\n"); @@ -2800,7 +2776,7 @@ test "a Save whose directory is missing because one above refuses says permissio test "a body write to an image pane says its body takes none, not that terminals have no text" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.image, "/tmp/pardes-pic.ppm", null); + const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null); try testing.expectEqualStrings(pane_files.e_no_body, wr(p, Node.of(doc.serial, .body), "x").reply.ename); } @@ -2830,7 +2806,7 @@ test "a Rename that reaches other files previews them, says so, and is the pane test "Edit on an image pane is refused as a data write there is, EINVAL, before it runs" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.image, "/tmp/pardes-pic.ppm", null); + const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null); const edit = wr(p, Node.of(doc.serial, .ctl), "Edit ,d\n"); const data = wr(p, Node.of(doc.serial, .data), "x"); try testing.expectEqual(E.INVAL, edit.errno()); @@ -2841,7 +2817,7 @@ test "Edit on an image pane is refused as a data write there is, EINVAL, before test "Petscii, Palette and Ascii take the state their tag word names, set rather than flipped" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.image, "/tmp/pardes-pic.ppm", null); + const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null); const ctl_node = Node.of(doc.serial, .ctl); for ([_][]const u8{ "Petscii on\n", "Petscii on\n" }) |line| { try testing.expectEqual(Status.ok, wr(p, ctl_node, line).reply.status); @@ -2851,7 +2827,7 @@ test "Petscii, Palette and Ascii take the state their tag word names, set rather try testing.expect(!doc.addon.?.art.glyph); _ = wr(p, ctl_node, "Palette terminal\n"); _ = wr(p, ctl_node, "Palette terminal\n"); - try testing.expectEqual(pardes.panes.Image.PaletteMode.terminal, doc.addon.?.art.palette); + try testing.expectEqual(pardes.Placement.Art.Palette.terminal, doc.addon.?.art.palette); _ = wr(p, ctl_node, "Ascii off\n"); _ = wr(p, ctl_node, "Ascii off\n"); try testing.expect(!doc.addon.?.art.ascii); diff --git a/src/panes.zig b/src/panes.zig index e4872468..cfe09f33 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -723,8 +723,6 @@ pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); -pub const Image = @import("image.zig"); - pub const Pdf = @import("pdf_view.zig"); pub const terminal = @import("terminal.zig"); @@ -736,7 +734,6 @@ test { _ = Output; _ = Dir; _ = mini; - _ = Image; _ = @import("Kind.zig"); _ = Pdf; _ = terminal; diff --git a/src/pardes.zig b/src/pardes.zig index 35cccf26..58f8fa17 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -42,6 +42,8 @@ pub const Cell = @import("surface.zig").Cell; pub const Placement = @import("surface.zig").Placement; pub const Raster = @import("surface.zig").Raster; pub const RectPx = @import("surface.zig").RectPx; +pub const NativeGeometry = @import("surface.zig").NativeGeometry; +pub const containGeometry = @import("surface.zig").containGeometry; pub const RectCell = @import("surface.zig").RectCell; pub const Surface = @import("surface.zig").Surface; pub const Region = @import("surface.zig").Region; @@ -77,8 +79,9 @@ pub const views = @import("views.zig"); pub const rollback = @import("rollback.zig"); pub const replica = @import("replica.zig"); pub const echo = @import("echo.zig"); -pub const image = @import("image.zig"); pub const Kind = @import("Kind.zig"); +/// A terminal's kitty pictures; its PNG resize is started with the shell. +pub const TerminalImages = panes.terminal.TerminalImages; pub const Addon = @import("Addon.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 8edb4902..93390b57 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -9,7 +9,7 @@ const config = @import("config.zig"); const modal = @import("modal.zig"); const filesystem = @import("fs.zig"); const tracy = @import("tracy.zig"); -const image = @import("image.zig"); +const surface = @import("surface.zig"); const look = @import("look.zig"); const tagline = @import("tagline.zig"); const File = panes.File; @@ -1147,8 +1147,163 @@ pub const PanResult = enum { moved, edge, unavailable }; pub const ScrollResult = struct { active_page: usize }; pub const CellPixels = struct { w: u16, h: u16 }; +/// How a native pixel attachment is placed in its pane body. `contain` is the +/// historical image-pane policy: shrink only when necessary and keep the +/// image at the top left. The axis-specific modes may enlarge, letterbox the +/// unconstrained axis, or crop it when it overflows. +pub const NativeFit = if (enabled) enum { contain, width, height } else enum { contain }; + +fn panOffset(overflow: u32, pan: u16) u32 { + if (overflow == 0 or pan == 0) return 0; + if (pan == std.math.maxInt(u16)) return overflow; + // Round, rather than truncate, so the midpoint is the visual midpoint. + return @intCast((@as(u64, overflow) * pan + std.math.maxInt(u16) / 2) / std.math.maxInt(u16)); +} + +fn fitWidth(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_y: u16) ?surface.NativeGeometry { + const scaled_h = @as(u64, src_h) * body_w; + if (scaled_h <= @as(u64, body_h) * src_w) { + const full_h: u32 = @intCast(@max(1, scaled_h / src_w)); + return .{ + .src = .{ .w = src_w, .h = src_h }, + .dst = .{ .y = (body_h - full_h) / 2, .w = body_w, .h = full_h }, + }; + } + + // Retain the largest whole source-pixel crop which cannot extend beyond + // the body at this scale. The sub-pixel remainder becomes at most a small + // centered letterbox instead of leaking into an adjacent cell in Kitty. + const crop_h_wide = @as(u64, body_h) * src_w / body_w; + if (crop_h_wide == 0) return null; + const crop_h: u32 = @min(src_h, @as(u32, @intCast(crop_h_wide))); + const dst_h: u32 = @min(body_h, @max(1, @as(u32, @intCast(@as(u64, crop_h) * body_w / src_w)))); + return .{ + .src = .{ + .y = panOffset(src_h - crop_h, pan_y), + .w = src_w, + .h = crop_h, + }, + .dst = .{ .y = (body_h - dst_h) / 2, .w = body_w, .h = dst_h }, + }; +} + +fn fitHeight(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_x: u16) ?surface.NativeGeometry { + const scaled_w = @as(u64, src_w) * body_h; + if (scaled_w <= @as(u64, body_w) * src_h) { + const full_w: u32 = @intCast(@max(1, scaled_w / src_h)); + return .{ + .src = .{ .w = src_w, .h = src_h }, + .dst = .{ .x = (body_w - full_w) / 2, .w = full_w, .h = body_h }, + }; + } + + const crop_w_wide = @as(u64, body_w) * src_h / body_h; + if (crop_w_wide == 0) return null; + const crop_w: u32 = @min(src_w, @as(u32, @intCast(crop_w_wide))); + const dst_w: u32 = @min(body_w, @max(1, @as(u32, @intCast(@as(u64, crop_w) * body_h / src_h)))); + return .{ + .src = .{ + .x = panOffset(src_w - crop_w, pan_x), + .w = crop_w, + .h = src_h, + }, + .dst = .{ .x = (body_w - dst_w) / 2, .w = dst_w, .h = body_h }, + }; +} + +/// Compute native image placement without floating point. Source dimensions +/// are limited to u32 because SDL's texture API and Kitty's crop parameters +/// cannot describe anything larger. Kitty applies the stricter u16 check at +/// its protocol boundary. +pub fn nativeGeometry( + iw: usize, + ih: usize, + body_pixel_w: u32, + body_pixel_h: u32, + fit: NativeFit, + pan_x: u16, + pan_y: u16, +) ?surface.NativeGeometry { + if (comptime !enabled) { + return surface.containGeometry(iw, ih, body_pixel_w, body_pixel_h); + } + if (iw == 0 or ih == 0 or body_pixel_w == 0 or body_pixel_h == 0 or + iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null; + + const src_w: u32 = @intCast(iw); + const src_h: u32 = @intCast(ih); + return switch (fit) { + .width => fitWidth(src_w, src_h, body_pixel_w, body_pixel_h, pan_y), + .height => fitHeight(src_w, src_h, body_pixel_w, body_pixel_h, pan_x), + // Pan is not contain's: it keeps the top-left placement. + .contain => surface.containGeometry(iw, ih, body_pixel_w, body_pixel_h), + }; +} + +test "native fit width handles portrait crop, pan extrema, and landscape letterbox" { + if (comptime !enabled) return; + const top = nativeGeometry(600, 1000, 800, 600, .width, 0, 0).?; + try std.testing.expectEqual(surface.RectPx{ .w = 600, .h = 450 }, top.src); + try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, top.dst); + + const middle = nativeGeometry(600, 1000, 800, 600, .width, 0, 32768).?; + try std.testing.expectEqual(@as(u32, 275), middle.src.y); + const bottom = nativeGeometry(600, 1000, 800, 600, .width, 65535, 65535).?; + try std.testing.expectEqual(@as(u32, 550), bottom.src.y); + + const landscape = nativeGeometry(1000, 600, 800, 600, .width, 0, 65535).?; + try std.testing.expectEqual(surface.RectPx{ .w = 1000, .h = 600 }, landscape.src); + try std.testing.expectEqual(surface.RectPx{ .y = 60, .w = 800, .h = 480 }, landscape.dst); +} + +test "native fit height handles portrait letterbox and landscape crop" { + if (comptime !enabled) return; + const portrait = nativeGeometry(600, 1000, 800, 600, .height, 65535, 0).?; + try std.testing.expectEqual(surface.RectPx{ .w = 600, .h = 1000 }, portrait.src); + try std.testing.expectEqual(surface.RectPx{ .x = 220, .w = 360, .h = 600 }, portrait.dst); + + const left = nativeGeometry(1000, 600, 800, 600, .height, 0, 0).?; + try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, left.src); + try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, left.dst); + const right = nativeGeometry(1000, 600, 800, 600, .height, 65535, 0).?; + try std.testing.expectEqual(@as(u32, 200), right.src.x); +} + +test "native fit odd ratios round inward and map points through letterboxes and crops" { + if (comptime !enabled) return; + const width = nativeGeometry(403, 211, 101, 47, .width, 0, 32768).?; + try std.testing.expectEqual(surface.RectPx{ .y = 12, .w = 403, .h = 187 }, width.src); + try std.testing.expectEqual(surface.RectPx{ .w = 101, .h = 46 }, width.dst); + const mapped = width.sourcePoint(100, 45).?; + try std.testing.expect(mapped.x < width.src.x + width.src.w); + try std.testing.expect(mapped.y < width.src.y + width.src.h); + try std.testing.expect(width.sourcePoint(101, 46) == null); + + const height = nativeGeometry(403, 211, 101, 47, .height, 32768, 0).?; + try std.testing.expectEqual(surface.RectPx{ .w = 403, .h = 211 }, height.src); + try std.testing.expectEqual(surface.RectPx{ .x = 6, .w = 89, .h = 47 }, height.dst); + try std.testing.expect(height.sourcePoint(5, 20) == null); + try std.testing.expect(height.sourcePoint(6, 20) != null); +} + +test "native fit modes reject what the backend contract cannot represent and are total at extreme aspect ratios" { + if (comptime !enabled) return; + try std.testing.expect(nativeGeometry(10, 10, 0, 20, .width, 0, 0) == null); + if (@bitSizeOf(usize) > 32) + try std.testing.expect(nativeGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20, .height, 0, 0) == null); + + const largest = std.math.maxInt(u32); + try std.testing.expect(nativeGeometry(1, largest, largest, 1, .width, 0, 65535) == null); + try std.testing.expect(nativeGeometry(largest, 1, 1, largest, .height, 65535, 0) == null); + + const wide = nativeGeometry(largest, 1, largest, 1, .width, 0, 0).?; + try std.testing.expectEqual(surface.RectPx{ .w = largest, .h = 1 }, wide.dst); + const tall = nativeGeometry(1, largest, 1, largest, .height, 0, 0).?; + try std.testing.expectEqual(surface.RectPx{ .w = 1, .h = largest }, tall.dst); +} + const PlacedGeometry = struct { - geometry: image.NativeGeometry, + geometry: surface.NativeGeometry, pixel_offset_y: f32, }; @@ -1157,7 +1312,7 @@ pub const PlacedRaster = if (enabled) struct { revision: u32, fit: FitMode, pan_x: u16, - geometry: image.NativeGeometry, + geometry: surface.NativeGeometry, pixel_offset_y: f32, rgba: []const u8, width: usize, @@ -1165,7 +1320,7 @@ pub const PlacedRaster = if (enabled) struct { } else void; const VisibleRows = struct { - base: image.NativeGeometry, + base: surface.NativeGeometry, y0: u32, y1: u32, dst_y: u32, @@ -1269,7 +1424,7 @@ fn visibleRows( ) ?VisibleRows { if (comptime !enabled) return null; const page_h = state.page_heights[page]; - const base = image.nativeGeometry( + const base = nativeGeometry( iw, ih, viewport.pixel_w, @@ -1367,7 +1522,7 @@ pub fn placedRaster(state: *const State, viewport: Viewport, page: usize) ?Place }; } -pub fn activeGeometry(state: *const State, viewport: Viewport) ?image.NativeGeometry { +pub fn activeGeometry(state: *const State, viewport: Viewport) ?surface.NativeGeometry { if (comptime !enabled) return null; const raster = rasterForPageConst(state, state.page) orelse return null; const placed = placedGeometry(state, raster, viewport, state.page) orelse return null; @@ -2131,7 +2286,7 @@ pub fn scrollDocument(state: *State, viewport: Viewport, delta_pixels: f64) ?Scr pub fn panPixels( state: *State, - geometry: image.NativeGeometry, + geometry: surface.NativeGeometry, axis: PanAxis, direction: i8, display_pixels: u32, @@ -2185,7 +2340,7 @@ pub fn panPixels( return .moved; } -fn setHorizontalEdge(state: *State, geometry: image.NativeGeometry, end: bool) void { +fn setHorizontalEdge(state: *State, geometry: surface.NativeGeometry, end: bool) void { if (comptime !enabled) return; const raster = rasterForPage(state, state.page) orelse return; if (raster.iw <= geometry.src.w) return; @@ -2205,7 +2360,7 @@ fn rearmSearchReveal(state: *State, viewport: Viewport) void { pub fn revealSearch( state: *State, viewport: Viewport, - geometry: ?image.NativeGeometry, + geometry: ?surface.NativeGeometry, ) void { if (comptime !enabled) return; if (!state.search_reveal_pending) return; @@ -2529,7 +2684,7 @@ pub fn probeWord( } pub fn pointAtGeometry( - geometry: image.NativeGeometry, + geometry: surface.NativeGeometry, pixel_offset_y: f32, full_width: usize, full_height: usize, @@ -2958,7 +3113,7 @@ pub fn tintColors(core: *const pardes.Pardes) TintColors { }; } -pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?image.NativeGeometry { +pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?surface.NativeGeometry { if (comptime !enabled) return null; const state = if (pane.pdf) |view| view else return null; const view = paneViewport(core, pane) orelse return null; diff --git a/src/surface.zig b/src/surface.zig index df9abac1..c058e101 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -7,7 +7,6 @@ const uucode = @import("uucode"); const vaxis = @import("vaxis"); const panes = @import("panes.zig"); const config = @import("config.zig"); -const image = @import("image.zig"); const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const MAX_TAG_LAYERS = pardes.MAX_TAG_LAYERS; @@ -71,7 +70,77 @@ test "cell visual equality ignores dead grapheme tail bytes" { } /// A rectangle in pixels. -pub const RectPx = image.PixelRect; +pub const RectPx = struct { + x: u32 = 0, + y: u32 = 0, + w: u32 = 0, + h: u32 = 0, +}; + +pub const PixelPoint = struct { x: u32, y: u32 }; + +/// Source pixels and their destination inside a pane body's pixel rectangle. +/// Both rectangles are half-open. Rounding is always toward the inside, so a +/// backend can draw this result without a backend-specific overflow clip. +pub const NativeGeometry = struct { + src: RectPx, + dst: RectPx, + + /// Map a destination pixel back into the retained source crop. This is the + /// same integer transform the texture rectangle describes; points in a + /// letterbox return null. + pub fn sourcePoint(self: NativeGeometry, x: u32, y: u32) ?PixelPoint { + if (self.src.w == 0 or self.src.h == 0 or self.dst.w == 0 or self.dst.h == 0) return null; + if (x < self.dst.x or y < self.dst.y) return null; + const dx = x - self.dst.x; + const dy = y - self.dst.y; + if (dx >= self.dst.w or dy >= self.dst.h) return null; + return .{ + .x = self.src.x + @as(u32, @intCast(@as(u64, dx) * self.src.w / self.dst.w)), + .y = self.src.y + @as(u32, @intCast(@as(u64, dy) * self.src.h / self.dst.h)), + }; + } +}; + +/// Where a fitted placement (`at` null) goes: shrunk only when it must be, +/// at the top left. The scale ratios are compared without floating point: +/// the tighter bound is exact, the other rounded inward. +pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeometry { + if (iw == 0 or ih == 0 or max_w == 0 or max_h == 0 or + iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null; + + const src_w: u32 = @intCast(iw); + const src_h: u32 = @intCast(ih); + if (src_w <= max_w and src_h <= max_h) return .{ + .src = .{ .w = src_w, .h = src_h }, + .dst = .{ .w = src_w, .h = src_h }, + }; + const dst: RectPx = if (@as(u64, max_w) * src_h <= @as(u64, max_h) * src_w) + .{ + .w = max_w, + .h = @intCast(@max(1, @as(u64, src_h) * max_w / src_w)), + } + else + .{ + .w = @intCast(@max(1, @as(u64, src_w) * max_h / src_h)), + .h = max_h, + }; + return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst }; +} + +test "native image contain keeps aspect, bounds, top-left, and small-image size" { + try std.testing.expectEqual(RectPx{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst); + try std.testing.expectEqual(RectPx{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst); + try std.testing.expectEqual(RectPx{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst); + try std.testing.expect(containGeometry(17, 9, 0, 40) == null); + + const odd = containGeometry(403, 211, 101, 47).?; + try std.testing.expectEqual(RectPx{ .w = 89, .h = 47 }, odd.dst); + try std.testing.expectEqual(RectPx{ .w = 403, .h = 211 }, odd.src); + // Nothing its backend contract cannot represent. + try std.testing.expect(containGeometry(0, 10, 20, 20) == null); + if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null); +} /// A rectangle in the frame's cells. pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; diff --git a/src/tape.zig b/src/tape.zig index d3e5558a..cd777f96 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -1242,8 +1242,10 @@ pub fn startFromEnv() void { pub fn replayMain(io: std.Io, path: []const u8) u8 { const gpa = std.heap.c_allocator; // What a shell starts before its core (tui.zig's localSession). - pardes.image.start(io, gpa); - if (comptime pardes.pdf_enabled) pardes.pdf.start(gpa); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.start(io, gpa); + pardes.pdf.start(gpa); + } pardes.syntax.start(gpa); const bytes = std.Io.Dir.cwd().readFileAlloc(std.Io.Threaded.global_single_threaded.io(), path, gpa, .unlimited) catch |err| { std.debug.print("replay: cannot read {s}: {t}\n", .{ path, err }); diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 0c74cbaa..fd47cb67 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -766,7 +766,7 @@ fn exactKittyPlacement( screen_pixel_w: u16, screen_pixel_h: u16, ) ?KittyPlacement { - const g: pardes.image.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null }; + const g: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null }; const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); if (g.dst.w == 0 or g.dst.h == 0 or g.src.w == 0 or g.src.h == 0) return null; @@ -823,7 +823,7 @@ fn kittyPlacement( ) ?KittyPlacement { const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8); const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16); - const geometry: pardes.image.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null }; + const geometry: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null }; const fit: enum { width, height } = if (geometry.dst.w >= @as(u32, place.dst.w) * cell_w) .width else .height; const safe_rows_u32 = geometry.dst.h / cell_h; @@ -1221,12 +1221,16 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se const have: ?*replica.Have = if (far) &have_store else null; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); - pardes.image.start(io, allocs.image); - if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.start(io, allocs.image); + pardes.pdf.start(allocs.pdf); + } pardes.syntax.start(allocs.tree_sitter); defer { - pardes.image.stop(); - if (comptime pardes.pdf_enabled) pardes.pdf.stop(); + if (comptime pardes.pdf_enabled) { + pardes.TerminalImages.stop(); + pardes.pdf.stop(); + } pardes.syntax.stop(); } var o = opts; diff --git a/test/behaviour/addons.zig b/test/behaviour/addons.zig index 523aefb9..c7a59951 100644 --- a/test/behaviour/addons.zig +++ b/test/behaviour/addons.zig @@ -33,13 +33,12 @@ fn unload(s: *Session, name: []const u8) void { test "addons: Addon load takes a library in, /addons lists it with the kinds compiled in, its words join /commands and Help, and Addon unload lets it go" { var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); - try std.testing.expect(has(try s.read("/addons"), "image 1 2.0 0 - - static\n")); try load(&s, fake.ok); defer unload(&s, "fake"); // `<kind> <version> <abi> <panes open> <path> <blake3> <state>`. const listed = try s.read("/addons"); - const at = std.mem.indexOf(u8, listed, "\nfake 1 2.0 0 /").?; - var fields = std.mem.tokenizeScalar(u8, listed[at + 1 .. std.mem.indexOfScalarPos(u8, listed, at + 1, '\n').?], ' '); + try std.testing.expect(std.mem.startsWith(u8, listed, "fake 1 2.0 0 /")); + var fields = std.mem.tokenizeScalar(u8, listed[0..std.mem.indexOfScalar(u8, listed, '\n').?], ' '); for (0..5) |_| _ = fields.next(); try std.testing.expectEqual(@as(usize, 64), fields.next().?.len); try std.testing.expectEqualStrings("loaded", fields.next().?); @@ -52,16 +51,13 @@ test "addons: Addon load takes a library in, /addons lists it with the kinds com // A pane of it open, it stays; closed, it goes. try s.write("/ctl", "Fake\n"); const pane = try paneOf(&s, "fake"); - try std.testing.expect(has(try s.read("/addons"), "\nfake 1 2.0 1 /")); + try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "fake 1 2.0 1 /")); try std.testing.expect(try s.refused("/ctl", "Addon unload fake\n") != 0); try std.testing.expect(has(s.said, "1 fake pane is open")); try s.write(s.at("/pane/{d}/ctl", .{pane}), "Del\n"); try s.write("/ctl", "Addon unload fake\n"); try std.testing.expect(!has(try s.read("/addons"), "fake")); try std.testing.expect(!has(try s.read("/commands"), "Fake")); - // A compiled-in kind is no library to let go. - try std.testing.expect(try s.refused("/ctl", "Addon unload image\n") != 0); - try std.testing.expect(has(s.said, "image is compiled in")); } test "addons: a library of another ABI, one with no pardes_addon, and one whose word is the core's are refused, each listed with why" { @@ -69,7 +65,7 @@ test "addons: a library of another ABI, one with no pardes_addon, and one whose defer s.deinit(); for ([_][]const u8{ fake.abi, fake.no_export, fake.core_word }) |path| try load(&s, path); const listed = try s.read("/addons"); - try std.testing.expect(has(listed, "\nfakeabi 1 3.0 0 /")); + try std.testing.expect(std.mem.startsWith(u8, listed, "fakeabi 1 3.0 0 /")); try std.testing.expect(has(listed, " refused: wants abi 3, this pardes speaks 2\n")); try std.testing.expect(has(listed, " refused: it has no pardes_addon\n")); try std.testing.expect(has(listed, "\nfakeword 1 2.0 0 /")); @@ -119,6 +115,65 @@ test "addons: a pane of an addon's kind shows its cells and its picture, takes i try std.testing.expect(try s.focused() != pane); } +test "addons: the image addon opens the pictures a Look names, fitted, with the core's art words in its tag; refuses what it cannot read; and keeps a picture's bytes through a dump" { + var s = try Session.initFile(std.testing.allocator, "x\n"); + defer s.deinit(); + try load(&s, Session.image_addon); + const listed = try s.read("/addons"); + try std.testing.expect(std.mem.startsWith(u8, listed, "image 1 2.0 0 /") and has(listed, " loaded\n")); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)]; + // A PNG 4x2, a JPEG 16x8 baseline and progressive, a PPM 2x1: each a + // pane showing its pixels (`src`), over the cells it fits. + const b64 = std.base64.standard.Decoder; + const pictures = [_]struct { []const u8, []const u8, u32, u32 }{ + .{ "red.png", "iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAIAAADwyuo0AAAAE0lEQVR4nGP4z8AARGDiPwMyBwBnsgf5Q2OaZwAAAABJRU5ErkJggg==", 4, 2 }, + .{ "red.jpg", "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAAIABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5Dooor8LP9VD/2Q==", 16, 8 }, + .{ "red.jpeg", "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wgARCAAIABADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAVAQEBAAAAAAAAAAAAAAAAAAAGCP/aAAwDAQACEAMQAAABkIC1V//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAQUCP//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Bf//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEABj8CP//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAT8hP//aAAwDAQACAAMAAAAQA//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Qf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Qf//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAT8QP//Z", 16, 8 }, + .{ "pixel.ppm", "P6\n2 1\n255\n\x0d\x4d\xe7\x0d\x4d\xe7", 2, 1 }, + }; + for (pictures) |pic| { + const bytes = if (std.mem.endsWith(u8, pic[0], ".ppm")) pic[1] else blk: { + const out = try s.arena.allocator().alloc(u8, try b64.calcSizeForSlice(pic[1])); + try b64.decode(out, pic[1]); + break :blk out; + }; + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = pic[0], .data = bytes }); + try s.write("/look", s.at("{s}/{s}\n", .{ dir, pic[0] })); + try std.testing.expect(has(try s.read("/screen"), s.at("\"serial\":{d},\"rect\":", .{try s.focused()}))); + try std.testing.expect(has(try s.read("/screen"), s.at("\"src\":[0,0,{d},{d}]", .{ pic[2], pic[3] }))); + } + const pane = try s.focused(); + // Its tag: the kind's `img`, the core's art words, its path. With no + // pixels to show (no frontend), glyph art whatever Petscii says. + const tag = s.at("/pane/{d}/tag", .{pane}); + try std.testing.expect(std.mem.startsWith(u8, try s.read(tag), s.at("img petscii:on palette:commodore ascii:on {s}/pixel.ppm ", .{dir}))); + const ctl = s.at("/pane/{d}/ctl", .{pane}); + for ([_][]const u8{ "Petscii on\n", "Palette terminal\n", "Palette terminal\n", "Ascii off\n" }) |line| try s.write(ctl, line); + try std.testing.expect(std.mem.startsWith(u8, try s.read(tag), "img petscii:on palette:terminal ascii:off ")); + try std.testing.expect(has(try s.read("/screen"), "\"petscii\":true")); + // A file it cannot read: the Look fails saying so, and opens nothing. + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad.png", .data = "\x89PNG not really" }); + const panes = (try s.read("/index")).len; + try std.testing.expect(try s.refused("/look", s.at("{s}/bad.png\n", .{dir})) != 0); + try std.testing.expect(has(s.said, "bad.png: not an image pardes can read")); + try std.testing.expectEqual(panes, (try s.read("/index")).len); + // Its record is the file's bytes: restored without the addon it waits + // as a placeholder holding them, and shows them again when it comes. + try s.write("/ctl", "Dump\n"); + const label = try s.arena.allocator().dupe(u8, std.mem.sliceTo(try s.read("/dumps"), ' ')); + var lines = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n'); + while (lines.next()) |line| if (std.mem.indexOf(u8, line, " image ") != null) try s.write(s.at("/pane/{s}/ctl", .{std.mem.sliceTo(line, ' ')}), "Del\n"); + try s.write("/ctl", "Addon unload image\n"); + try s.write("/ctl", s.at("Restore {s}\n", .{label})); + try std.testing.expect(has(try s.screen(), "addon image 1 is not loaded: Addon load <path>")); + try load(&s, Session.image_addon); + defer unload(&s, "image"); + try std.testing.expect(has(try s.read("/screen"), "\"src\":[0,0,4,2]")); +} + test "addons: a dump keeps an addon's pane; restored without its addon it waits as a placeholder, and opens in place when the addon comes" { var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index 6ee50f77..22ce27fe 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -1,6 +1,5 @@ const std = @import("std"); const pardes = @import("pardes"); -const image = pardes.image; const filesystem = pardes.filesystem; test "runtime Mount and Unmount copy command arguments and change Look resolution" { @@ -289,8 +288,6 @@ test "owned cwd failed file opens never publish a pane or retain a reservation" test "images decode through explicit filesystem mounts, and a dump reads one on disk from there" { if (!filesystem.platform_has_fs) return error.SkipZigTest; const gpa = std.testing.allocator; - pardes.image.start(std.testing.io, gpa); - defer pardes.image.stop(); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const bytes = "P6\n1 1\n255\n\x0d\x4d\xe7"; @@ -299,22 +296,27 @@ test "images decode through explicit filesystem mounts, and a dump reads one on const directory_len = try tmp.dir.realPath(std.testing.io, &directory_buffer); const path = try std.fmt.allocPrint(gpa, "/n/os{s}/pixel.ppm", .{directory_buffer[0..directory_len]}); defer gpa.free(path); - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .file = path }); + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); + // The image addon loaded, as `Addon load` loads it; the picture looked at. + pardes.Addon.perform(p, .load, 0, @import("test_addons").image); + pardes.look.lookAt(p, 0, path); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); // Its decode is a job its host runs: here, at once. - while (p.nextEffect()) |e| p.perform(e); + while (p.nextEffect()) |e| if (e == .job) p.perform(e); _ = try p.render(arena.allocator()); const shown = p.surface.placements.items; try std.testing.expectEqual(@as(usize, 1), shown.len); try std.testing.expectEqual(@as(u32, 1), shown[0].raster.w); try std.testing.expectEqual(@as(u32, 1), shown[0].raster.h); - // The picture's bytes are in the dump: it comes back as it was shown. + // The picture's bytes are in the dump: it comes back as it was shown + // (a placeholder holding them, as a core without the addon keeps it). try pardes.dump.dumpState(p); const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); - const slot = restored.panes[0].?.addon.?; - var kept: [64]u8 = undefined; - try std.testing.expectEqualStrings(bytes, kept[0..image.kind.dump.?(slot.st, &kept, kept.len)]); + const slot = for (restored.panes) |pane| { + if (pane) |each| if (each.addon) |s| break s; + } else return error.NoImagePane; + try std.testing.expectEqualStrings(bytes, slot.record.?); } diff --git a/test/image_harness.zig b/test/image_harness.zig index 18392851..02e6690b 100644 --- a/test/image_harness.zig +++ b/test/image_harness.zig @@ -36,12 +36,14 @@ pub fn main(init: std.process.Init) !void { defer arena_state.deinit(); const arena = arena_state.allocator(); const args = try init.minimal.args.toSlice(arena); - if (args.len != 3 and args.len != 4) return error.BadArgs; + // <pardes> <image.so> tui|gui [pdf] + if (args.len != 4 and args.len != 5) return error.BadArgs; const exe = try arena.dupeSentinel(u8, args[1], 0); - const backend = args[2]; - const pdf_mode = args.len == 4 and std.mem.eql(u8, args[3], "pdf"); - if (args.len == 4 and !pdf_mode) return error.BadArgs; + const image_addon = try std.Io.Dir.cwd().realPathFileAlloc(init.io, args[2], arena); + const backend = args[3]; + const pdf_mode = args.len == 5 and std.mem.eql(u8, args[4], "pdf"); + if (args.len == 5 and !pdf_mode) return error.BadArgs; const base = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-image-harness-{d}", .{libc.getpid()}, 0); if (libc.mkdir(base, 0o755) != 0 and libc.errno(-1) != .EXIST) return error.MkdirFailed; defer cleanupBase(arena, base); @@ -54,6 +56,10 @@ pub fn main(init: std.process.Init) !void { const config_dir = try std.fmt.allocPrintSentinel(arena, "{s}/pardes", .{config_home}, 0); if (libc.mkdir(config_dir, 0o755) != 0) return error.MkdirFailed; try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/init", .{config_dir}, 0), "Theme helix\n"); + // Its data directory too, holding the image addon its start scan loads. + _ = setenv("XDG_DATA_HOME", try std.fmt.allocPrintSentinel(arena, "{s}/data", .{base}, 0), 1); + for ([_][]const u8{ "data", "data/pardes", "data/pardes/addons" }) |sub| _ = libc.mkdir(try std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ base, sub }, 0), 0o755); + if (libc.symlink(image_addon, try std.fmt.allocPrintSentinel(arena, "{s}/data/pardes/addons/image.so", .{base}, 0)) != 0) return error.SymlinkFailed; _ = setenv("HISTFILE", "/dev/null", 1); _ = setenv("TERM", "xterm-256color", 1); _ = setenv("LC_ALL", "C", 1); @@ -78,11 +84,15 @@ fn cleanupBase(arena: std.mem.Allocator, base: [:0]const u8) void { _ = libc.rmdir(config_dir); const config_home = std.fmt.allocPrintSentinel(arena, "{s}/.config", .{base}, 0) catch return; _ = libc.rmdir(config_home); - const names = [_][]const u8{ "native.ppm", "pages.pdf", "latest.ppm", "latest.ppm.tmp", ".bash_history" }; + const names = [_][]const u8{ "native.ppm", "pages.pdf", "latest.ppm", "latest.ppm.tmp", ".bash_history", "data/pardes/addons/image.so" }; for (names) |name| { const path = std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ base, name }, 0) catch continue; _ = libc.unlink(path); } + for ([_][]const u8{ "data/pardes/addons", "data/pardes", "data" }) |sub| { + const path = std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ base, sub }, 0) catch continue; + _ = libc.rmdir(path); + } _ = libc.rmdir(base); } diff --git a/test/kitty.zig b/test/kitty.zig index 70e20139..ad70f453 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -64,9 +64,9 @@ const Rig = struct { read: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty), fn init(shells: u8) !Rig { - // f=100 decodes through pardes's own decoder (stb_image), which the - // shells start at launch. - pardes.image.start(std.testing.io, gpa); + // f=100 decodes through wuffs, its resize through stb_image_resize, + // which the shells start at launch. + pardes.TerminalImages.start(std.testing.io, gpa); // ghostty warns of every refused command; the refusals are the point. std.testing.log_level = .err; // A core boots one shell or the classic three. @@ -86,7 +86,7 @@ const Rig = struct { for (&r.read) |*b| b.deinit(gpa); r.frame.deinit(); r.p.deinit(); - pardes.image.stop(); + pardes.TerminalImages.stop(); } fn drain(r: *Rig) void { @@ -398,7 +398,7 @@ test "kitty: a=p places one image twice by placement id, a source rect crops it, const crop = cropped orelse return error.CroppedPlacementMissing; try std.testing.expectEqual(o.x + 9, crop.dst.x); try std.testing.expectEqual(@as(u16, 1), crop.dst.w); - const g: pardes.image.NativeGeometry = .{ .src = crop.src, .dst = crop.at.? }; + const g: pardes.NativeGeometry = .{ .src = crop.src, .dst = crop.at.? }; try std.testing.expectEqual(@as(u32, 2), g.src.x); try std.testing.expectEqual(@as(u32, 2), g.src.w); // Put again under the same id, placement 1 moves; it is not doubled. @@ -1212,7 +1212,7 @@ test "kitty: an image wider than its pane is cut at the pane's edge, never drawn try std.testing.expect(drawn[0].dst.x + drawn[0].dst.w <= o.x + r.pane(0).cols); try std.testing.expect(drawn[0].dst.x + drawn[0].dst.w <= right); // And the pixels it takes are only that cell's. - const g: pardes.image.NativeGeometry = .{ .src = drawn[0].src, .dst = drawn[0].at.? }; + const g: pardes.NativeGeometry = .{ .src = drawn[0].src, .dst = drawn[0].at.? }; try std.testing.expect(g.dst.w <= @as(u32, drawn[0].dst.w) * 10); } diff --git a/test/mode.zig b/test/mode.zig index cb93b73e..7335b4ef 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -92,7 +92,7 @@ test "Mode from actual tag Exec preserves parked file and output insert transact test "Mode leaves image and PDF document modes unchanged" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - const picture = try pardes.Kind.open(p, 1, pardes.Kind.image, "/mode-test.png", ""); + const picture = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/mode-test.png", ""); try mode(p, 1, .normal); try std.testing.expect(picture.addon != null); if (comptime panes.Pdf.enabled) { diff --git a/test/panes.zig b/test/panes.zig index e0c383fd..28a884ab 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -8,7 +8,6 @@ const Key = pardes.Key; const config = pardes.config; const modal = pardes.modal; const dump = pardes.dump; -const image = pardes.image; const syntax = pardes.syntax; const filesystem = pardes.filesystem; @@ -2246,24 +2245,65 @@ const OutputTests = struct { } }; +/// The image addon (addons/image/image.c), loaded as `Addon load` loads it. const ImageTests = struct { + fn load(p: *Pardes) u8 { + pardes.Addon.perform(p, .load, 0, @import("test_addons").image); + return p.kinds.byName("image").?; + } + test "pane-local renderer choices are visible in the image tag" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - pardes.image.start(std.testing.io, std.testing.allocator); - defer pardes.image.stop(); // A picture shown (its decode landed, a frame drawn): the core's // art words after the kind's `img`, then its path. const id = p.freeSlot().?; - const pane = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/picture.ppm", "P6\n1 1\n255\n\x01\x02\x03"); + const pane = try pardes.Kind.open(p, id, load(p), "/tmp/picture.ppm", "P6\n1 1\n255\n\x01\x02\x03"); while (p.nextEffect()) |e| p.perform(e); pardes.exec.placeNew(p, 0, 0, id, .doc); _ = try p.render(p.scratch.allocator()); pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false }; - try std.testing.expectEqualStrings( - config.tag_image ++ " petscii:on palette:terminal ascii:off /tmp/picture.ppm", - try pardes.tagline.tagPrefix(p, pane), - ); + try std.testing.expectEqualStrings("img petscii:on palette:terminal ascii:off /tmp/picture.ppm", try pardes.tagline.tagPrefix(p, pane)); + } + + test "an image's dump keeps its file's bytes, its renderer choices and its tag's tail" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + try pardes.panes.deinitPane(p, p.panes[0].?); + p.panes[0] = null; + + const source = "P6\n1 1\n255\n\x0d\x4d\xe7"; + const k = load(p); + const pane = try pardes.Kind.open(p, 0, k, "/missing/restored-image.ppm", source); + pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false }; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Keep Del"); + try dump.dumpState(p); + + // Restored where its addon is (a Restore's kinds are the process's). + var words: [64]pardes.Kind.LoadedWord = undefined; + const e = &p.kinds.kinds[k]; + const brought = [_]pardes.Kind.Loaded{pardes.Kind.loadedOf(p.kinds.ops[k].?, e.path.slice(), e.hash, &words)}; + const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .addons = &brought }, p.dump_out.?); + defer restored.deinit(); + const restored_pane = restored.panes[0].?; + const art = restored_pane.addon.?.art; + try std.testing.expect(art.glyph); + try std.testing.expectEqual(pardes.Placement.Art.Palette.terminal, art.palette); + try std.testing.expect(!art.ascii); + try std.testing.expect(restored_pane.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", pardes.tagline.curTail(restored_pane)); + var kept: [64]u8 = undefined; + const slot = restored_pane.addon.?; + try std.testing.expectEqualSlices(u8, source, kept[0..slot.ops.?.dump.?(slot.st, &kept, kept.len)]); + + // And dumped again, its bytes still there. + try dump.dumpState(restored); + const again = try dump.load(gpa, .{ .tty_only = true }, restored.dump_out.?, null); + defer again.deinit(); + // Loaded as a replica loads it: a placeholder holding the record. + try std.testing.expectEqualSlices(u8, source, again.panes[0].?.addon.?.record.?); } }; diff --git a/test/pdf.zig b/test/pdf.zig index 5de72876..98e8a0ae 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -3,7 +3,6 @@ const pardes = @import("pardes"); const panes = pardes.panes; const look = pardes.look; const pdf_impl = panes.Pdf.pdf; -const image = pardes.image; const config = pardes.config; const builtins = pardes.builtins; const layout = pardes.layout; @@ -23,8 +22,8 @@ const Placement = pardes.Placement; const Shown = struct { page: u32, revision: u32, - fit: image.NativeFit, - geometry: image.NativeGeometry, + fit: pardes.panes.Pdf.NativeFit, + geometry: pardes.NativeGeometry, pixel_offset_y: f32, rgba: []const u8, iw: usize, @@ -628,7 +627,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(@as(usize, 1), first.placements.items.len); const first_place = (try shownAll(p, frame.allocator()))[0]; try std.testing.expect(first_place.rgba.len == first_place.iw * first_place.ih * 4); - try std.testing.expectEqual(image.NativeFit.width, first_place.fit); + try std.testing.expectEqual(pardes.panes.Pdf.NativeFit.width, first_place.fit); const request = panes.Pdf.renderRequest( panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport, pdf_raster_policy, @@ -964,7 +963,7 @@ test "a fling's banded pages show the reader exactly what whole pages would" { const landing = @as(f64, @floatFromInt(pv.page_starts[1] -| viewport.pixel_h / 3)); const Shot = struct { page: u32, - dst: image.PixelRect, + dst: pardes.RectPx, pixels: []u8, }; var shots: [8]Shot = undefined; @@ -1190,7 +1189,7 @@ test "a tall page is drawn at the display's resolution, in bands that are the wh fn copySourceRect( gpa: std.mem.Allocator, place: Shown, - src: image.PixelRect, + src: pardes.RectPx, ) ![]u8 { const stride = place.iw * 4; const row_len = @as(usize, src.w) * 4; @@ -1388,7 +1387,7 @@ test "PDF tint and tinted theme changes rebuild every visible raster only" { const Snapshot = struct { page: u32, revision: u32, - geometry: image.NativeGeometry, + geometry: pardes.NativeGeometry, pixel_offset_y: f32, iw: usize, ih: usize, diff --git a/test/process.zig b/test/process.zig index 674996d0..0a443a21 100644 --- a/test/process.zig +++ b/test/process.zig @@ -512,6 +512,9 @@ pub fn of(gpa: std.mem.Allocator, h: *const eh.Harness) Files { /// host it was built with. pub const Backend = enum { tui, gui }; pub var backend: Backend = .tui; +/// The image addon the build made (the runner's --image-addon=), linked +/// into each session's data directory, where its start scan finds it. +pub var image_addon: ?[:0]const u8 = null; /// A case about one frontend's own behaviour (`--tty`, a killed terminal /// editor) skips on the other. @@ -583,6 +586,10 @@ pub const Detached = struct { errdefer if (d.cap_len > 0) removeDir(d.captures()); const dir = d.root(); var bufs: [6][4096]u8 = undefined; + if (image_addon) |lib| { + for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| _ = libc.mkdir(try std.fmt.bufPrintSentinel(&bufs[5], "{s}{s}", .{ dir, sub }, 0), 0o755); + _ = libc.symlink(lib, try std.fmt.bufPrintSentinel(&bufs[5], "{s}/.local/share/pardes/addons/image.so", .{dir}, 0)); + } if (opts.init) |text| { const cfg = try std.fmt.bufPrintSentinel(&bufs[5], "{s}/config", .{dir}, 0); _ = libc.mkdir(cfg, 0o755); diff --git a/test/process_test.zig b/test/process_test.zig index e363c78a..37dd0954 100644 --- a/test/process_test.zig +++ b/test/process_test.zig @@ -22,12 +22,14 @@ const files = .{ pub fn main(init: std.process.Init) !void { const all = try init.minimal.args.toSlice(init.arena.allocator()); - // <pardes> [--backend=tui|gui] [filter] + // <pardes> [--backend=tui|gui] [--image-addon=<image.so>] [filter] var args: [3][:0]const u8 = undefined; var n: usize = 0; for (all[1..]) |a| { if (std.mem.startsWith(u8, a, "--backend=")) { process.backend = std.meta.stringToEnum(process.Backend, a["--backend=".len..]) orelse return error.Usage; + } else if (std.mem.startsWith(u8, a, "--image-addon=")) { + process.image_addon = try std.Io.Dir.cwd().realPathFileAlloc(init.io, a["--image-addon=".len..], init.arena.allocator()); } else if (n < args.len) { args[n] = a; n += 1; diff --git a/test/session.zig b/test/session.zig index db33d7b0..5b608521 100644 --- a/test/session.zig +++ b/test/session.zig @@ -13,6 +13,8 @@ const Reply = pardes.ctlfs.Reply; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; pub const Session = struct { + /// The image addon (addons/image/image.c), as the build installs it. + pub const image_addon = @import("session_options").image_addon; /// The fake addon, and its copies built wrong (build.zig). pub const fake_addons = struct { const o = @import("session_options"); diff --git a/test/snapshot.zig b/test/snapshot.zig index d93face2..26022a41 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -86,6 +86,9 @@ var careful = false; /// abs path of the deterministic mock language server the build handed over /// (--lspmock=); null leaves the protocol client fully disabled for the run var lspmock_bin: ?[:0]const u8 = null; +/// abs path of the image addon the build made (--image-addon=), linked into +/// each script's data directory, where a session's start scan finds it +var image_addon: ?[:0]const u8 = null; var record_dir: ?[]const u8 = null; /// --tape=DIR: each session records its tape there (PARDES_RECORD, src/tape.zig) /// and the script fails unless every tape replays without diverging. @@ -133,6 +136,8 @@ pub fn main(init: std.process.Init) !void { trace_stable = true; } else if (std.mem.startsWith(u8, a, "--lspmock=")) { lspmock = try absPath(arena, orig_cwd, a["--lspmock=".len..]); + } else if (std.mem.startsWith(u8, a, "--image-addon=")) { + image_addon = try arena.dupeSentinel(u8, try absPath(arena, orig_cwd, a["--image-addon=".len..]), 0); } else if (std.mem.startsWith(u8, a, "--record=")) { record_dir = try absPath(arena, orig_cwd, a["--record=".len..]); } else if (std.mem.startsWith(u8, a, "--tape=")) { @@ -165,6 +170,7 @@ pub fn main(init: std.process.Init) !void { std.mem.eql(u8, a, "--no-retry") or std.mem.eql(u8, a, "--trace-stable") or std.mem.startsWith(u8, a, "--lspmock=") or + std.mem.startsWith(u8, a, "--image-addon=") or std.mem.startsWith(u8, a, "--record=") or std.mem.startsWith(u8, a, "--tape=") or std.mem.eql(u8, a, "--dump") or @@ -628,6 +634,13 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const // XDG directory that points outside this per-snapshot fake home. const config_home = try std.fmt.allocPrintSentinel(arena, "{s}/.config", .{home}, 0); _ = setenv("XDG_CONFIG_HOME", config_home, 1); + // ...and its data directory (dumps, the addons its start scan loads). + const data_home = try std.fmt.allocPrintSentinel(arena, "{s}/.local/share", .{home}, 0); + _ = setenv("XDG_DATA_HOME", data_home, 1); + if (image_addon) |lib| { + for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| try mkdir(arena, try std.fmt.allocPrint(arena, "{s}{s}", .{ home, sub }), true); + if (libc.symlink(lib, try std.fmt.allocPrintSentinel(arena, "{s}/pardes/addons/image.so", .{data_home}, 0)) != 0) return error.SymlinkFailed; + } // ...and it is not empty: the DEFAULT shell is $SHELL, whatever this // machine's user logs in with (fish's prompt carries a hostname and its // greeting a version), so a golden taken |
