summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-06 06:24:42 -0300
committerGabriel Schneider <[email protected]>2026-11-06 11:19:44 -0300
commitc1917b949b9580de8bf0977874a210f0266812da (patch)
tree447dd2235ea00634f662cd3becf4bceb8a895f41 /test
parent76c55b5bce0f181b0b15b16596c900397dfef544 (diff)
downloadpardes-c1917b949b9580de8bf0977874a210f0266812da.tar.gz
pardes-c1917b949b9580de8bf0977874a210f0266812da.zip
kinds #14, the core's PDF code gone: pdf.zig and pdf_view.zig leave and every pdf_enabled branch with them; look, Jump, Recent, dumps (one from before the addon opens as its pane), the watch, mouse, keys, the rail and the tag go through Kind for any kind's pane; test/pdf.zig's behaviours are T1 cases over 9P (addons_pdf.zig) and pane cases (a Shadow over a replica, a file changed under it), the harnesses load pdf.so by path
Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
Diffstat (limited to 'test')
-rw-r--r--test/behaviour.zig1
-rw-r--r--test/behaviour/addons_pdf.zig231
-rw-r--r--test/behaviour/keys.zig48
-rw-r--r--test/image_harness.zig11
-rw-r--r--test/mode.zig17
-rw-r--r--test/panes.zig313
-rw-r--r--test/pdf.zig2246
-rw-r--r--test/process.zig18
-rw-r--r--test/process_test.zig8
-rw-r--r--test/session.zig29
-rw-r--r--test/snapshot.zig24
11 files changed, 484 insertions, 2462 deletions
diff --git a/test/behaviour.zig b/test/behaviour.zig
index 685128df..de0cb83c 100644
--- a/test/behaviour.zig
+++ b/test/behaviour.zig
@@ -4,6 +4,7 @@
//! so a test sees the session as a 9P client does.
test {
_ = @import("behaviour/addons.zig");
+ _ = @import("behaviour/addons_pdf.zig");
_ = @import("behaviour/addresses.zig");
_ = @import("behaviour/builtins.zig");
_ = @import("behaviour/callstack.zig");
diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig
new file mode 100644
index 00000000..f3c2d872
--- /dev/null
+++ b/test/behaviour/addons_pdf.zig
@@ -0,0 +1,231 @@
+//! docs/typ/reference.typ, Addons <addons> and the PDF passages of Panes
+//! <panes> and Look and exec <look-and-exec>: a PDF is a pane of the pdf
+//! addon (addons/pdf/pdf.c), driven here as a 9P client drives it. What
+//! test/pdf.zig asked of the core's PDF code before it left the core.
+const std = @import("std");
+const Session = @import("session").Session;
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+/// The pictures /screen places for pane `serial`: their keys and the part
+/// of their pixels shown, `[x, y, w, h]`.
+const Shown = struct { key: []const u8, src: [4]i64 };
+
+fn shown(s: *Session, serial: u32) ![]Shown {
+ const a = s.arena.allocator();
+ const json = try std.json.parseFromSliceLeaky(std.json.Value, a, try s.read("/screen"), .{});
+ var out: std.ArrayList(Shown) = .empty;
+ const images = json.object.get("images") orelse return out.items;
+ for (images.array.items) |im| {
+ if (im.object.get("serial").?.integer != serial) continue;
+ var src: [4]i64 = undefined;
+ for (im.object.get("src").?.array.items, &src) |v, *o| o.* = v.integer;
+ const key = im.object.get("key").?;
+ try out.append(a, .{ .key = if (key == .string) key.string else try std.fmt.allocPrint(a, "{d}", .{key.integer}), .src = src });
+ }
+ return out.items;
+}
+
+fn ctlOf(s: *Session, n: u32) ![]const u8 {
+ return s.read(s.at("/pane/{d}/ctl", .{n}));
+}
+
+test "addons: a PDF is the pdf addon's pane, its pages pictures, its page in its tag, its fit and tint in its ctl and stepped by its words, all of it back from a Dump" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ try std.testing.expect(has(try s.read("/index"), " pdf "));
+ try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "pdf 1 2.1 1 /"));
+ const pages = (try s.pdfPage(n))[1];
+ try std.testing.expectEqual(@as(u32, 16), pages);
+ // Its first page, a picture over its body.
+ const first = try shown(&s, n);
+ try std.testing.expect(first.len >= 1);
+ // Its tag: its page, then the core's art words (it placed a picture),
+ // its path and its kind's words.
+ const tag = try s.read(s.at("/pane/{d}/tag", .{n}));
+ try std.testing.expect(std.mem.startsWith(u8, tag, "[1/16] petscii:on palette:commodore ascii:on /"));
+ try std.testing.expect(has(tag, "/docs/design.pdf Term PdfSections PdfTint PdfFit Collapse Del"));
+ try std.testing.expect(has(try ctlOf(&s, n), " fit:width tint:filtered mode:normal "));
+ // The words: bare they step, given a value they take it, any other
+ // value refused; another pane's is refused and leaves the PDF alone.
+ const ctl = s.at("/pane/{d}/ctl", .{n});
+ try s.write(ctl, "PdfFit\n");
+ try std.testing.expect(has(try ctlOf(&s, n), " fit:height "));
+ try s.write(ctl, "PdfTint full\n");
+ try std.testing.expect(has(try ctlOf(&s, n), " tint:full "));
+ // A tint is a page drawn again: another picture.
+ const tinted = try shown(&s, n);
+ try std.testing.expect(tinted.len >= 1 and !std.mem.eql(u8, tinted[0].key, first[0].key));
+ _ = try s.refused(ctl, "PdfTint loud\n");
+ try std.testing.expect(has(s.said, "PdfTint takes disabled, filtered or full"));
+ const text = std.mem.sliceTo(try s.read("/index"), ' ');
+ _ = try s.refused(s.at("/pane/{s}/ctl", .{text}), "PdfFit\n");
+ try std.testing.expect(has(try ctlOf(&s, n), " fit:height tint:full "));
+ // Its last page, then a Dump: restored it is there, as it was.
+ try s.keys("ge");
+ try std.testing.expectEqual(@as(u32, 16), (try s.pdfPage(n))[0]);
+ try s.write("/ctl", "Dump\n");
+ const label = try s.arena.allocator().dupe(u8, std.mem.sliceTo(try s.read("/dumps"), ' '));
+ try s.write(ctl, "Del\n");
+ try s.write("/ctl", s.at("Restore {s}\n", .{label}));
+ // (A test's session steps only on its writes: a key that moves nothing
+ // is the step after the Restore a host's wake makes.)
+ try s.keys("0");
+ var back: u32 = 0;
+ var lines = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (lines.next()) |line| if (has(line, " pdf ")) {
+ back = try std.fmt.parseInt(u32, std.mem.sliceTo(line, ' '), 10);
+ };
+ try std.testing.expect(back != 0);
+ try std.testing.expectEqual(@as(u32, 16), (try s.pdfPage(back))[0]);
+ try std.testing.expect(has(try ctlOf(&s, back), " fit:height tint:full "));
+ try std.testing.expect((try shown(&s, back)).len >= 1);
+}
+
+test "addons: a PDF's / lists its hits as file.pdf:P:H rows in a +Search, n walks them, a Look of one turns to its page, Esc drops the search first and then leaves, and a hit not there is a miss" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ try s.keys("/pardes\r");
+ var rows: []const u8 = "";
+ var it = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (it.next()) |line| if (has(line, "+Search")) {
+ rows = try s.read(s.at("/pane/{s}/body", .{std.mem.sliceTo(line, ' ')}));
+ };
+ // (Each row its place, then the text, as a +Search lays its rows out.)
+ try std.testing.expect(std.mem.startsWith(u8, rows, "design.pdf:1:1\n"));
+ try std.testing.expect(std.mem.count(u8, rows, "design.pdf:") > 3);
+ // At its first hit's page; from the PDF n walks its rows (the
+ // keyboard on the next, selected), and a Look of a row turns there.
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ var search: u32 = 0;
+ it = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (it.next()) |line| if (has(line, "+Search")) {
+ search = try std.fmt.parseInt(u32, std.mem.sliceTo(line, ' '), 10);
+ };
+ try s.write("/focus", s.at("{d}\n", .{n}));
+ try s.keys("n");
+ try std.testing.expectEqual(search, try s.focused());
+ var last: []const u8 = "";
+ var places = std.mem.tokenizeScalar(u8, rows, '\n');
+ while (places.next()) |row| if (std.mem.startsWith(u8, row, "design.pdf:")) {
+ last = row;
+ };
+ const page = try std.fmt.parseInt(u32, last["design.pdf:".len..std.mem.indexOfScalarPos(u8, last, "design.pdf:".len, ':').?], 10);
+ try s.write(s.at("/pane/{d}/look", .{search}), s.at("{s}\n", .{last}));
+ try std.testing.expectEqual(page, (try s.pdfPage(n))[0]);
+ try std.testing.expectEqual(n, try s.focused());
+ // A hit there is a place; one not there a miss said with its path.
+ const look = s.at("/pane/{d}/look", .{n});
+ try s.write(look, ":1:1\n");
+ _ = try s.refused(look, ":1:99\n");
+ try std.testing.expect(has(try s.read("/log"), "design.pdf has no search hit 99 on page 1"));
+ // Esc: the search goes first (no hit is a place now), then the pane.
+ try s.keys("\x1b");
+ try std.testing.expectEqual(n, try s.focused());
+ _ = try s.refused(look, ":1:1\n");
+ try s.keys("\x1b");
+ try std.testing.expect(try s.focused() != n);
+}
+
+test "addons: a PDF's f is its PdfSections, its outline as places a Look in it goes to (none once the PDF is gone), and a jump back over a far one is Ctrl-o's, Forward's on, two places on a page a window apart two" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("test/pdf-fixtures/outline.pdf");
+ try s.keys("f");
+ var list: u32 = 0;
+ var it = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (it.next()) |line| if (has(line, "/+PdfSections")) {
+ list = try std.fmt.parseInt(u32, std.mem.sliceTo(line, ' '), 10);
+ };
+ try std.testing.expect(list != 0);
+ const body = try s.read(s.at("/pane/{d}/body", .{list}));
+ try std.testing.expect(std.mem.startsWith(u8, body, "outline.pdf:"));
+ // The last row of a section in it: its page, where a Look lands.
+ var last: []const u8 = "";
+ var rows = std.mem.tokenizeScalar(u8, body, '\n');
+ while (rows.next()) |row| if (std.mem.startsWith(u8, row, "outline.pdf:")) {
+ last = row;
+ };
+ const place = last[0..std.mem.indexOfScalar(u8, last, ' ').?];
+ var fields = std.mem.splitScalar(u8, place, ':');
+ _ = fields.next();
+ const page = try std.fmt.parseInt(u32, fields.next().?, 10);
+ try s.write(s.at("/pane/{d}/look", .{list}), s.at("{s}\n", .{place}));
+ try std.testing.expectEqual(page, (try s.pdfPage(n))[0]);
+ // A jump far: Ctrl-o goes back, Ctrl-i on.
+ try s.write(s.at("/pane/{d}/look", .{n}), ":1\n");
+ try s.keys("ge");
+ const end = (try s.pdfPage(n))[0];
+ try s.keys("\x0f");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ // (Ctrl-i is Tab without kitty's keyboard: its word, Forward.)
+ try s.write("/ctl", "Forward\n");
+ try std.testing.expectEqual(end, (try s.pdfPage(n))[0]);
+ // Two places on page 1 more than a window apart (the second its 0.8,
+ // as its `where` says a place) are two visits: Ctrl-o from a far one
+ // goes to the second, then the first, where they were.
+ const look = s.at("/pane/{d}/look", .{n});
+ try s.write(look, ":1\n");
+ const top = (try shown(&s, n))[0].src[1];
+ try s.write(look, ":1:0.8\n");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ const down = (try shown(&s, n))[0].src[1];
+ try std.testing.expect(down > top);
+ try s.write(look, ":3\n");
+ try s.keys("\x0f");
+ try std.testing.expectEqual(down, (try shown(&s, n))[0].src[1]);
+ try s.keys("\x0f");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ try std.testing.expectEqual(top, (try shown(&s, n))[0].src[1]);
+ // The PDF gone, its list's rows are no place: not another pane's.
+ try s.write(s.at("/pane/{d}/ctl", .{n}), "Del\n");
+ _ = try s.refused(s.at("/pane/{d}/look", .{list}), s.at("{s}\n", .{place}));
+ try std.testing.expect(has(try s.read("/log"), "the pane its list is of is gone"));
+}
+
+test "addons: a closed PDF is in Recent and its jumps, and a jump back to it opens it at its page; a tall page is shown a band of it at a time" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ try s.write(s.at("/pane/{d}/look", .{n}), ":5\n");
+ const name = std.mem.trimEnd(u8, try s.read(s.at("/pane/{d}/name", .{n})), "\n");
+ // From a scratch, Back is the nearest place of any file: the PDF's,
+ // closed meanwhile, opened again at its page.
+ const scratch = try s.newPane();
+ try s.write("/focus", s.at("{d}\n", .{scratch}));
+ try s.write(s.at("/pane/{d}/ctl", .{n}), "Del\n");
+ try std.testing.expect(has(try s.read("/recent"), s.at("closed {s}", .{name})));
+ try s.keys("\x0f");
+ const again = try s.focused();
+ try std.testing.expect(again != scratch);
+ try std.testing.expectEqual(@as(u32, 5), (try s.pdfPage(again))[0]);
+ // A page 9000 points tall: a band of its rows, never the whole.
+ const tall = try s.lookFile("test/pdf-fixtures/tall.pdf");
+ const bands = try shown(&s, tall);
+ try std.testing.expect(bands.len >= 1);
+ try std.testing.expect(bands[0].src[3] <= 8192);
+}
+
+test "addons: a PDF's body is its page's text layer, read from any offset and never written; a truncated PDF is a refused Look saying why" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("test/pdf-fixtures/links.pdf");
+ const body = s.at("/pane/{d}/body", .{n});
+ const whole = try s.arena.allocator().dupe(u8, try s.read(body));
+ try std.testing.expect(has(whole, "target.txt"));
+ // (Read from an offset, as a mount's chunked reads ask.)
+ try std.testing.expectEqualStrings(whole[3..], try s.readAt(body, 3, 4096));
+ try std.testing.expect(try s.refused(body, "more\n") != 0);
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "test/pdf-fixtures/links.pdf", s.arena.allocator(), .unlimited);
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "cut.pdf", .data = bytes[0..40] });
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)];
+ _ = try s.refused("/look", s.at("{s}/cut.pdf\n", .{dir}));
+ try std.testing.expect(has(s.said, "cut.pdf") and has(s.said, "not a PDF pardes can read"));
+}
diff --git a/test/behaviour/keys.zig b/test/behaviour/keys.zig
index eeaacf7d..879ff441 100644
--- a/test/behaviour/keys.zig
+++ b/test/behaviour/keys.zig
@@ -136,28 +136,33 @@ test "keys: a count or a prefix a click or a change of pane cancels leaves nothi
}
}
-test "keys: a PDF shown as text turns pages for the moving keys, counted, and the editing keys do nothing" {
+test "keys: a PDF's moving keys scroll its strip, counted, gg G and ge go to pages, and the editing keys do nothing" {
var s = try Session.initFile(std.testing.allocator, "x\n");
defer s.deinit();
const n = try s.lookFile("docs/design.pdf");
const pages = (try s.pdfPage(n))[1];
try std.testing.expect(pages > 3);
- // j k, Ctrl-d Ctrl-u, Ctrl-f Ctrl-b: a page each, counted.
- for ([_][]const u8{ "2j", "2k", "2\x04", "2\x15", "2\x06", "2\x02" }, 0..) |keys, i| {
- try s.keys(keys);
- try std.testing.expectEqual(@as(u32, if (i % 2 == 0) 3 else 1), (try s.pdfPage(n))[0]);
- }
- for ([_]struct { []const u8, u32 }{ .{ "ge", pages }, .{ "gg", 1 }, .{ "3gg", 3 }, .{ "2G", 2 } }) |step| {
+ for ([_]struct { []const u8, u32 }{ .{ "ge", pages }, .{ "gg", 1 }, .{ "3gg", 3 }, .{ "2G", 2 }, .{ "G", pages }, .{ "gg", 1 } }) |step| {
try s.keys(step[0]);
try std.testing.expectEqual(step[1], (try s.pdfPage(n))[0]);
}
+ // j a cell's pixels, Ctrl-f a window's: a count moves that many, so
+ // thirty windows down is past the first page (a window is a few rows
+ // of a page here), thirty back at the first, and k at the top stays.
+ try s.keys("k");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ try s.keys("30\x06");
+ try std.testing.expect((try s.pdfPage(n))[0] > 1);
+ try s.keys("30\x02");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ try s.keys("200j");
+ try std.testing.expect((try s.pdfPage(n))[0] > 1);
+ try s.keys("2G");
// Consumed, with their count: the page stays, no selection begins, and
- // the next j is one page.
- try s.keys("4dv|");
+ // no mode changes.
+ try s.keys("4dv|i");
try std.testing.expectEqual(@as(u32, 2), (try s.pdfPage(n))[0]);
try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{n})), " mode:normal "));
- try s.keys("j");
- try std.testing.expectEqual(@as(u32, 3), (try s.pdfPage(n))[0]);
}
test "keys: SPC j n and SPC j p in plain text select its places, never a comment's slashes, round the end, opening nothing" {
@@ -334,23 +339,26 @@ test "keys: a PDF in normal mode keeps : (its tag and back), SPC (a leader, canc
var s = try Session.initFile(std.testing.allocator, "x\n");
defer s.deinit();
const n = try s.lookFile("docs/design.pdf");
- const body = (try s.cursor()).?;
- const tag = (try s.where("docs/design.pdf [1/"))[1];
+ // A page has no text cursor: the body shows none.
+ try std.testing.expect(try s.cursor() == null);
+ _ = try s.pdfPage(n);
+ const tag = (try s.where("[1/"))[1];
try s.keys(":");
+ // On its tag, which runs to three rows (its path, the core's art words).
const on_tag = (try s.cursor()).?[1];
- try std.testing.expect(on_tag == tag or on_tag == tag + 1);
+ try std.testing.expect(on_tag >= tag and on_tag <= tag + 2);
try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{n})), " mode:normal "));
try s.keys(":");
- try std.testing.expectEqual(body, (try s.cursor()).?);
- // The leader shows its keys at the row's end until one it has not.
+ try std.testing.expect(try s.cursor() == null);
+ // The leader shows its keys until one it has not.
try s.keys(" ");
- try std.testing.expect(std.mem.endsWith(u8, std.mem.trimEnd(u8, try screenRow(&s, body[1]), " "), " SPC"));
+ try std.testing.expect(std.mem.indexOf(u8, try s.screen(), " SPC") != null);
try s.keys("!");
- try std.testing.expect(!std.mem.endsWith(u8, std.mem.trimEnd(u8, try screenRow(&s, body[1]), " "), " SPC"));
+ try std.testing.expect(std.mem.indexOf(u8, try s.screen(), " SPC") == null);
try s.keys("/");
- try std.testing.expect(!std.meta.eql(body, (try s.cursor()).?));
+ try std.testing.expect(try s.cursor() != null);
try std.testing.expectEqual(n, try s.focused());
try s.keys("\x1b");
- try std.testing.expectEqual(body, (try s.cursor()).?);
+ try std.testing.expect(try s.cursor() == null);
try std.testing.expectEqual(n, try s.focused());
}
diff --git a/test/image_harness.zig b/test/image_harness.zig
index 02e6690b..46564dee 100644
--- a/test/image_harness.zig
+++ b/test/image_harness.zig
@@ -36,14 +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);
- // <pardes> <image.so> tui|gui [pdf]
- if (args.len != 4 and args.len != 5) return error.BadArgs;
+ // <pardes> <image.so> tui|gui [pdf <pdf.so>]
+ if (args.len != 4 and args.len != 6) return error.BadArgs;
const exe = try arena.dupeSentinel(u8, args[1], 0);
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 pdf_mode = args.len == 6 and std.mem.eql(u8, args[4], "pdf");
+ if (args.len == 6 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);
@@ -60,6 +60,7 @@ pub fn main(init: std.process.Init) !void {
_ = 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;
+ if (pdf_mode) if (libc.symlink(try std.Io.Dir.cwd().realPathFileAlloc(init.io, args[5], arena), try std.fmt.allocPrintSentinel(arena, "{s}/data/pardes/addons/pdf.so", .{base}, 0)) != 0) return error.SymlinkFailed;
_ = setenv("HISTFILE", "/dev/null", 1);
_ = setenv("TERM", "xterm-256color", 1);
_ = setenv("LC_ALL", "C", 1);
@@ -84,7 +85,7 @@ 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", "data/pardes/addons/image.so" };
+ const names = [_][]const u8{ "native.ppm", "pages.pdf", "latest.ppm", "latest.ppm.tmp", ".bash_history", "data/pardes/addons/image.so", "data/pardes/addons/pdf.so" };
for (names) |name| {
const path = std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ base, name }, 0) catch continue;
_ = libc.unlink(path);
diff --git a/test/mode.zig b/test/mode.zig
index 7335b4ef..1f21c7db 100644
--- a/test/mode.zig
+++ b/test/mode.zig
@@ -89,25 +89,10 @@ test "Mode from actual tag Exec preserves parked file and output insert transact
}
}
-test "Mode leaves image and PDF document modes unchanged" {
+test "Mode leaves a kind's pane (a picture) as it is" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
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) {
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try panes.Pdf.pdf.testFixture(std.testing.allocator, "links.pdf");
- defer std.testing.allocator.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mode.pdf", .data = bytes });
- var buffer: [4096]u8 = undefined;
- const len = try tmp.dir.realPath(std.testing.io, &buffer);
- const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/mode.pdf", .{buffer[0..len]});
- defer std.testing.allocator.free(path);
- const document = try panes.Pdf.openPane(p, 2, path, 1, .last);
- const page = document.pdf.?.page;
- try mode(p, 2, .normal);
- try std.testing.expectEqual(page, document.pdf.?.page);
- }
}
diff --git a/test/panes.zig b/test/panes.zig
index 28a884ab..a19af1a6 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -2307,154 +2307,6 @@ const ImageTests = struct {
}
};
-const PdfTests = struct {
- const enabled = panes.Pdf.enabled;
- const pdf = panes.Pdf.pdf;
- const Point = panes.Pdf.Point;
- const Document = panes.Pdf.Document;
- const State = panes.Pdf.State;
- const probeWord = panes.Pdf.probeWord;
- const pointAtGeometry = panes.Pdf.pointAtGeometry;
- const SectionRows = panes.Pdf.SectionRows;
-
- test "feature-off PDF state is zero-sized" {
- if (!enabled) try std.testing.expectEqual(@as(usize, 0), @sizeOf(State));
- }
-
- test "PDF section rows preserve DFS ordinals and sanitise hierarchy" {
- if (!enabled) return;
- const entries = [_]pdf.OutlineEntry{
- .{ .depth = 0, .title = null, .destination = .none },
- .{ .depth = 1, .title = " Child\n\tTitle\x01 Café \u{2028} Next ", .destination = .{ .internal = .{ .page = 2, .x = 12, .y = 34 } } },
- .{ .depth = 0, .title = "", .destination = .{ .internal = .{ .page = 0, .x = null, .y = null } } },
- .{ .depth = 0, .title = "External", .destination = .{ .external = "https://example.com/manual" } },
- .{ .depth = 0, .title = "Dead branch", .destination = .none },
- .{ .depth = 0, .title = "Unsafe", .destination = .{ .external = "javascript:alert" } },
- .{ .depth = 0, .title = "Linked branch", .destination = .none },
- .{ .depth = 1, .title = "Deep link", .destination = .{ .external = "https://example.com/deep" } },
- };
- const rows = try SectionRows.render(std.testing.allocator, "/tmp/manual.pdf", &entries);
- defer std.testing.allocator.free(rows);
- try std.testing.expectEqualStrings(
- "manual.pdf:3:1 [untitled]\n" ++
- "manual.pdf:3:2 Child Title Café Next\n" ++
- "manual.pdf:1:3 [empty title]\n" ++
- "https://example.com/manual External\n" ++
- "https://example.com/deep Linked branch\n" ++
- "https://example.com/deep Deep link\n",
- rows,
- );
- try std.testing.expect(SectionRows.resolve(&entries, 4) == null);
- try std.testing.expect(SectionRows.resolve(&entries, 5) == null);
- const resolved = try SectionRows.resolveOrdinals(std.testing.allocator, &entries);
- defer std.testing.allocator.free(resolved);
- for (entries, 0..) |_, ordinal| {
- const single = SectionRows.resolve(&entries, ordinal);
- if (resolved[ordinal] == std.math.maxInt(usize)) {
- try std.testing.expect(single == null);
- } else {
- const bulk = SectionRows.usableDestination(entries[resolved[ordinal]].destination) orelse
- return error.MissingBulkPdfSectionDestination;
- try std.testing.expect(single != null);
- try std.testing.expect(std.meta.eql(single.?, bulk));
- }
- }
-
- // Every allocation site in the ordinal table and output growth remains
- // atomic: the testing allocator sees each induced failure cleaned up
- // before the first index at which the whole render can succeed.
- var rendered = false;
- for (0..64) |fail_index| {
- var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{
- .fail_index = fail_index,
- });
- const failure_gpa = failing.allocator();
- const attempt = SectionRows.render(failure_gpa, "/tmp/manual.pdf", &entries) catch |err| {
- try std.testing.expectEqual(error.OutOfMemory, err);
- continue;
- };
- failure_gpa.free(attempt);
- rendered = true;
- break;
- }
- try std.testing.expect(rendered);
- }
-
- test "bulk PDF section resolution matches single Look policy across DFS boundaries" {
- if (!enabled) return;
- const entries = [_]pdf.OutlineEntry{
- .{ .depth = 0, .title = "Resolved root", .destination = .none },
- .{ .depth = 1, .title = "Unsafe branch", .destination = .{ .external = "javascript:unsafe" } },
- .{ .depth = 2, .title = "Safe grandchild", .destination = .{ .internal = .{ .page = 1, .x = 4, .y = 8 } } },
- .{ .depth = 1, .title = "Unresolved child", .destination = .none },
- .{ .depth = 1, .title = "Sibling", .destination = .{ .internal = .{ .page = 2, .x = null, .y = null } } },
- .{ .depth = 0, .title = "Unresolved root", .destination = .none },
- .{ .depth = 0, .title = "Next root", .destination = .{ .internal = .{ .page = 3, .x = null, .y = null } } },
- };
- const bulk = try SectionRows.resolveOrdinals(std.testing.allocator, &entries);
- defer std.testing.allocator.free(bulk);
- const none = std.math.maxInt(usize);
- try std.testing.expectEqualSlices(usize, &.{ 2, none, 2, none, 4, none, 6 }, bulk);
- for (entries, 0..) |_, ordinal| {
- const single = SectionRows.resolve(&entries, ordinal);
- if (bulk[ordinal] == none) {
- try std.testing.expect(single == null);
- } else {
- const destination = SectionRows.usableDestination(entries[bulk[ordinal]].destination) orelse
- return error.MissingBoundaryPdfSectionDestination;
- try std.testing.expect(single != null);
- try std.testing.expect(std.meta.eql(single.?, destination));
- }
- }
- }
-
- test "PDF word probe owns quads and text without a selection object" {
- if (comptime !enabled) return;
- const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "docs/design.pdf", std.testing.allocator, .unlimited);
- defer std.testing.allocator.free(bytes);
- var document = try Document.openBytes(bytes);
- defer document.deinit();
- var found = try document.search(std.testing.allocator, 0, "Pardes");
- defer found.deinit(std.testing.allocator);
- const quad = found.quads[0].quad;
- const point = Point{
- .x = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4,
- .y = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4,
- };
-
- // Exactly one shared probe exercises the primitive used by both UI paths;
- // click-vs-hover equivalence belongs to production structure, not a second
- // test that can only restate this MuPDF result.
- var probe = (try probeWord(&document, std.testing.allocator, 0, point)) orelse
- return error.MissingPdfWordProbe;
- defer probe.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, 0), probe.page);
- try std.testing.expect(probe.quads.len > 0);
- try std.testing.expect(std.ascii.findIgnoreCase(probe.text, "Pardes") != null);
- }
-
- test "PDF point mapping restores band origin and fractional placement" {
- if (comptime !enabled) return;
- const point = pointAtGeometry(
- .{
- .src = .{ .x = 20, .y = 10, .w = 40, .h = 20 },
- .dst = .{ .x = 100, .y = 30, .w = 80, .h = 20 },
- },
- -0.5,
- 200,
- 200,
- 80,
- 120,
- 34,
- false,
- ) orelse return error.MissingPdfMappedPoint;
- // x: src 30; y: band 80 + local src 14. The returned coordinates address
- // pixel centers, matching MuPDF's normalized page-space contract.
- try std.testing.expectApproxEqAbs(@as(f32, 30.5 / 200.0), point.x, 0.000_001);
- try std.testing.expectApproxEqAbs(@as(f32, 94.5 / 200.0), point.y, 0.000_001);
- }
-};
-
const TerminalTests = struct {
// Tests asserting raw ANSI indices explicitly select helix, whose palette
// is inherited. Native-palette coverage lives in the overlay/eviction and
@@ -3636,13 +3488,11 @@ test {
_ = @import("output.zig");
_ = @import("column_drag.zig");
_ = @import("mode.zig");
- _ = @import("pdf.zig");
_ = @import("fs_namespace.zig");
_ = @import("hxdiff.zig");
_ = FileTests;
_ = OutputTests;
_ = ImageTests;
- _ = PdfTests;
_ = TerminalTests;
}
@@ -3858,3 +3708,166 @@ test "a terminal keeps its tag and two body rows through a squeeze, a drag and a
p.sync();
try std.testing.expect(p.view().rects[term].h >= p.panes[term].?.tag_rows + layout.min_body_rows);
}
+
+// ---- a PDF: a pane of the pdf addon (addons/pdf/pdf.c) ----
+
+const PdfAddon = struct {
+ const addons = @import("test_addons");
+ const pdf_lib: []const u8 = if (addons.has_pdf) addons.pdf else "";
+
+ /// Its jobs, run here and answered as a host's workers answer: an
+ /// event `land` steps (a core's own update, or an authority's). An
+ /// authority's host takes them as a session's does (`job`): one run
+ /// inside the effect would be an update a replica cannot replay.
+ fn jobs(core: *Pardes, land: anytype) !void {
+ while (core.nextEffect()) |e| if (e == .job) asked.append(e.job);
+ while (asked.pop()) |a| {
+ const j = pardes.host_io.KindJob.take(core, a.pane, a.serial, a.token) orelse continue;
+ defer j.drop();
+ j.run();
+ try land.step(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } });
+ }
+ }
+
+ const Asked = struct { pane: u8, serial: u32, token: u32 };
+ var asked: struct {
+ items: [16]Asked = undefined,
+ n: usize = 0,
+ fn append(q: *@This(), j: anytype) void {
+ if (q.n < q.items.len) q.items[q.n] = .{ .pane = j.pane, .serial = j.serial, .token = j.token };
+ q.n += @intFromBool(q.n < q.items.len);
+ }
+ fn pop(q: *@This()) ?Asked {
+ if (q.n == 0) return null;
+ q.n -= 1;
+ return q.items[q.n];
+ }
+ } = .{};
+
+ const host_vtable: pardes.Host.VTable = .{
+ .watched = struct {
+ fn f(_: ?*anyopaque) bool {
+ return false;
+ }
+ }.f,
+ .job = struct {
+ fn f(_: ?*anyopaque, pane: u8, serial: u32, token: u32) void {
+ asked.append(.{ .pane = pane, .serial = serial, .token = token });
+ }
+ }.f,
+ };
+
+ test "a client without the pdf addon shows a PDF pane as the session's frames of it, its pages by key, and its wheel goes to the session" {
+ if (!addons.has_pdf) return error.SkipZigTest;
+ const R = pardes.replica;
+ const gpa = std.testing.allocator;
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false);
+ defer a.deinit();
+ var screens: R.Screens = .init(gpa);
+ defer screens.deinit(a.core);
+ const peer = try screens.addPeer();
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
+ defer r.deinit();
+ const Land = struct {
+ a: *R.Authority,
+ r: *R.Replica,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ l.r.confirm(try l.a.local(ev));
+ }
+ };
+ const land: Land = .{ .a = a, .r = r };
+ var words: [64]pardes.Kind.LoadedWord = undefined;
+ var why: pardes.Kind.Buf(160) = .{};
+ const lib = pardes.Addon.readLoaded(pdf_lib, &words, &why);
+ try land.step(.{ .addon = .{ .op = .load, .pane = 0, .kind = &lib } });
+ try std.testing.expect(r.core().kinds.ops[r.core().kinds.n - 1] == null);
+ var buf: [4096]u8 = undefined;
+ const real = try std.Io.Dir.cwd().realPathFile(std.testing.io, "docs/design.pdf", &buf);
+ var line: [4200]u8 = undefined;
+ try land.step(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{buf[0..real]}) });
+ for (0..3) |_| {
+ try land.step(.tick);
+ try jobs(a.core, land);
+ }
+ // Its frame crosses: the replica draws the pane as the session
+ // painted it, its pages placed by key, its page in its tag.
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const deliver = struct {
+ fn f(au: *R.Authority, sc: *R.Screens, pe: u16, re: *R.Replica) !void {
+ var msgs: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (msgs.items) |m| std.testing.allocator.free(m);
+ msgs.deinit(std.testing.allocator);
+ }
+ try sc.flush(au.core, pe, re.view, &msgs);
+ for (msgs.items) |m| if (re.screen(m)) |reply| {
+ _ = try sc.take(au.core, pe, reply);
+ };
+ }
+ }.f;
+ _ = try a.core.render(arena.allocator());
+ // (A kind's prefix is its last frame's, and the tag a step's: a
+ // Shadow's is the authority's last step's.)
+ try land.step(.tick);
+ try deliver(a, &screens, peer, r);
+ const id = for (r.core().panes, 0..) |slot, i| {
+ if (slot) |pane| if (pane.addon != null) break i;
+ } else return error.NoPdfPane;
+ const shown = try r.core().render(arena.allocator());
+ var placed: usize = 0;
+ for (shown.placements.items) |pl| placed += @intFromBool(pl.pane == id);
+ try std.testing.expect(placed >= 1);
+ try std.testing.expect(std.mem.startsWith(u8, try pardes.tagline.tagPrefix(r.core(), r.core().panes[id].?), "[1/16]"));
+ // A wheel at the replica: the session's kind takes it, and the
+ // replica shows where the session's strip went.
+ const before = a.core.panes[id].?.addon.?.thumb_at;
+ const rect = r.core().view().rects[id];
+ for (0..20) |_| r.confirm(try a.take(try r.input(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + rect.w / 2, .row = rect.y + rect.h / 2 } })));
+ try jobs(a.core, land);
+ _ = try a.core.render(arena.allocator());
+ try std.testing.expect(a.core.panes[id].?.addon.?.thumb_at > before);
+ try deliver(a, &screens, peer, r);
+ r.settle();
+ try std.testing.expect(r.diverged == null);
+ }
+
+ test "a PDF pane whose file changes on disk opens again from it at its page, its fit kept" {
+ if (!addons.has_pdf) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try std.Io.Dir.cwd().copyFile("docs/design.pdf", tmp.dir, "live.pdf", std.testing.io, .{});
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)];
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .tty_only = true });
+ defer p.deinit();
+ pardes.Addon.perform(p, .load, 0, pdf_lib);
+ var line: [4200]u8 = undefined;
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, try std.fmt.bufPrint(&line, "Look {s}/live.pdf:5", .{dir})));
+ const id = p.view().active;
+ try std.testing.expect(p.executeBuiltinLine(id, "PdfFit height"));
+ const Self = struct {
+ core: *Pardes,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ l.core.update(ev);
+ }
+ };
+ p.update(.tick);
+ try jobs(p, Self{ .core = p });
+ // Another file under its name (an outline's three pages): opened
+ // again, on the page it can still be on, as height-fitted.
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "test/pdf-fixtures/outline.pdf", p.scratch.allocator(), .unlimited) });
+ try std.testing.expect(p.reloadWatchedFile(@intCast(id), &.{}));
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ _ = try p.render(arena.allocator());
+ try std.testing.expectEqualStrings("[3/3]", p.panes[id].?.addon.?.prefix.slice());
+ var fields: [256]u8 = undefined;
+ try std.testing.expect(std.mem.indexOf(u8, pardes.Kind.ctlRead(p.panes[id].?, &fields), "fit:height") != null);
+ }
+};
+
+test {
+ _ = PdfAddon;
+}
diff --git a/test/pdf.zig b/test/pdf.zig
deleted file mode 100644
index 98e8a0ae..00000000
--- a/test/pdf.zig
+++ /dev/null
@@ -1,2246 +0,0 @@
-const std = @import("std");
-const pardes = @import("pardes");
-const panes = pardes.panes;
-const look = pardes.look;
-const pdf_impl = panes.Pdf.pdf;
-const config = pardes.config;
-const builtins = pardes.builtins;
-const layout = pardes.layout;
-
-const dump = pardes.dump;
-
-const Pardes = pardes.Pardes;
-const Builtin = builtins.registry.Builtin();
-const Key = pardes.Key;
-const Event = pardes.Event;
-const Mode = panes.Text.Mode;
-const Surface = pardes.Surface;
-const Placement = pardes.Placement;
-
-/// A placement as these cases read it: its page and revision (its key
-/// among its pane's pages), where it goes and its pixels.
-const Shown = struct {
- page: u32,
- revision: u32,
- fit: pardes.panes.Pdf.NativeFit,
- geometry: pardes.NativeGeometry,
- pixel_offset_y: f32,
- rgba: []const u8,
- iw: usize,
- ih: usize,
-};
-
-/// A frame of `p`, and its placements read so.
-fn renderShown(p: *Pardes, arena: std.mem.Allocator) ![]Shown {
- _ = try p.render(arena);
- return shownAll(p, arena);
-}
-
-/// `p`'s frame's placements, read so.
-fn shownAll(p: *Pardes, arena: std.mem.Allocator) ![]Shown {
- const s = &p.surface;
- const out = try arena.alloc(Shown, s.placements.items.len);
- for (s.placements.items, out) |place, *o| {
- const pane = p.panes[place.pane].?;
- const pv = pane.pdf.?;
- var page: u32 = 0;
- var revision: u32 = 0;
- found: {
- for (pv.rasters[0..pv.rasters_len]) |r| if (r.valid and Placement.keyOf(pane.serial, @intCast(r.page), r.revision) == place.key) {
- page = @intCast(r.page);
- revision = r.revision;
- break :found;
- };
- for (0..pv.page_count) |pg| if (Placement.keyOf(pane.serial, @intCast(pg), 0) == place.key) {
- page = @intCast(pg);
- break :found;
- };
- return error.UnknownPlacement;
- }
- var scroll: f64 = 0;
- for (s.regionList()) |r| if (r.kind == .body and r.owner == place.pane) {
- scroll = r.scroll_px;
- break;
- };
- o.* = .{
- .page = page,
- .revision = revision,
- .fit = switch (pv.fit) {
- .width => .width,
- .height => .height,
- },
- .geometry = .{ .src = place.src, .dst = place.at orelse return error.MissingPdfGeometry },
- .pixel_offset_y = -@as(f32, @floatCast(scroll - @floor(scroll))),
- .rgba = place.raster.bytes(),
- .iw = place.raster.w,
- .ih = place.raster.h,
- };
- }
- return out;
-}
-const PdfFitMode = panes.Pdf.FitMode;
-const PdfTintMode = panes.Pdf.TintMode;
-const pdf_enabled = panes.Pdf.enabled;
-const platform = pardes.platform;
-const themes = pardes.themes;
-const pdf_raster_policy = pardes.pdf_raster_policy;
-const PDF_PAGE_GAP_PX = pardes.PDF_PAGE_GAP_PX;
-const BOX_H = pardes.BOX_H;
-const sel_slot = @backingInt(config.select_button);
-const pane_tail = " " ++ config.pdf_pane_builtins_str;
-
-fn hasPdf(pane: *const pardes.Pane) bool {
- return if (comptime pdf_enabled) pane.pdf != null else false;
-}
-
-const PdfLinkTests = struct {
- const Cell = struct { col: u16, row: u16 };
-
- fn init(tmp: std.testing.TmpDir) !*Pardes {
- const bytes = try pdf_impl.testFixture(std.testing.allocator, "links.pdf");
- defer std.testing.allocator.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "links.pdf", .data = bytes });
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "target.txt", .data = "chosen file\n" });
- var dir_buf: [4096]u8 = undefined;
- const len = try tmp.dir.realPath(std.testing.io, &dir_buf);
- const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/links.pdf", .{dir_buf[0..len]});
- defer std.testing.allocator.free(path);
- const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 100, .rows = 36 });
- p.view().frontend.native_images = true;
- p.panes[0].?.pdf.?.fit = .height;
- return p;
- }
-
- fn cellAt(p: *Pardes, x: f32, y: f32) !Cell {
- const pane = p.panes[0].?;
- const rect = p.view().rects[0];
- var best: ?Cell = null;
- var distance: f32 = std.math.inf(f32);
- for (rect.y..rect.y + rect.h) |row| for (rect.x..rect.x + rect.w) |col| {
- const point = panes.Pdf.panePointAtPage(p, pane, 0, @intCast(col), @intCast(row), false) orelse continue;
- const dx = point.x - x;
- const dy = point.y - y;
- const d = dx * dx + dy * dy;
- if (d < distance) {
- distance = d;
- best = .{ .col = @intCast(col), .row = @intCast(row) };
- }
- };
- return best orelse error.LinkOutsideViewport;
- }
-
- fn textCell(p: *Pardes, text: []const u8) !Cell {
- var found = try p.panes[0].?.pdf.?.document.search(p.gpa, 0, text);
- defer found.deinit(p.gpa);
- if (found.quads.len == 0) return error.MissingLinkFixtureText;
- const q = found.quads[0].quad;
- return cellAt(p, (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4, (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4);
- }
-
- fn click(p: *Pardes, cell: Cell) void {
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = cell.col, .row = cell.row } });
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = cell.col, .row = cell.row } });
- }
-
- fn expectOpened(p: *Pardes, expected: ?[]const u8) !void {
- var count: usize = 0;
- while (p.nextEffect()) |effect| {
- if (effect == .open_link) {
- count += 1;
- try std.testing.expectEqualStrings(expected orelse return error.UnexpectedExternalOpen, effect.open_link.slice());
- }
- }
- try std.testing.expectEqual(@as(usize, if (expected != null) 1 else 0), count);
- }
-
- test "PDF links activate embedded URLs and blank internal annotations" {
- if (!pdf_enabled) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const p = try init(tmp);
- defer p.deinit();
- var frame = std.heap.ArenaAllocator.init(p.gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- while (p.nextEffect()) |_| {}
- click(p, try textCell(p, "label"));
- try expectOpened(p, "https://example.com/only");
- try std.testing.expectEqual(@as(usize, 0), p.panes[0].?.pdf.?.page);
- click(p, try cellAt(p, 0.3, 0.38));
- try expectOpened(p, null);
- try std.testing.expectEqual(@as(usize, 1), p.panes[0].?.pdf.?.page);
- }
-
- test "PDF links offer distinct visible destinations and do not duplicate the same URL" {
- if (!pdf_enabled) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const p = try init(tmp);
- defer p.deinit();
- var frame = std.heap.ArenaAllocator.init(p.gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- while (p.nextEffect()) |_| {}
- const target_cell = try textCell(p, "target.txt");
- try std.testing.expect(panes.Pdf.beginDrag(p, p.panes[0].?, target_cell.col, target_cell.row, true));
- try std.testing.expect(p.panes[0].?.pdf.?.selection != null);
- click(p, target_cell);
- try expectOpened(p, null);
- try std.testing.expect(p.panes[0].?.pdf.?.selection == null);
- const choices = for (p.panes, 0..) |slot, id| {
- if (id == 0) continue;
- if (slot) |pane| if (pane.file) |file| if (file.output != null) break pane;
- } else return error.MissingPdfLinkChoices;
- try std.testing.expect(std.mem.indexOf(u8, choices.file.?.content, "https://example.com/embedded") != null);
- try std.testing.expect(std.mem.indexOf(u8, choices.file.?.content, "target.txt") != null);
- const choices_id = for (p.panes, 0..) |slot, id| {
- if (slot == choices) break id;
- } else return error.MissingPdfLinkChoices;
- pardes.look.lookAt(p, choices_id, "https://example.com/embedded");
- try expectOpened(p, "https://example.com/embedded");
- pardes.look.lookAt(p, choices_id, "target.txt");
- try std.testing.expectEqualStrings("chosen file\n", p.panes[p.view().active].?.file.?.content);
- p.view().active = 0;
- _ = try p.render(frame.allocator());
- click(p, try textCell(p, "https://example.com/same"));
- try expectOpened(p, "https://example.com/same");
- }
-
- fn hover(p: *Pardes, cell: Cell) void {
- p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = cell.col, .row = cell.row } });
- for (0..config.look_preview_delay_frames) |_| p.update(.tick);
- }
-
- test "PDF links hover clears on leave page and reload while right drag chooses Look text" {
- if (!pdf_enabled) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const p = try init(tmp);
- defer p.deinit();
- const pane = p.panes[0].?;
- var frame = std.heap.ArenaAllocator.init(p.gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- const plain_revision = (try shownAll(p, frame.allocator()))[0].revision;
- while (p.nextEffect()) |_| {}
- const blank = try cellAt(p, 0.3, 0.38);
- hover(p, blank);
- const hovered = try p.render(frame.allocator());
- try std.testing.expectEqual(Surface.PointerShape.link, hovered.pointer_shape);
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != plain_revision);
- const highlights = panes.Pdf.highlightInput(p, 0, pane);
- try std.testing.expect(!std.meta.eql(highlights.hover_color, highlights.selection_color));
- try std.testing.expect(pane.pdf.?.selection == null);
- try expectOpened(p, null);
- p.update(.pointer_leave);
- try std.testing.expectEqual(Surface.PointerShape.arrow, (try p.render(frame.allocator())).pointer_shape);
- hover(p, blank);
- panes.Pdf.activatePage(p, pane, 1, true);
- try std.testing.expectEqual(Surface.PointerShape.arrow, (try p.render(frame.allocator())).pointer_shape);
- panes.Pdf.activatePage(p, pane, 0, true);
- _ = try p.render(frame.allocator());
- hover(p, try cellAt(p, 0.3, 0.38));
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(Surface.PointerShape.arrow, (try p.render(frame.allocator())).pointer_shape);
-
- const label = try textCell(p, "label");
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = label.col, .row = label.row } });
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .drag, .col = label.col + 3, .row = label.row } });
- try std.testing.expect(pane.pdf.?.selection != null);
- try std.testing.expect(pane.pdf.?.selection_text.len > 0);
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = label.col + 3, .row = label.row } });
- try expectOpened(p, null);
- try std.testing.expect(pane.pdf.?.selection == null);
- try std.testing.expect(pane.pdf.?.selection_text.len == 0);
- try std.testing.expect(pane.pdf.?.search_query.len > 0);
- }
-};
-
-test {
- _ = PdfLinkTests;
-}
-
-test "PDF mounted bytes own their source after the caller frees it" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- const source = try pardes.filesystem.readFile(gpa, "docs/design.pdf");
- var document = pdf_impl.Document.openBytes(source) catch |err| {
- gpa.free(source);
- return err;
- };
- @memset(source, 0);
- gpa.free(source);
- defer document.deinit();
-
- const again = try pardes.filesystem.readFile(gpa, "docs/design.pdf");
- defer gpa.free(again);
- var original = try pdf_impl.Document.openBytes(again);
- defer original.deinit();
- try std.testing.expectEqual(original.pages, document.pages);
- try std.testing.expectEqual(try original.pageSize(0), try document.pageSize(0));
- const raster = try document.render(gpa, 0, .{}, &.{});
- defer gpa.free(raster.rgba);
- try std.testing.expect(raster.rgba.len > 0);
-}
-
-test "explicit OS PDF opens and reloads keep their namespace path" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const original = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(original);
- const replacement = try pdf_impl.testFixture(gpa, "offset-rotated.pdf");
- defer gpa.free(replacement);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = original });
- var directory_buffer: [4096]u8 = undefined;
- const directory_len = try tmp.dir.realPath(std.testing.io, &directory_buffer);
- const path = try std.fmt.allocPrint(gpa, "/n/os{s}/live.pdf", .{directory_buffer[0..directory_len]});
- defer gpa.free(path);
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 24 });
- defer p.deinit();
- const pane = p.panes[0].?;
- try std.testing.expectEqualStrings(path, pane.pdf.?.path);
- try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count);
- var watched = false;
- while (p.nextEffect()) |effect| {
- if (effect == .watch and effect.watch.pane == 0 and effect.watch.on) watched = true;
- }
- try std.testing.expect(watched);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = replacement });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqualStrings(path, pane.pdf.?.path);
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page_count);
-}
-
-test "PDF feature gates keep argv and builtin behavior coherent" {
- const maybe_fit = std.meta.stringToEnum(Builtin, "PdfFit");
- const maybe_tint = std.meta.stringToEnum(Builtin, "PdfTint");
- const maybe_sections = std.meta.stringToEnum(Builtin, "PdfSections");
- try std.testing.expectEqual(pdf_enabled, maybe_fit != null);
- try std.testing.expectEqual(pdf_enabled, maybe_tint != null);
- try std.testing.expectEqual(pdf_enabled, maybe_sections != null);
- if (pdf_enabled) {
- try std.testing.expectEqualStrings("tz", config.leader_path.get(maybe_fit.?).?);
- try std.testing.expectEqualStrings("ti", config.leader_path.get(maybe_tint.?).?);
- try std.testing.expectEqualStrings("ts", config.leader_path.get(maybe_sections.?).?);
- } else {
- const p = try Pardes.init(std.testing.allocator, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- try std.testing.expect(pane.file != null);
- try std.testing.expect(pane.image == null);
- try std.testing.expect(!hasPdf(pane));
- }
-}
-
-test "PdfSections Look follows the exact owning PDF, not an equal path" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const fixture = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
-
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- const first = p.panes[0].?;
- // Bare normal-mode `f` on a PDF dispatches the PdfSections builtin.
- p.update(.{ .key = .{ .cp = 'f', .text = "f" } });
- const first_output_id = first.search_pane orelse return error.MissingPdfSectionsOutput;
- const first_output = p.panes[first_output_id].?;
- try std.testing.expect(panes.Pdf.isSectionsOutput(first_output));
- try std.testing.expect(first_output.file.?.content.len > 0);
-
- // A clean result is re-armed in place without rebuilding it.
- const first_revision = first_output.file.?.revision;
- panes.Pdf.openSections(p, 0);
- try std.testing.expectEqual(first_output_id, first.search_pane.?);
- try std.testing.expectEqual(first_revision, first_output.file.?.revision);
-
- const duplicate_id = p.freeSlot() orelse return error.NoDuplicatePdfSlot;
- const duplicate = try panes.Pdf.openPane(p, duplicate_id, path, 0, .last);
- pardes.exec.placeNew(p, 0, 0, duplicate_id, .doc);
- layout.compute(p);
- panes.Pdf.openSections(p, duplicate_id);
- const duplicate_output_id = duplicate.search_pane orelse return error.MissingDuplicatePdfSections;
-
- const first_row = std.mem.sliceTo(first_output.file.?.content, '\n');
- const target = first_row[0 .. std.mem.indexOfScalar(u8, first_row, ' ') orelse first_row.len];
- pardes.look.lookAt(p, first_output_id, target);
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- pardes.look.lookAt(p, duplicate_output_id, target);
- try std.testing.expectEqual(duplicate_id, p.view().active);
-
- // Once the original document is gone, its output cannot reinterpret an
- // old ordinal against the still-open equal-path duplicate.
- try std.testing.expect(pardes.test_api.runBuiltin(p, "Del", 0, "", null));
- p.view().active = first_output_id;
- pardes.look.lookAt(p, first_output_id, target);
- try std.testing.expectEqual(first_output_id, p.view().active);
-}
-
-test "SDL PDF raster policy is materially denser than Kitty" {
- try std.testing.expect(
- pardes.sdl_pdf_raster_policy.dpi >= pardes.kitty_pdf_raster_policy.dpi * 2,
- );
- try std.testing.expect(
- pardes.sdl_pdf_raster_policy.max_dimension >
- pardes.kitty_pdf_raster_policy.max_dimension * 3,
- );
- try std.testing.expect(!pardes.kitty_pdf_raster_policy.match_viewport);
- try std.testing.expect(pardes.sdl_pdf_raster_policy.match_viewport);
-}
-
-test "watched PDF reload replaces MuPDF state and preserves the reading view" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const original = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(original);
- const replacement = try pdf_impl.testFixture(gpa, "offset-rotated.pdf");
- defer gpa.free(replacement);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = original });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(
- &path_buf,
- ".zig-cache/tmp/{s}/live.pdf",
- .{tmp.sub_path},
- );
-
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- var watched = false;
- while (p.nextEffect()) |effect| switch (effect) {
- .watch => |watch| if (watch.pane == 0 and watch.on) {
- watched = true;
- },
- else => {},
- };
- try std.testing.expect(watched);
-
- const pane = p.panes[0].?;
- const state = pane.pdf.?;
- try std.testing.expectEqual(@as(usize, 3), state.page_count);
- panes.Pdf.openSections(p, 0);
- const sections_id = pane.search_pane orelse return error.MissingPdfSectionsOutput;
- const sections = p.panes[sections_id].?;
- try std.testing.expect(sections.file.?.content.len > 0);
-
- p.view().frontend.native_images = true;
- state.fit = .height;
- state.tint = .full;
- state.pan_x = 1234;
- state.pan_y = 4321;
- try state.setSearchQuery(p.pdf_gpa, "needle");
- panes.Pdf.activatePage(p, pane, 2, true);
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- state.text_scroll = 7;
- state.search_hit = 4;
- state.search_reveal_pending = false;
- const reveal_viewport_w = state.reveal_viewport_w;
- const reveal_viewport_h = state.reveal_viewport_h;
- const reveal_fit = state.reveal_fit;
- const reveal_viewport_valid = state.reveal_viewport_valid;
- const old_revision = panes.Pdf.rasterForPage(state, 2).?.revision;
- const old_revision_counter = state.next_raster_revision;
- const anchor_fraction: f64 = 0.375;
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[2])) +
- anchor_fraction * @as(f64, @floatFromInt(state.page_heights[2]));
- state.scroll_to_page_pending = false;
- state.layout_anchor_pending = false;
- pane.body.cur_row = 9;
- pane.body.cur_col = 8;
-
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = replacement });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
-
- try std.testing.expectEqual(@as(usize, 1), state.page_count);
- try std.testing.expectEqual(@as(usize, 0), state.page);
- try std.testing.expectEqual(PdfFitMode.height, state.fit);
- try std.testing.expectEqual(PdfTintMode.full, state.tint);
- try std.testing.expectEqual(@as(u16, 1234), state.pan_x);
- try std.testing.expectEqual(@as(u16, 4321), state.pan_y);
- try std.testing.expectEqual(@as(usize, 7), state.text_scroll);
- try std.testing.expect(state.text_scroll_clamp_pending);
- try std.testing.expectEqualStrings("needle", state.search_query);
- try std.testing.expectEqual(@as(usize, 4), state.search_hit);
- try std.testing.expectEqual(reveal_viewport_w, state.reveal_viewport_w);
- try std.testing.expectEqual(reveal_viewport_h, state.reveal_viewport_h);
- try std.testing.expectEqual(reveal_fit, state.reveal_fit);
- try std.testing.expectEqual(reveal_viewport_valid, state.reveal_viewport_valid);
- try std.testing.expectEqual(old_revision_counter, state.next_raster_revision);
- try std.testing.expectEqual(@as(usize, 0), state.rasters_len);
- try std.testing.expect(state.layout_anchor_pending);
- try std.testing.expectEqual(@as(usize, 2), state.layout_anchor_page);
- try std.testing.expectApproxEqAbs(anchor_fraction, state.layout_anchor_fraction, 0.0001);
- try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
- try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
- _ = state.ensureText(p.pdf_gpa);
- const text_lines = std.mem.count(u8, state.text, "\n") + 1;
- try std.testing.expect(state.text_scroll < text_lines);
- try std.testing.expect(!state.text_scroll_clamp_pending);
-
- // A clean generated outline is derived data: it refreshes in place and
- // remains the remembered output. This replacement deliberately has none.
- try std.testing.expectEqual(@as(usize, 0), sections.file.?.content.len);
- try std.testing.expectEqual(sections_id, state.sections_output.?.pane);
- try std.testing.expectEqual(sections.file.?.revision, state.sections_output.?.revision);
-
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const fresh_raster = panes.Pdf.rasterForPage(state, 0).?;
- try std.testing.expect(fresh_raster.revision != old_revision);
- try std.testing.expect(fresh_raster.revision > old_revision_counter);
- const expected_scroll = anchor_fraction *
- @as(f64, @floatFromInt(state.page_heights[0]));
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- try std.testing.expectApproxEqAbs(@min(expected_scroll, max_scroll), state.document_scroll_y, 0.001);
-
- // Reopen is transactional: malformed replacement bytes leave the last
- // good MuPDF handle and every durable setting untouched.
- const good_handle = state.document.handle;
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = "not a PDF" });
- try std.testing.expect(!p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(good_handle, state.document.handle);
- try std.testing.expectEqual(@as(usize, 1), state.page_count);
- try std.testing.expectEqualStrings("needle", state.search_query);
- try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "PDF reload") != null);
-
- // A user edit breaks the generated-revision token. A later valid reload
- // updates the document but leaves those user-owned output bytes alone.
- panes.File.setContent(p, &sections.file.?, try gpa.dupe(u8, "edited sections\n"));
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = original });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(@as(usize, 3), state.page_count);
- try std.testing.expectEqualStrings("edited sections\n", sections.file.?.content);
-
- // The watch follows the PDF payload's lifetime just like a text file's;
- // emit the stop while the slot still identifies the disappearing pane.
- try pardes.panes.deinitPane(p, pane);
- p.panes[0] = null;
- var unwatched = false;
- while (p.nextEffect()) |effect| switch (effect) {
- .watch => |watch| if (watch.pane == 0 and !watch.on) {
- unwatched = true;
- },
- else => {},
- };
- try std.testing.expect(unwatched);
-}
-
-test "PDF reload does not re-center an already revealed matching search" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- const fixture = try pardes.filesystem.readFile(gpa, "docs/design.pdf");
- defer gpa.free(fixture);
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "search.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/search.pdf", .{tmp.sub_path});
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const state = pane.pdf.?;
- try state.setSearchQuery(p.pdf_gpa, "Pardes");
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- try std.testing.expect(state.search_results != null);
- try std.testing.expect(state.search_results.?.hit_count > 0);
- try std.testing.expect(state.reveal_viewport_valid);
-
- // Reading moved on after the original reveal. A reload retains the query
- // and rebuilds its quads, but it must not mistake that for a new request to
- // jump back to the hit.
- const anchor_page = state.page;
- const anchor_fraction: f64 = 0.82;
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[anchor_page])) +
- anchor_fraction * @as(f64, @floatFromInt(state.page_heights[anchor_page]));
- state.scroll_to_page_pending = false;
- state.layout_anchor_pending = false;
- state.search_reveal_pending = false;
- const reveal_w = state.reveal_viewport_w;
- const reveal_h = state.reveal_viewport_h;
- const reveal_fit = state.reveal_fit;
-
- // Same semantic document on a fresh generation keeps the expected anchor
- // easy to state while still rebuilding every MuPDF-owned search object.
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "search.pdf", .data = fixture });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(reveal_w, state.reveal_viewport_w);
- try std.testing.expectEqual(reveal_h, state.reveal_viewport_h);
- try std.testing.expectEqual(reveal_fit, state.reveal_fit);
- try std.testing.expect(!state.search_reveal_pending);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
-
- const page = @min(anchor_page, state.page_count - 1);
- const anchored = @as(f64, @floatFromInt(state.page_starts[page])) +
- anchor_fraction * @as(f64, @floatFromInt(state.page_heights[page]));
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- try std.testing.expectApproxEqAbs(@min(anchored, max_scroll), state.document_scroll_y, 0.001);
-}
-
-test "MuPDF pane renders, navigates, searches, and round-trips its page" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- try std.testing.expect(hasPdf(pane));
- try std.testing.expect(pane.pdf.?.page_count > 1);
- try std.testing.expectEqual(PdfFitMode.width, pane.pdf.?.fit);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y);
- try std.testing.expectEqual(@as(u16, 8), p.view().cell_pixels.w);
- try std.testing.expectEqual(@as(u16, 16), p.view().cell_pixels.h);
- const initial_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane);
- const expected_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [1/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page_count, pane_tail });
- try std.testing.expectEqualStrings(expected_tag, initial_tag);
- try std.testing.expect(std.mem.endsWith(u8, initial_tag, pane_tail));
-
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- const first = try p.render(frame.allocator());
- 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(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,
- pane.pdf.?.fit,
- );
- try std.testing.expectEqual(pdf_raster_policy.dpi, request.dpi);
- try std.testing.expectEqual(pdf_raster_policy.max_dimension, request.max_dimension);
- try std.testing.expectEqual(
- request,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.request,
- );
- try std.testing.expect(@max(first_place.iw, first_place.ih) <= request.max_dimension);
- if (pdf_raster_policy.match_viewport) {
- const viewport = panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport;
- try std.testing.expectEqual(viewport.pixel_w, request.minimum_width);
- try std.testing.expectEqual(viewport.pixel_h, request.minimum_height);
- try std.testing.expect(first_place.iw >= viewport.pixel_w or
- @max(first_place.iw, first_place.ih) == request.max_dimension);
- try std.testing.expect(first_place.ih >= viewport.pixel_h or
- @max(first_place.iw, first_place.ih) == request.max_dimension);
- } else {
- try std.testing.expectEqual(@as(u32, 0), request.minimum_width);
- try std.testing.expectEqual(@as(u32, 0), request.minimum_height);
- }
-
- // SDL's raw dy path retains fractions in the placement itself; it does
- // not leave native pixels fixed while only the underlying cells slide.
- p.update(.{ .pdf_scroll = .{ .pane = 0, .delta_pixels = 0.25, .glide = false } });
- try std.testing.expectEqual(@as(f64, 0.25), pane.pdf.?.document_scroll_y);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(first_place.revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expectEqual(@as(f32, -0.25), (try shownAll(p, frame.allocator()))[0].pixel_offset_y);
- pane.pdf.?.document_scroll_y = 0;
-
- // The default reading view moves one exact display-cell distance without
- // replacing page pixels. Document placement, not texture identity, moves.
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.page);
- try std.testing.expectEqual(@as(f64, p.view().cell_pixels.h), pane.pdf.?.document_scroll_y);
- try std.testing.expectEqual(
- first_place.revision,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(first_place.revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].geometry.src.y > first_place.geometry.src.y);
-
- const row_scroll = pane.pdf.?.document_scroll_y;
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '3' } });
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(f64, p.view().cell_pixels.h * 3), pane.pdf.?.document_scroll_y);
-
- // Counts survive a shared multi-key prefix. An invalid continuation is
- // consumed and clears both prefix and count before the following action.
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(f64, p.view().cell_pixels.h * 2), pane.pdf.?.document_scroll_y);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '4' } });
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = '?' } });
- try std.testing.expectEqual(null, pane.body.normal.prefix);
- try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count);
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y);
-
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
- const half_scroll = pane.pdf.?.document_scroll_y;
- try std.testing.expect(half_scroll > row_scroll);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
- const counted_half = pane.pdf.?.document_scroll_y;
- try std.testing.expectEqual(half_scroll * 2, counted_half);
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'u', .ctrl = true } });
- try std.testing.expectEqual(@as(f64, 0), pane.pdf.?.document_scroll_y);
- pane.pdf.?.document_scroll_y = @as(f64, p.view().cell_pixels.h) * 4;
- p.update(.{ .key = .{ .cp = '3' } });
- p.update(.{ .key = .{ .cp = 'k' } });
- try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
- try std.testing.expect(pane.pdf.?.document_scroll_y >= half_scroll);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
- const key_viewport = panes.Pdf.paneViewport(p, pane).?;
- const max_key_scroll = @as(f64, @floatFromInt(pane.pdf.?.document_height -| key_viewport.pixel_h));
- const counted_full = @min(@as(f64, @floatFromInt(key_viewport.pixel_h * 2)), max_key_scroll);
- try std.testing.expectEqual(counted_full, pane.pdf.?.document_scroll_y);
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
- try std.testing.expectEqual(@max(@as(f64, 0), counted_full - @as(f64, @floatFromInt(key_viewport.pixel_h * 2))), pane.pdf.?.document_scroll_y);
- try std.testing.expectEqual(
- first_place.revision,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
-
- // At a page boundary both page rasters coexist, the gap remains uncovered,
- // and a row step crosses it without snapping either page to an edge.
- //
- // This lands by ASSIGNMENT, which is a jump and not a fling — and the
- // travel counter has to say so: the keys above scrolled two screenfuls
- // without any frame in between to spend that distance, which no shell does
- // (every wheel batch is followed by a draw). Left unspent it would make the
- // frame below the first frame of a fling and hand it bands.
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- pane.pdf.?.scroll_travel = 0;
- pane.pdf.?.document_scroll_y = @floatFromInt(
- pane.pdf.?.page_starts[1] -| viewport.pixel_h / 2,
- );
- _ = frame.reset(.retain_capacity);
- const boundary = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 2), boundary.placements.items.len);
- try std.testing.expectEqual(@as(u32, 0), (try shownAll(p, frame.allocator()))[0].page);
- try std.testing.expectEqual(@as(u32, 1), (try shownAll(p, frame.allocator()))[1].page);
- const first_bottom = @as(f32, @floatFromInt(
- (try shownAll(p, frame.allocator()))[0].geometry.dst.y +
- (try shownAll(p, frame.allocator()))[0].geometry.dst.h,
- )) + (try shownAll(p, frame.allocator()))[0].pixel_offset_y;
- const second_top = @as(f32, @floatFromInt(
- (try shownAll(p, frame.allocator()))[1].geometry.dst.y,
- )) + (try shownAll(p, frame.allocator()))[1].pixel_offset_y;
- const visible_gap = second_top - first_bottom;
- try std.testing.expect(visible_gap >= @as(f32, PDF_PAGE_GAP_PX));
- try std.testing.expect(visible_gap <= @as(f32, PDF_PAGE_GAP_PX + 1));
- const before_boundary_scroll = pane.pdf.?.document_scroll_y;
- const page0_revision = (try shownAll(p, frame.allocator()))[0].revision;
- const page1_revision = (try shownAll(p, frame.allocator()))[1].revision;
-
- // A scroll can activate the already-cached neighbor before the shell's
- // next draw. Every consumer resolves the active page's resident raster,
- // so a queued click cannot accidentally use page zero's dimensions.
- pane.pdf.?.document_scroll_y = @as(f64, @floatFromInt(pane.pdf.?.page_starts[1])) - 0.5;
- try std.testing.expectEqual(
- page0_revision,
- panes.Pdf.rasterForPage(pane.pdf.?, 0).?.revision,
- );
- try std.testing.expect(panes.Pdf.scrollPane(p, pane, 1, false));
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page);
- try std.testing.expectEqual(
- page1_revision,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
- panes.Pdf.activatePage(p, pane, 0, false);
- pane.pdf.?.document_scroll_y = before_boundary_scroll;
-
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(before_boundary_scroll + p.view().cell_pixels.h, pane.pdf.?.document_scroll_y);
- _ = frame.reset(.retain_capacity);
- const second = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 2), second.placements.items.len);
- try std.testing.expectEqual(page0_revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expectEqual(page1_revision, (try shownAll(p, frame.allocator()))[1].revision);
- p.update(.{ .key = .{ .cp = 'k' } });
- try std.testing.expectEqual(before_boundary_scroll, pane.pdf.?.document_scroll_y);
-
- // Once page zero is wholly outside the viewport, both its owned RGBA and
- // backend placement disappear; returning later renders a new raster. What
- // does NOT go back is the memory: the departing page's bytes are parked in
- // the relay and the arriving page of the same size takes them, so a fling
- // never asks the allocator (or the kernel's fault handler) for megabytes it
- // just gave up.
- panes.Pdf.activatePage(p, pane, 1, true);
- _ = frame.reset(.retain_capacity);
- const away = try p.render(frame.allocator());
- try std.testing.expect(away.placements.items.len > 0);
- for (try shownAll(p, frame.allocator())) |place|
- try std.testing.expect(place.page != 0);
- try std.testing.expect(panes.Pdf.rasterForPage(pane.pdf.?, 0) == null);
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.spare_len);
- const retired = pane.pdf.?.spare[0];
- panes.Pdf.activatePage(p, pane, 0, true);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(u32, 0), (try shownAll(p, frame.allocator()))[0].page);
- try std.testing.expectEqual(retired.ptr, (try shownAll(p, frame.allocator()))[0].rgba.ptr);
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != page0_revision);
-
- // PdfFit exists as a real builtin in this build. It resets placement but
- // preserves the current page pixels; fit-height j/k remains continuous in
- // the same document-pixel coordinate space.
- const fit_builtin = std.meta.stringToEnum(Builtin, "PdfFit") orelse
- return error.MissingPdfFitBuiltin;
- const revision_before_toggle = panes.Pdf.rasterForPage(
- pane.pdf.?,
- pane.pdf.?.page,
- ).?.revision;
- try std.testing.expect(pardes.test_api.runBuiltin(
- p,
- @tagName(fit_builtin),
- 0,
- "",
- null,
- ));
- try std.testing.expectEqual(PdfFitMode.height, pane.pdf.?.fit);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y);
- try std.testing.expectEqual(
- revision_before_toggle,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
- const height_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane);
- const expected_height_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [{d}/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page + 1, pane.pdf.?.page_count, pane_tail });
- try std.testing.expectEqualStrings(expected_height_tag, height_tag);
- for (p.panes) |slot| {
- const other = slot orelse continue;
- if (hasPdf(other)) continue;
- panes.Pdf.toggleFit(other); // pane-scoped and deliberately inert here
- try std.testing.expectEqual(PdfFitMode.height, pane.pdf.?.fit);
- break;
- }
-
- // A fit-height landscape page exposes horizontal overflow to a horizontal
- // wheel without rerasterizing. Use synthetic dimensions only for the
- // geometry check; no frame is drawn while they differ from the buffer.
- const active_raster = panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?;
- const saved_iw = active_raster.iw;
- const saved_ih = active_raster.ih;
- active_raster.iw = 2000;
- active_raster.ih = 500;
- panes.Pdf.horizontalWheel(p, pane, 1);
- try std.testing.expect(pane.pdf.?.pan_x > 0);
- try std.testing.expectEqual(revision_before_toggle, active_raster.revision);
- pane.pdf.?.pan_x = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'l' } });
- try std.testing.expect(pane.pdf.?.pan_x > 0);
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'l' } });
- try std.testing.expectEqual(std.math.maxInt(u16), pane.pdf.?.pan_x);
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'h' } });
- try std.testing.expect(pane.pdf.?.pan_x < std.math.maxInt(u16));
- p.update(.{ .key = .{ .cp = '0' } });
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'l' } });
- try std.testing.expectEqual(std.math.maxInt(u16), pane.pdf.?.pan_x);
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'h' } });
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- active_raster.iw = saved_iw;
- active_raster.ih = saved_ih;
- pane.pdf.?.pan_x = 0;
-
- const before_height_scroll = pane.pdf.?.document_scroll_y;
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expect(pane.pdf.?.document_scroll_y > before_height_scroll);
-
- const revision_before_search = active_raster.revision;
- _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true);
- try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query);
- try std.testing.expectEqual(revision_before_search, active_raster.revision);
- const results_id = pane.search_pane orelse return error.MissingPdfSearchResults;
- const results = p.panes[results_id].?.file.?.content;
- try std.testing.expect(std.mem.indexOf(u8, results, "design.pdf:") != null);
- // n SELECTS the first result row and opens nothing: the walk's only list
- // here is the unlooked +Search buffer, so focus lands THERE. Enter is what
- // jumps, and the document query survives both.
- p.update(.{ .key = .{ .cp = 'n' } });
- try std.testing.expectEqual(results_id, p.view().active);
- const results_pane = p.panes[results_id].?;
- try std.testing.expect(results_pane.body.vsel.active and results_pane.body.vsel.explicit);
- try std.testing.expectEqual(@as(i32, 0), results_pane.body.cur_row);
- try std.testing.expectEqual(@as(i32, 0), results_pane.body.cur_col);
- p.update(.{ .key = .{ .cp = Key.enter } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query);
-
- // Search state is owned and untruncated, and changing pages invalidates
- // only page-local state while retaining the document query.
- const long_query = "a query deliberately longer than any tag display budget: " ++
- "012345678901234567890123456789012345678901234567890123456789" ++
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
- try pane.pdf.?.setSearchQuery(p.pdf_gpa, long_query);
- try std.testing.expectEqualStrings(long_query, pane.pdf.?.search_query);
- const next_page = if (pane.pdf.?.page == 0) @as(usize, 1) else 0;
- panes.Pdf.activatePage(p, pane, next_page, true);
- try std.testing.expectEqualStrings(long_query, pane.pdf.?.search_query);
-
- // PDF dumps keep the image-compatible schema: page/path, the exact
- // editable tail, and the pane's fit and tint (pdf_fit, pdf_tint).
- panes.Pdf.toggleTint(pane);
- try std.testing.expectEqual(PdfTintMode.full, pane.pdf.?.tint);
- pane.pdf.?.fit = .height;
- const custom_tail = " Keep Del";
- if (pane.tag.own) |own| p.gpa.free(own);
- pane.tag.own = try p.gpa.dupe(u8, custom_tail);
- try pardes.dump.dumpState(p);
- const restored = try pardes.dump.initFromDump(gpa, .{}, p.dump_out.?);
- defer restored.deinit();
- try std.testing.expect(hasPdf(restored.panes[0].?));
- try std.testing.expectEqual(pane.pdf.?.page, restored.panes[0].?.pdf.?.page);
- try std.testing.expectEqual(PdfFitMode.height, restored.panes[0].?.pdf.?.fit);
- try std.testing.expectEqual(PdfTintMode.full, restored.panes[0].?.pdf.?.tint);
- const restored_pane = restored.panes[0].?;
- try std.testing.expect(restored_pane.tag.own != null);
- try std.testing.expectEqualStrings(
- custom_tail,
- restored_pane.tag.own.?,
- );
-}
-
-test "a fling's banded pages show the reader exactly what whole pages would" {
- if (!pdf_enabled) return;
-
- // The contract fast scrolling is allowed to change: HOW pixels are carried
- // (a strip of a page instead of the page) but never WHICH pixels arrive. So
- // the same frame is drawn twice — once at fling speed, once at reading
- // speed — and every pixel inside every source rectangle must match, along
- // with where on screen it goes.
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{ .file = "docs/design.pdf", .cols = 120, .rows = 40 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
-
- const viewport = panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport;
- // Land mid-page-boundary so the frame carries TWO pages, each showing a
- // fraction of itself — the shape a fling actually produces.
- const landing = @as(f64, @floatFromInt(pv.page_starts[1] -| viewport.pixel_h / 3));
- const Shot = struct {
- page: u32,
- dst: pardes.RectPx,
- pixels: []u8,
- };
- var shots: [8]Shot = undefined;
- var shots_len: usize = 0;
- defer for (shots[0..shots_len]) |shot| gpa.free(shot.pixels);
-
- // A fling: one frame's worth of wheel travel carrying the viewport more
- // than a screenful, delivered through the real scroll path so the distance
- // is counted the way a wheel batch counts it.
- pv.document_scroll_y = 0;
- pv.scroll_travel = 0;
- try std.testing.expect(panes.Pdf.scrollPane(p, pane, landing, false));
- _ = frame.reset(.retain_capacity);
- const flung = try p.render(frame.allocator());
- try std.testing.expect(flung.placements.items.len >= 2);
- var banded = false;
- for (try shownAll(p, frame.allocator())) |place| {
- const geometry = place.geometry;
- const raster = panes.Pdf.rasterForPage(pv, place.page) orelse
- return error.MissingPdfRaster;
- if (raster.band_h < raster.ih) banded = true;
- try std.testing.expectEqual(place.iw * raster.band_h * 4, place.rgba.len);
- shots[shots_len] = .{
- .page = place.page,
- .dst = geometry.dst,
- .pixels = try copySourceRect(gpa, place, geometry.src),
- };
- shots_len += 1;
- }
- // ...and it really did band, or the comparison below is two identical
- // whole-page renders agreeing with each other.
- try std.testing.expect(banded);
- // ...at reading speed: no travel at all since the frame above, so every
- // page is rasterized whole again, and that is the picture the banded frame
- // has to have matched.
- _ = frame.reset(.retain_capacity);
- const rested = try p.render(frame.allocator());
- try std.testing.expectEqual(shots_len, rested.placements.items.len);
- for (try shownAll(p, frame.allocator()), shots[0..shots_len]) |place, shot| {
- const geometry = place.geometry;
- const raster = panes.Pdf.rasterForPage(pv, place.page) orelse
- return error.MissingPdfRaster;
- try std.testing.expectEqual(raster.ih, raster.band_h); // promoted at rest
- try std.testing.expectEqual(shot.page, place.page);
- try std.testing.expectEqual(shot.dst.x, geometry.dst.x);
- try std.testing.expectEqual(shot.dst.y, geometry.dst.y);
- try std.testing.expectEqual(shot.dst.w, geometry.dst.w);
- try std.testing.expectEqual(shot.dst.h, geometry.dst.h);
- const whole = try copySourceRect(gpa, place, geometry.src);
- defer gpa.free(whole);
- try std.testing.expectEqualSlices(u8, shot.pixels, whole);
- }
-}
-
-/// MuPDF clips the edges of a path to the pixmap, and an edge that crosses a
-/// band's clip is stepped from a different start: along its whole length in
-/// the band, its antialiased pixels can be a level or two off the whole
-/// page's. Never more.
-const band_tolerance: u8 = 4;
-
-fn expectNearRows(expected: []const u8, got: []const u8) !void {
- try std.testing.expectEqual(expected.len, got.len);
- var worst: u8 = 0;
- for (expected, got) |a, b| worst = @max(worst, if (a > b) a - b else b - a);
- if (worst > band_tolerance) {
- std.debug.print("band rows are {d} levels off the whole page's\n", .{worst});
- return error.TestExpectedEqual;
- }
-}
-
-test "a tall page is drawn at the display's resolution, in bands that are the whole page's rows" {
- if (!pdf_enabled) return;
-
- // The page is fifteen A4 heights tall. Squeezed whole into the raster
- // budget it was a third as wide as the pane and blown up, blurred; it is
- // drawn instead at the pane's own resolution, a band around the screen at
- // a time, and every band row must be the row a whole-page render makes
- // (to `band_tolerance`), and the same row however it was scrolled to.
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try pdf_impl.testFixture(gpa, "tall.pdf");
- defer gpa.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "tall.pdf", .data = bytes });
- var dir_buf: [4096]u8 = undefined;
- const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf);
- const path = try std.fmt.allocPrint(gpa, "{s}/tall.pdf", .{dir_buf[0..dir_len]});
- defer gpa.free(path);
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 120, .rows = 40 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
-
- const viewport = panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport;
- const request = panes.Pdf.renderRequest(viewport, pdf_raster_policy, pv.fit);
- const shape = try pv.document.measureRenderAt(0, request);
- if (pdf_raster_policy.match_viewport) {
- // The rendered scale IS the screen's: one raster pixel per pixel of
- // the pane's width, so nothing is scaled up.
- try std.testing.expectEqual(@as(usize, viewport.pixel_w), shape.width);
- } else {
- // Kitty's policy is a dpi, kept low for the wire; the tall page gets
- // it as every other page does, not a quarter of it.
- try std.testing.expectEqual(
- @as(usize, @intFromFloat(pdf_impl.tall_test_page.width)) * pdf_raster_policy.dpi / 72,
- shape.width,
- );
- }
- try std.testing.expect(panes.Pdf.isBanded(shape));
-
- // The reference: the whole page in one render, before highlights and
- // tint, and tinted as the pane tints.
- const plain = try gpa.alloc(u8, shape.len);
- defer gpa.free(plain);
- try pv.document.renderIntoAtWithPaper(0, request, shape, shape.wholePage(), &.{}, plain, false);
- const whole = try gpa.dupe(u8, plain);
- defer gpa.free(whole);
- try pdf_impl.tintRgba(whole, pv.tint, panes.Pdf.tintColors(p));
-
- const max_scroll = @as(f64, @floatFromInt(pv.document_height - viewport.pixel_h));
- var middle: []u8 = &.{};
- defer gpa.free(middle);
- var middle_y: usize = 0;
- for ([_]f64{ 0, @round(max_scroll / 2), max_scroll }, 0..) |at, step| {
- _ = panes.Pdf.scrollPane(p, pane, at - pv.document_scroll_y, false);
- pv.scroll_travel = 0; // read, not flung
- _ = frame.reset(.retain_capacity);
- const surface = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 1), surface.placements.items.len);
- const place = (try shownAll(p, frame.allocator()))[0];
- const geometry = place.geometry;
- const raster = panes.Pdf.rasterForPage(pv, 0) orelse return error.MissingPdfRaster;
- // Bounded: a band, never the page, and within one buffer's budget.
- try std.testing.expectEqual(shape.width, place.iw);
- try std.testing.expect(raster.band_h < raster.ih);
- try std.testing.expect(place.rgba.len <= pdf_impl.max_owned_raster_bytes);
- // Prefetched: a screenful beyond what is shown, both ways, where the
- // page goes on.
- const seen_top = raster.band_y + geometry.src.y;
- const seen_end = seen_top + geometry.src.h;
- try std.testing.expect(raster.band_y <= seen_top -| geometry.src.h);
- try std.testing.expect(raster.band_y + raster.band_h >= @min(raster.ih, seen_end + geometry.src.h));
- // ...and every row of the band is the whole page's row.
- const stride = shape.stride;
- try expectNearRows(whole[raster.band_y * stride ..][0 .. raster.band_h * stride], place.rgba);
- if (step == 1) {
- middle = try gpa.dupe(u8, place.rgba);
- middle_y = raster.band_y;
- }
- }
-
- // Straight back to the middle from the foot: the rows rendered afresh
- // are the very rows rendered on the way down, so no seam moves with the
- // path a reader took.
- _ = panes.Pdf.scrollPane(p, pane, @round(max_scroll / 2) - pv.document_scroll_y, false);
- pv.scroll_travel = 0;
- _ = frame.reset(.retain_capacity);
- const again = (try renderShown(p, frame.allocator()))[0];
- const again_y = panes.Pdf.rasterForPage(pv, 0).?.band_y;
- const stride = shape.stride;
- const common_top = @max(middle_y, again_y);
- const common_end = @min(middle_y + middle.len / stride, again_y + again.rgba.len / stride);
- try std.testing.expect(common_end > common_top);
- try std.testing.expectEqualSlices(
- u8,
- middle[(common_top - middle_y) * stride .. (common_end - middle_y) * stride],
- again.rgba[(common_top - again_y) * stride .. (common_end - again_y) * stride],
- );
- _ = panes.Pdf.scrollPane(p, pane, max_scroll - pv.document_scroll_y, false);
- pv.scroll_travel = 0;
- _ = frame.reset(.retain_capacity);
- const foot = try gpa.dupe(u8, (try renderShown(p, frame.allocator()))[0].rgba);
- defer gpa.free(foot);
-
- // At the foot of the page, a search hit: its highlight lands on exactly
- // the rows and pixels it would on the whole page, and a pointer over the
- // word finds the word.
- try pv.setSearchQuery(gpa, "bottommost");
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const place = (try shownAll(p, frame.allocator()))[0];
- const raster = panes.Pdf.rasterForPage(pv, 0) orelse return error.MissingPdfRaster;
- const highlights = try panes.Pdf.buildHighlights(pv, frame.allocator(), panes.Pdf.highlightInput(p, 0, pane));
- const marks = highlights.forPage(0);
- try std.testing.expect(marks.len > 0);
- const rows = try pv.document.highlightRows(0, request, marks);
- try std.testing.expect(rows.start >= raster.band_y and rows.end <= raster.band_y + raster.band_h);
- // Exactly the highlight's rows changed, and nothing else...
- try std.testing.expectEqual(foot.len, place.rgba.len);
- const from = (rows.start - raster.band_y) * stride;
- const to = (rows.end - raster.band_y) * stride;
- try std.testing.expectEqualSlices(u8, foot[0..from], place.rgba[0..from]);
- try std.testing.expectEqualSlices(u8, foot[to..], place.rgba[to..]);
- try std.testing.expect(!std.mem.eql(u8, foot[from..to], place.rgba[from..to]));
- // ...to what the whole page painted with them is.
- const expected = try gpa.dupe(u8, plain[rows.start * stride .. rows.end * stride]);
- defer gpa.free(expected);
- try pv.document.paintHighlightsAt(0, request, shape, shape.band(rows.start, rows.end - rows.start), marks, expected);
- try pdf_impl.tintRgba(expected, pv.tint, panes.Pdf.tintColors(p));
- try expectNearRows(expected, place.rgba[from..to]);
-
- const quad = pv.search_results.?.quads[0].quad;
- const left = @min(quad.ul.x, quad.ll.x);
- const right = @max(quad.ur.x, quad.lr.x);
- const top = @min(quad.ul.y, quad.ur.y);
- const bottom = @max(quad.ll.y, quad.lr.y);
- const rect = p.view().rects[0];
- var inside: usize = 0;
- for (rect.y..rect.y + rect.h) |row| for (rect.x..rect.x + rect.w) |col| {
- const point = panes.Pdf.panePointAtPage(p, pane, 0, @intCast(col), @intCast(row), false) orelse continue;
- if (point.x >= left and point.x <= right and point.y >= top and point.y <= bottom) inside += 1;
- };
- try std.testing.expect(inside > 0);
-}
-
-/// The pixels a backend samples out of one placement: the source rectangle,
-/// row by row, at the texture's own stride. Test-only, and the one operation
-/// that makes "same picture" mean something when the textures differ in shape.
-fn copySourceRect(
- gpa: std.mem.Allocator,
- place: Shown,
- src: pardes.RectPx,
-) ![]u8 {
- const stride = place.iw * 4;
- const row_len = @as(usize, src.w) * 4;
- const out = try gpa.alloc(u8, row_len * src.h);
- errdefer gpa.free(out);
- var row: usize = 0;
- while (row < src.h) : (row += 1) {
- const from = (@as(usize, src.y) + row) * stride + @as(usize, src.x) * 4;
- @memcpy(out[row * row_len ..][0..row_len], place.rgba[from..][0..row_len]);
- }
- return out;
-}
-
-test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape leaves at once" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 28,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
-
- // A second pane, then focus it and come back: `Last` has somewhere to go
- // and the PDF is where the keys land.
- panes.Pdf.openSections(p, 0);
- p.update(.{ .key = .{ .cp = 'w', .ctrl = true } });
- p.update(.{ .key = .{ .cp = 'j' } });
- p.update(.{ .key = .{ .cp = Key.enter } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- p.update(.{ .key = .{ .cp = 'w', .ctrl = true } });
- p.update(.{ .key = .{ .cp = 'k' } });
- p.update(.{ .key = .{ .cp = Key.enter } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
-
- // Everything a reader can see over the page: a search overlay and a live
- // word selection.
- try pv.setSearchQuery(p.pdf_gpa, "Pardes");
- var found = try pv.document.search(gpa, pv.page, "Pardes");
- defer found.deinit(gpa);
- try std.testing.expect(found.quads.len > 0);
- const quad = found.quads[0].quad;
- try std.testing.expectEqual(
- panes.Pdf.SelectionUpdate.changed,
- pv.setSelection(p.pdf_gpa, quad.ul, quad.lr, false),
- );
- p.update(.{ .key = .{ .cp = '3' } });
- const page_before = pv.page;
- const scroll_before = pv.document_scroll_y;
-
- // Escape drops the overlay and the selection, keeps the reading position,
- // and does NOT hand the keyboard to another pane.
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try std.testing.expect(pv.selection == null and pv.selection_text.len == 0);
- try std.testing.expectEqual(@as(usize, 0), pv.search_query.len);
- try std.testing.expect(pv.search_results == null);
- try std.testing.expect(!pv.highlights_dirty and !pv.search_reveal_pending);
- try std.testing.expectEqual(page_before, pv.page);
- try std.testing.expectEqual(scroll_before, pv.document_scroll_y);
- try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count);
- try std.testing.expectEqual(null, pane.body.normal.prefix);
- // With nothing left to drop, Escape goes back a pane as anywhere else,
- // and leaves the document as it found it.
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- try std.testing.expectEqual(page_before, pv.page);
- try std.testing.expectEqual(scroll_before, pv.document_scroll_y);
-
- // Shift-Escape goes at once, over a selection too.
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try std.testing.expectEqual(
- panes.Pdf.SelectionUpdate.changed,
- pv.setSelection(p.pdf_gpa, quad.ul, quad.lr, false),
- );
- p.update(.{ .key = .{ .cp = Key.escape, .shift = true } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- try std.testing.expect(pv.selection != null);
-
- // A text-only page shows neither: one Escape drops them and goes.
- p.view().frontend.native_images = false;
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try pv.setSearchQuery(p.pdf_gpa, "Pardes");
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- try std.testing.expect(pv.selection == null and pv.search_query.len == 0);
-}
-
-test "PDF continuous strip renders every intersecting short page" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- try std.testing.expect(pv.page_count > 3);
- p.view().frontend.native_images = true;
-
- // A legal wide MediaBox can make more than three pages intersect one
- // viewport. Seed tiny matching rasters so this tests transport/cache
- // cardinality without spending the unit test rendering fake page sizes.
- for (pv.page_sizes) |*size| size.* = .{ .width = 100_000, .height = 1 };
- pv.layout_valid = false;
- pv.scroll_to_page_pending = true;
- const viewport = panes.Pdf.ensurePaneLayout(p, pane).?;
- const visible = panes.Pdf.visiblePages(pv, viewport);
- try std.testing.expectEqual(pv.page_count, visible.len);
- const request = panes.Pdf.renderRequest(viewport, pdf_raster_policy, pv.fit);
- try std.testing.expect(pv.page_count <= pv.rasters.len);
- for (0..pv.page_count) |page| {
- const rgba = try gpa.alloc(u8, @as(usize, viewport.pixel_w) * 4);
- @memset(rgba, @intCast(page));
- pv.rasters[pv.rasters_len] = .{
- .valid = true,
- .page = page,
- .rgba = rgba,
- .iw = viewport.pixel_w,
- .ih = 1,
- .request = request,
- .request_valid = true,
- .tried = true,
- .tint_key = .{ .mode = pv.tint, .colors = panes.Pdf.tintColors(p) },
- .revision = @intCast(page + 1),
- };
- pv.rasters_len += 1;
- }
-
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- const surface = try p.render(frame.allocator());
- try std.testing.expectEqual(pv.page_count, surface.placements.items.len);
- try std.testing.expectEqual(pv.page_count, pv.rasters_len);
- for (try shownAll(p, frame.allocator()), 0..) |place, page| {
- try std.testing.expectEqual(@as(u32, @intCast(page)), place.page);
- try std.testing.expectEqual(@as(u32, 1), place.geometry.dst.h);
- }
-}
-
-test "PDF tint resolves a theme's null page colors to its chrome" {
- if (!pdf_enabled) return;
-
- const p = try Pardes.init(std.testing.allocator, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- // `dark` intentionally leaves page bg/fg null. PDF tint resolves those
- // deterministically to its chrome colors rather than host defaults.
- const dark_index = for (themes, 0..) |th, i| {
- if (std.mem.eql(u8, th.name, "dark")) break i;
- } else return error.MissingDarkTheme;
- pardes.colors.setThemeIndex(p, dark_index);
- const colors = panes.Pdf.tintColors(p);
- try std.testing.expectEqual(p.theme().tag_bg, colors.background);
- try std.testing.expectEqual(p.theme().tag_fg, colors.foreground);
-}
-
-test "PDF tint and tinted theme changes rebuild every visible raster only" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- _ = try p.render(frame.allocator());
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- pv.document_scroll_y = @floatFromInt(pv.page_starts[1] -| viewport.pixel_h / 2);
- _ = frame.reset(.retain_capacity);
- const default_surface = try p.render(frame.allocator());
- try std.testing.expectEqual(PdfTintMode.filtered, pv.tint);
- try std.testing.expectEqual(@as(usize, 2), default_surface.placements.items.len);
- try std.testing.expectEqual(@as(usize, 2), pv.rasters_len);
-
- const Snapshot = struct {
- page: u32,
- revision: u32,
- geometry: pardes.NativeGeometry,
- pixel_offset_y: f32,
- iw: usize,
- ih: usize,
- checksum: u64,
- };
- const Capture = struct {
- fn get(core: *Pardes, arena: std.mem.Allocator) ![2]Snapshot {
- if (core.surface.placements.items.len != 2) return error.UnexpectedVisiblePdfCount;
- var out: [2]Snapshot = undefined;
- const shown = try shownAll(core, arena);
- for (&out, 0..) |*snapshot, i| {
- const place = shown[i];
- snapshot.* = .{
- .page = place.page,
- .revision = place.revision,
- .geometry = place.geometry,
- .pixel_offset_y = place.pixel_offset_y,
- .iw = place.iw,
- .ih = place.ih,
- .checksum = std.hash.Wyhash.hash(0x5044_4654_494e_5421, place.rgba),
- };
- }
- return out;
- }
-
- fn expectGeometry(before: [2]Snapshot, after: [2]Snapshot) !void {
- for (before, after) |old, new| {
- try std.testing.expectEqual(old.page, new.page);
- try std.testing.expectEqual(old.geometry, new.geometry);
- try std.testing.expectEqual(old.pixel_offset_y, new.pixel_offset_y);
- try std.testing.expectEqual(old.iw, new.iw);
- try std.testing.expectEqual(old.ih, new.ih);
- }
- }
- };
- const default_filtered = try Capture.get(p, frame.allocator());
- for (pv.rasters[0..pv.rasters_len]) |raster|
- try std.testing.expectEqual(PdfTintMode.filtered, raster.tint_key.?.mode);
-
- const dark_index = for (themes, 0..) |th, i| {
- if (std.mem.eql(u8, th.name, "dark")) break i;
- } else return error.MissingDarkTheme;
- pardes.colors.setThemeIndex(p, dark_index);
- for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(!raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const themed = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(default_filtered, themed);
- for (default_filtered, themed) |old, new| {
- try std.testing.expect(new.revision > old.revision);
- try std.testing.expect(new.checksum != old.checksum);
- }
-
- panes.Pdf.toggleTint(pane);
- try std.testing.expectEqual(PdfTintMode.full, pv.tint);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const full = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(themed, full);
- for (themed, full) |old, new| {
- try std.testing.expect(new.revision > old.revision);
- }
- for (pv.rasters[0..pv.rasters_len]) |raster|
- try std.testing.expectEqual(PdfTintMode.full, raster.tint_key.?.mode);
-
- panes.Pdf.toggleTint(pane);
- try std.testing.expectEqual(PdfTintMode.disabled, pv.tint);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const disabled = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(full, disabled);
- for (full, disabled) |old, source| {
- try std.testing.expect(source.revision > old.revision);
- try std.testing.expect(source.checksum != old.checksum);
- }
-
- const acme_index = for (themes, 0..) |th, i| {
- if (std.mem.eql(u8, th.name, "acme")) break i;
- } else return error.MissingAcmeTheme;
- for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(raster.tried);
- pardes.colors.setThemeIndex(p, acme_index);
- // Disabled keys ignore theme colors, so neither explicit invalidation nor
- // the per-raster key comparison asks MuPDF for replacement pixels.
- for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const unchanged = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(disabled, unchanged);
- for (disabled, unchanged) |old, new| {
- try std.testing.expectEqual(old.revision, new.revision);
- try std.testing.expectEqual(old.checksum, new.checksum);
- }
- try std.testing.expectEqual(@as(usize, 2), pv.rasters_len);
-}
-
-test "PDF resize preserves page-relative document position" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- panes.Pdf.activatePage(p, pane, 1, true);
- _ = try p.render(frame.allocator());
- const fraction: f64 = 0.375;
- pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[1])) +
- fraction * @as(f64, @floatFromInt(pv.page_heights[1]));
- p.update(.{ .resize = .{
- .cols = 100,
- .rows = 24,
- .cell_pixels = p.view().cell_pixels,
- } });
- try std.testing.expect(!pv.layout_valid);
- try std.testing.expect(pv.layout_anchor_pending);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const resized_fraction = (pv.document_scroll_y -
- @as(f64, @floatFromInt(pv.page_starts[1]))) /
- @as(f64, @floatFromInt(pv.page_heights[1]));
- try std.testing.expectApproxEqAbs(fraction, resized_fraction, 0.000_001);
- try std.testing.expectEqual(@as(usize, 1), pv.page);
-
- const held = pv.document_scroll_y;
- p.update(.{ .resize = .{
- .cols = 100,
- .rows = 24,
- .cell_pixels = p.view().cell_pixels,
- } });
- try std.testing.expectEqual(held, pv.document_scroll_y);
- try std.testing.expect(pv.layout_valid);
-}
-
-test "PDF pane geometry change preserves its page-relative position" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- // A FILE boot is one pane now and a lone column always fills the window,
- // so the divider drag below needs a second column to take the width from.
- _ = try p.newShell(1, "");
- _ = layout.splitColumn(p, 0, 1, false);
- p.sync(); // rects for the new column, exactly as the two-pane boot did
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- panes.Pdf.activatePage(p, pane, 1, true);
- _ = try p.render(frame.allocator());
- const fraction: f64 = 0.625;
- pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[1])) +
- fraction * @as(f64, @floatFromInt(pv.page_heights[1]));
- const old_width = pv.layout_viewport_w;
-
- // A divider/split changes rects through computeGeom without emitting a
- // shell resize. panes.Pdf.ensurePaneLayout anchors against the old layout
- // before rebuilding it for this wider pane.
- const sibling_weight = p.view().cols[1].weight;
- p.view().cols[0].weight = sibling_weight * 6;
- layout.compute(p);
- try std.testing.expect(panes.Pdf.paneViewport(p, pane).?.pixel_w != old_width);
- try std.testing.expect(pv.layout_valid);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const changed_fraction = (pv.document_scroll_y -
- @as(f64, @floatFromInt(pv.page_starts[1]))) /
- @as(f64, @floatFromInt(pv.page_heights[1]));
- try std.testing.expectApproxEqAbs(fraction, changed_fraction, 0.000_001);
- try std.testing.expectEqual(@as(usize, 1), pv.page);
-
- // An explicit pending reveal wins over an implicit layout anchor.
- pv.page = 2;
- pv.scroll_to_page_pending = true;
- p.view().cols[0].weight = sibling_weight * 2;
- layout.compute(p);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- @as(f64, @floatFromInt(pv.page_starts[2])),
- pv.document_scroll_y,
- );
-}
-
-test "PDF n/N addresses and reveals distinct MuPDF hits on one page" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 120,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
-
- var page_hits = try pv.document.search(gpa, 0, "Pardes");
- defer page_hits.deinit(gpa);
- try std.testing.expect(page_hits.hit_count >= 3);
-
- p.locations_config.context = 2;
- p.locations_config.tscontext = true;
- _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true);
- const results_id = pane.search_pane orelse return error.MissingPdfSearchResults;
- const results = p.panes[results_id].?.file.?;
- var found: [3]bool = @splat(false);
- for (results.location_rows, 0..) |row, index| {
- // PDF locations address page/hit pairs, not binary file lines. Each
- // address owns one snippet, which must not add a navigation stop.
- if (index % 2 == 1) {
- try std.testing.expectEqual(.preview, row.kind);
- try std.testing.expectEqual(results.location_rows[index - 1].at, row.at);
- try std.testing.expectEqual(@as(usize, 0), row.code_start);
- try std.testing.expectEqualStrings("Pardes", pardes.modal.lineSlice(results.content, index));
- continue;
- }
- try std.testing.expectEqual(.match, row.kind);
- const line = pardes.modal.lineSlice(results.content, index);
- try std.testing.expectEqual(line.len, row.code_start);
- if (!std.mem.endsWith(u8, row.path, "design.pdf") or row.at.line != 1) continue;
- if (row.at.col < 1 or row.at.col > found.len) continue;
- found[row.at.col - 1] = true;
- }
- for (found) |present| try std.testing.expect(present);
-
- // Exaggerate the cell aspect only to make the three fixture hits occupy
- // distinct fit-width crops. The search/reveal math must use the same
- // reported metrics as placement, whatever a backend reports.
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = .{ .w = 16, .h = 4 },
- } });
-
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- try std.testing.expect(pardes.look.searchStep(p, 0, 1));
- try std.testing.expectEqual(@as(usize, 0), pv.search_hit);
- try std.testing.expectEqual(@as(usize, 0), pane.search_row.?);
- _ = try p.render(frame.allocator());
- const revision = (try shownAll(p, frame.allocator()))[0].revision;
- const raster = panes.Pdf.rasterForPage(pv, pv.page).?;
- const first_scroll = pv.document_scroll_y;
- const first_results = pv.search_results orelse return error.MissingPdfPageSearch;
- const first_quad = for (first_results.quads) |item| {
- if (item.hit == 0) break item.quad;
- } else return error.MissingFirstPdfHit;
- const first_y = panes.Pdf.normalizedPixel(
- (first_quad.ul.y + first_quad.ur.y + first_quad.ll.y + first_quad.lr.y) / 4,
- raster.ih,
- );
- const first_geometry = panes.Pdf.paneGeometry(p, pane) orelse return error.MissingPdfGeometry;
- try std.testing.expect(first_y >= first_geometry.src.y and
- first_y < first_geometry.src.y + first_geometry.src.h);
-
- try std.testing.expect(pardes.look.searchStep(p, 0, 1));
- try std.testing.expectEqual(@as(usize, 1), pv.search_hit);
- try std.testing.expectEqual(@as(usize, 2), pane.search_row.?);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(revision, (try shownAll(p, frame.allocator()))[0].revision);
-
- try std.testing.expect(pardes.look.searchStep(p, 0, 1));
- try std.testing.expectEqual(@as(usize, 2), pv.search_hit);
- try std.testing.expectEqual(@as(usize, 4), pane.search_row.?);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expect(pv.document_scroll_y != first_scroll);
- const third_results = pv.search_results orelse return error.MissingPdfPageSearch;
- const third_quad = for (third_results.quads) |item| {
- if (item.hit == 2) break item.quad;
- } else return error.MissingThirdPdfHit;
- const third_y = panes.Pdf.normalizedPixel(
- (third_quad.ul.y + third_quad.ur.y + third_quad.ll.y + third_quad.lr.y) / 4,
- raster.ih,
- );
- const third_geometry = panes.Pdf.paneGeometry(p, pane) orelse return error.MissingPdfGeometry;
- try std.testing.expect(third_y >= third_geometry.src.y and
- third_y < third_geometry.src.y + third_geometry.src.h);
-}
-
-test "PDF native mouse selection, Look, and highlights share page geometry" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- // A host without Kitty/native pixels keeps the projected-text contract:
- // j/k can still change pages and a body drag remains a generic selection.
- const fallback = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 0), fallback.placements.items.len);
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page);
- p.update(.{ .key = .{ .cp = 'k' } });
- try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.page);
- const fallback_rect = p.view().rects[0];
- const fallback_col = fallback_rect.x + config.GUTTER + 1;
- const fallback_row = fallback_rect.y + BOX_H + 1;
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = fallback_col, .row = fallback_row } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = fallback_col + 4, .row = fallback_row } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = fallback_col + 4, .row = fallback_row } });
- try std.testing.expectEqual(.done, pane.sel[sel_slot].state);
- try std.testing.expect(pane.pdf.?.selection == null);
- pane.sel[sel_slot].state = .none;
-
- p.view().frontend.native_images = true;
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const plain_revision = (try shownAll(p, frame.allocator()))[0].revision;
-
- var found = try pane.pdf.?.document.search(gpa, 0, "Pardes");
- defer found.deinit(gpa);
- const quad = found.quads[0].quad;
- const nx = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4;
- const ny = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4;
- const pv = pane.pdf.?;
- const raster = panes.Pdf.rasterForPage(pv, pv.page).?;
- const source_x: u32 = @intCast(@min(
- raster.iw - 1,
- @as(usize, @intFromFloat(nx * @as(f32, @floatFromInt(raster.iw)))),
- ));
- const source_y: u32 = @intCast(@min(
- raster.ih - 1,
- @as(usize, @intFromFloat(ny * @as(f32, @floatFromInt(raster.ih)))),
- ));
-
- // Bring the known word into the fit-width crop, then invert the shared
- // source/destination geometry to the nearest body cell.
- var geometry = panes.Pdf.paneGeometry(p, pane).?;
- if (source_y < geometry.src.y or source_y >= geometry.src.y + geometry.src.h) {
- const overflow = @as(u32, @intCast(raster.ih)) - geometry.src.h;
- const wanted = @min(overflow, source_y -| geometry.src.h / 2);
- pv.pan_y = if (overflow == 0) 0 else @intCast(
- (@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow,
- );
- geometry = panes.Pdf.paneGeometry(p, pane).?;
- }
- const pixel_x = geometry.dst.x + @as(u32, @intCast(
- @as(u64, source_x - geometry.src.x) * geometry.dst.w / geometry.src.w,
- ));
- const pixel_y = geometry.dst.y + @as(u32, @intCast(
- @as(u64, source_y - geometry.src.y) * geometry.dst.h / geometry.src.h,
- ));
- const r = p.view().rects[0];
- const base_col: i32 = @intCast(r.x + config.GUTTER + pixel_x / p.view().cell_pixels.w);
- const base_row: i32 = @intCast(r.y + BOX_H + pixel_y / p.view().cell_pixels.h);
-
- var selected_col: ?u16 = null;
- var selected_row: u16 = 0;
- const nearby = [_]i32{ 0, -1, 1, -2, 2 };
- find_word: for (nearby) |dy| for (nearby) |dx| {
- const col: u16 = @intCast(std.math.clamp(
- base_col + dx,
- @as(i32, r.x + config.GUTTER),
- @as(i32, r.x + r.w - 1),
- ));
- const row: u16 = @intCast(std.math.clamp(
- base_row + dy,
- @as(i32, r.y + BOX_H),
- @as(i32, r.y + r.h - 1),
- ));
- if (!panes.Pdf.beginDrag(p, pane, col, row, true)) continue;
- if (std.ascii.findIgnoreCase(pv.selection_text, "Pardes") != null) {
- selected_col = col;
- selected_row = row;
- break :find_word;
- }
- };
- const word_col = selected_col orelse return error.PdfMouseMappingMissedWord;
- try std.testing.expect(std.ascii.findIgnoreCase(
- pardes.exec.heldSelection(p, 0).?,
- "Pardes",
- ) != null);
-
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const selected_revision = (try shownAll(p, frame.allocator()))[0].revision;
- try std.testing.expect(selected_revision != plain_revision);
-
- // Repeating an identical drag endpoint is a no-op: Kitty/SDL keep the
- // same texture generation instead of retransmitting identical pixels.
- try std.testing.expect(panes.Pdf.beginDrag(p, pane, word_col, selected_row, true));
- try std.testing.expect(raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(selected_revision, (try shownAll(p, frame.allocator()))[0].revision);
-
- // Delayed native hover retains independent quads/text and changes only
- // presentation state. In particular it must not borrow the click path,
- // whose page activation and persistent selection are intentional effects
- // of a gesture rather than observation.
- {
- const delay = config.look_preview_delay_frames;
- const active_before = p.view().active;
- const page_before = pv.page;
- const scroll_before = pv.document_scroll_y;
- const sels_before = pane.sel;
- const cursor_before = .{ pane.body.cur_row, pane.body.cur_col };
- const modal_before = .{ pane.body.vsel, pane.body.nsel };
- const selection_before = pv.selection orelse return error.MissingPdfSelection;
- const selection_quads_before = try gpa.dupe(pdf_impl.Quad, selection_before.quads);
- defer gpa.free(selection_quads_before);
- const selection_text_before = try gpa.dupe(u8, pv.selection_text);
- defer gpa.free(selection_text_before);
- const selection_anchor_before = pv.selection_anchor;
- const selection_head_before = pv.selection_head;
- const query_before = try gpa.dupe(u8, pv.search_query);
- defer gpa.free(query_before);
- const search_hit_before = pv.search_hit;
- const jumps_before = .{ p.view().jumps.n, p.view().jumps.cur, p.n_look_src };
- const effects_before = p.effects_len;
- try std.testing.expect(p.view().drag == .none);
-
- const hover_motion = Event{ .mouse = .{
- .button = .none,
- .kind = .motion,
- .col = word_col,
- .row = selected_row,
- } };
- p.update(hover_motion);
- try std.testing.expect(p.look_hover_wait != null);
- for (0..delay) |_| p.update(.tick);
- const hover = p.pdf_hover_preview orelse return error.MissingPdfHoverPreview;
- try std.testing.expectEqual(@as(usize, 0), hover.probe.page);
- try std.testing.expect(hover.probe.quads.len > 0);
- try std.testing.expect(std.ascii.findIgnoreCase(hover.probe.text, "Pardes") != null);
- try std.testing.expect(p.look_hover_preview == null);
- try std.testing.expect(p.look_hover_wait == null);
-
- const decorated = try panes.Pdf.buildHighlights(
- pv,
- p.scratch.allocator(),
- panes.Pdf.highlightInput(p, 0, pane),
- );
- const page_highlights = decorated.forPage(pv.page);
- try std.testing.expectEqual(pdf_impl.HighlightKind.custom, page_highlights[0].kind);
- try std.testing.expectEqual(pdf_impl.HighlightKind.selection, page_highlights[page_highlights.len - 1].kind);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const hovered_revision = (try shownAll(p, frame.allocator()))[0].revision;
- try std.testing.expect(hovered_revision != selected_revision);
-
- p.update(.pointer_leave);
- try std.testing.expect(p.pdf_hover_preview == null);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != hovered_revision);
-
- try std.testing.expectEqual(active_before, p.view().active);
- try std.testing.expectEqual(page_before, pv.page);
- try std.testing.expectEqual(scroll_before, pv.document_scroll_y);
- try std.testing.expect(std.meta.eql(sels_before, pane.sel));
- try std.testing.expectEqual(cursor_before, .{ pane.body.cur_row, pane.body.cur_col });
- try std.testing.expect(std.meta.eql(modal_before, .{ pane.body.vsel, pane.body.nsel }));
- const selection_after = pv.selection orelse return error.HoverDroppedPdfSelection;
- try std.testing.expectEqualSlices(pdf_impl.Quad, selection_quads_before, selection_after.quads);
- try std.testing.expectEqualStrings(selection_text_before, pv.selection_text);
- try std.testing.expect(std.meta.eql(selection_anchor_before, pv.selection_anchor));
- try std.testing.expect(std.meta.eql(selection_head_before, pv.selection_head));
- try std.testing.expectEqualStrings(query_before, pv.search_query);
- try std.testing.expectEqual(search_hit_before, pv.search_hit);
- try std.testing.expectEqual(jumps_before, .{ p.view().jumps.n, p.view().jumps.cur, p.n_look_src });
- try std.testing.expectEqual(effects_before, p.effects_len);
- try std.testing.expect(p.view().drag == .none);
- }
-
- // A native right-click resolves the same MuPDF-snapped word and feeds it
- // to Look. Resolving it clears the previous selection, leaving the new
- // search highlights without carrying an old selection into the result.
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = word_col, .row = selected_row } });
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = word_col, .row = selected_row } });
- try std.testing.expect(std.ascii.findIgnoreCase(pv.search_query, "Pardes") != null);
- pv.resolveSearch(p.pdf_gpa);
- const highlights = (try panes.Pdf.buildHighlights(
- pv,
- p.scratch.allocator(),
- panes.Pdf.highlightInput(p, 0, pane),
- )).forPage(pv.page);
- try std.testing.expect(highlights.len > 0);
- for (highlights) |highlight| try std.testing.expectEqual(pdf_impl.HighlightKind.search, highlight.kind);
- try std.testing.expect(pv.selection == null and pv.selection_text.len == 0);
- const revision_before_reveal = raster.revision;
- const max_document_scroll = @as(f64, @floatFromInt(
- pv.document_height -| panes.Pdf.paneViewport(p, pane).?.pixel_h,
- ));
- pv.document_scroll_y = max_document_scroll;
- panes.Pdf.revealSearch(pv, panes.Pdf.paneViewport(p, pane).?, panes.Pdf.paneGeometry(p, pane));
- const revealed_scroll = pv.document_scroll_y;
- try std.testing.expect(revealed_scroll != max_document_scroll);
- try std.testing.expectEqual(revision_before_reveal, raster.revision);
- pv.document_scroll_y = max_document_scroll;
- panes.Pdf.revealSearch(
- pv,
- panes.Pdf.paneViewport(p, pane).?,
- panes.Pdf.paneGeometry(p, pane),
- ); // one shot: subsequent manual pan stays put
- try std.testing.expectEqual(max_document_scroll, pv.document_scroll_y);
- pv.document_scroll_y = revealed_scroll;
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != selected_revision);
-
- // Fit and viewport changes can crop a hit which was already revealed.
- // Fit remains placement-only. SDL's physical-viewport quality request
- // changes with a resize and therefore replaces pixels; Kitty's fixed,
- // bandwidth-conscious request retains them.
- const revision_before_geometry_change = (try shownAll(p, frame.allocator()))[0].revision;
- pv.search_reveal_pending = false;
- panes.Pdf.toggleFit(pane);
- try std.testing.expect(pv.search_reveal_pending);
- pv.search_reveal_pending = false;
- panes.Pdf.toggleFit(pane); // restore the reading-width geometry
- try std.testing.expect(pv.search_reveal_pending);
- pv.search_reveal_pending = false;
- const original_cell_pixels = p.view().cell_pixels;
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = p.view().cell_pixels,
- } });
- try std.testing.expect(!pv.search_reveal_pending);
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = .{
- .w = original_cell_pixels.w,
- .h = original_cell_pixels.h + 1,
- },
- } });
- try std.testing.expect(pv.search_reveal_pending);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- if (pdf_raster_policy.match_viewport)
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision !=
- revision_before_geometry_change)
- else
- try std.testing.expectEqual(
- revision_before_geometry_change,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = original_cell_pixels,
- } });
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
-
- // Unsupported text-selection actions are consumed by the PDF adapter:
- // they neither invent a range over placeholder cells nor disturb the
- // native MuPDF selection. The select-button's no-drag click still clears.
- try std.testing.expect(panes.Pdf.beginDrag(p, pane, word_col, selected_row, true));
- p.update(.{ .key = .{ .cp = 'v' } });
- try std.testing.expect(pv.selection != null);
- try std.testing.expect(!pane.body.vsel.active);
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = word_col, .row = selected_row } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = word_col, .row = selected_row } });
- try std.testing.expect(pv.selection == null);
- try std.testing.expect(panes.Pdf.beginDrag(p, pane, word_col, selected_row, true));
-
- // Native drag events update MuPDF quads and copied text immediately, but
- // keep the already transmitted page generation stable until release.
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const before_drag_revision = (try shownAll(p, frame.allocator()))[0].revision;
- const drag_col = @min(r.x + r.w - 1, word_col +| 12);
- const drag_row = @min(r.y + r.h - 1, selected_row +| 4);
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .press,
- .col = word_col,
- .row = selected_row,
- } });
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .drag,
- .col = @min(drag_col, word_col +| 4),
- .row = @min(drag_row, selected_row +| 2),
- } });
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- before_drag_revision,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .drag,
- .col = drag_col,
- .row = drag_row,
- } });
- try std.testing.expect(p.view().drag.select.pdf.selection_changed);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- before_drag_revision,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .release,
- .col = drag_col,
- .row = drag_row,
- } });
- try std.testing.expect(!raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- before_drag_revision + 1,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- (try shownAll(p, frame.allocator()))[0].revision,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
-
- const saved_query = try gpa.dupe(u8, pv.search_query);
- defer gpa.free(saved_query);
- const saved_selection = try gpa.dupe(u8, pv.selection_text);
- defer gpa.free(saved_selection);
- const selected_page = pv.selection_page;
- panes.Pdf.activatePage(p, pane, 1, true);
- try std.testing.expect(pv.selection != null);
- try std.testing.expectEqual(selected_page, pv.selection_page);
- try std.testing.expectEqualStrings(saved_selection, pv.selection_text);
- try std.testing.expectEqualStrings(saved_query, pv.search_query);
-}
-
-test "Esc back into a PDF keeps the offset within its page" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const fixture = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
-
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- p.update(.{ .resize = .{ .cols = 80, .rows = 28 } });
- const doc = p.view().active;
- const dp = p.panes[doc].?;
- try std.testing.expect(dp.pdf != null);
- p.sync();
-
- // Read a little way DOWN the page you are on, then step away.
- const pv = dp.pdf.?;
- pv.document_scroll_y += 137;
- const mid = pv.document_scroll_y;
- pv.scroll_to_page_pending = false;
- p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc
- p.sync();
- const shell = p.view().active;
- try std.testing.expect(shell != doc);
-
- p.update(.{ .key = .{ .cp = Key.escape } }); // Esc: back into the PDF
- p.sync();
- try std.testing.expectEqual(doc, p.view().active);
-
- // The jumps stack records a PDF as its PAGE, so returning revealed the page
- // you were already on — and a reveal sets `document_scroll_y` to that page's
- // start, throwing away where you had read to inside it.
- try std.testing.expectEqual(mid, pv.document_scroll_y);
- // Same reveal, the other half: with no valid layout yet it only ARMS the
- // snap, so a test that watched the offset alone would not see it coming.
- try std.testing.expect(!pv.scroll_to_page_pending);
-}
-
-test "PDF Back and Forward clear selections and land on recorded pages" {
- if (!pdf_enabled) return error.SkipZigTest;
- const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const state = pane.pdf.?;
- try std.testing.expect(state.page_count > 1);
- try std.testing.expect(state.focusLocation(p.pdf_gpa, 2, 0));
- p.view().jumps.n = 2;
- p.view().jumps.cur = 1;
- p.view().jumps.list[0] = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 0 };
- p.view().jumps.list[1] = .{ .pane = 0, .serial = pane.serial, .line = 2, .col = 0 };
- for ([_]u21{ 'o', 'i' }, 0..) |key, destination| {
- try std.testing.expectEqual(panes.Pdf.SelectionUpdate.changed, state.setSelection(p.pdf_gpa, .{ .x = 0, .y = 0 }, .{ .x = 1, .y = 1 }, true));
- try std.testing.expect(state.selection != null and state.selection_text.len > 0);
- p.update(.{ .key = .{ .cp = key, .ctrl = true } });
- try std.testing.expectEqual(destination, p.view().jumps.cur);
- try std.testing.expectEqual(destination, state.page);
- try std.testing.expect(state.selection == null);
- try std.testing.expect(state.selection_page == null);
- try std.testing.expectEqual(@as(usize, 0), state.selection_text.len);
- try std.testing.expect(state.drag_anchor == null and state.drag_head == null);
- }
-}
-
-test "a PDF's fit and tint, and Collapse, read in its ctl and come back from a Dump" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const fixture = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- const doc = p.panes[0].?;
- try std.testing.expect(p.executeBuiltinLine(0, "PdfFit height"));
- try std.testing.expect(p.executeBuiltinLine(0, "PdfTint full"));
- const ctlfs = pardes.ctlfs;
- const ctl_node = ctlfs.Node.of(doc.serial, .ctl);
- const read = p.fsPayload(p.serveFs(.{ .tag = 1, .op = .read, .node = ctl_node, .size = 4096 }));
- try std.testing.expect(std.mem.indexOf(u8, read, "fit:height tint:full ") != null);
- try pardes.dump.dumpState(p);
- const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
- defer restored.deinit();
- const pv = restored.panes[0].?.pdf.?;
- try std.testing.expectEqualStrings("height", @tagName(pv.fit));
- try std.testing.expectEqualStrings("full", @tagName(pv.tint));
-}
-
-/// The jumplist's PDF (pdfrender): the Intel SDM (5363 pages, the author's
-/// stress file) when this machine has it, else the docs' PDF; the same
-/// checks either way.
-fn jumpPdf() []const u8 {
- const sdm = "/home/goblin/00-projects/kvmctf/harnesses/contained-official/visor-uefi/intel-ia32-manual.pdf";
- std.Io.Dir.accessAbsolute(std.testing.io, sdm, .{}) catch return "docs/design.pdf";
- return sdm;
-}
-
-/// Lays the PDF pane out (a frame drawn) and syncs, so the jumplist sees it.
-fn jumpFrame(p: *Pardes) !void {
- var frame: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- p.sync();
-}
-
-fn stripAtPlace(p: *Pardes, pane: *pardes.Pane, page: usize, fraction: f64) !f64 {
- const pv = pane.pdf.?;
- pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[page])) + fraction * @as(f64, @floatFromInt(pv.page_heights[page]));
- try jumpFrame(p);
- return pv.document_scroll_y;
-}
-
-test "a PDF's jumps: Back after a far jump returns to the exact offset, two places on one page are two entries" {
- if (!pdf_enabled) return error.SkipZigTest;
- const p = try Pardes.init(std.testing.allocator, .{ .file = jumpPdf(), .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const id = p.view().active;
- const pane = p.panes[id].?;
- const pv = pane.pdf.?;
- try jumpFrame(p);
- try std.testing.expect(pv.page_count > 3);
- // Two places on page 1, more than a body apart: two entries.
- const before = p.view().jumps.n;
- _ = try stripAtPlace(p, pane, 1, 0.05);
- const near = try stripAtPlace(p, pane, 1, 0.8);
- try std.testing.expectEqual(before + 2, p.view().jumps.n);
- try std.testing.expect(p.view().jumps.list[p.view().jumps.n - 1].pdf);
- // A far jump (a Look at a page), then Back: the exact offset, not the
- // page's top, and its page.
- look.lookAt(p, id, if (pv.page_count > 3000) ":3000" else ":4");
- try jumpFrame(p);
- try std.testing.expect(pv.page >= 3);
- pardes.Jump.jumpBy(p, -1);
- try jumpFrame(p);
- try std.testing.expectEqual(@as(usize, 1), pv.page);
- try std.testing.expectApproxEqAbs(near, pv.document_scroll_y, 0.5);
- // A wheel's small steps are the same visit: the entry follows them.
- const n = p.view().jumps.n;
- for (0..4) |_| {
- _ = panes.Pdf.scrollPane(p, pane, 30, true);
- try jumpFrame(p);
- }
- try std.testing.expectEqual(n, p.view().jumps.n);
-}
-
-test "a PDF's jumps keep to the PDF, and a closed PDF reopens at its place" {
- if (!pdf_enabled) return error.SkipZigTest;
- // Recent keeps a file by the path it was opened as: a real one here,
- // as a Look opens one.
- var cwd_buf: [4096]u8 = undefined;
- const cwd = cwd_buf[0..try std.Io.Dir.cwd().realPath(std.testing.io, &cwd_buf)];
- var path_buf: [4200]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, "{s}/docs/design.pdf", .{cwd});
- const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const doc = p.view().active;
- const pane = p.panes[doc].?;
- try jumpFrame(p);
- const first = try stripAtPlace(p, pane, 1, 0.3);
- // A text between, then a far place in the PDF.
- look.lookAt(p, doc, "../build.zig:10");
- try jumpFrame(p);
- try std.testing.expect(p.view().active != doc);
- p.view().active = doc;
- _ = try stripAtPlace(p, pane, 3, 0.5);
- // Back from the PDF keeps to it: its own earlier place, not the text.
- pardes.Jump.jumpBy(p, -1);
- try jumpFrame(p);
- try std.testing.expectEqual(doc, p.view().active);
- try std.testing.expectApproxEqAbs(first, pane.pdf.?.document_scroll_y, 0.5);
- // Closed, its entries stay; Back from the text reopens it at the place.
- pardes.Jump.jumpBy(p, 1);
- try jumpFrame(p);
- try p.removePane(doc, null);
- try jumpFrame(p);
- var closed = false;
- for (p.view().jumps.list[0..p.view().jumps.n]) |j| closed = closed or (j.serial == 0 and j.pdf);
- try std.testing.expect(closed);
- var tries: usize = 0;
- while (tries < 4) : (tries += 1) {
- pardes.Jump.jumpBy(p, -1);
- try jumpFrame(p);
- if (p.panes[p.view().active].?.pdf != null) break;
- }
- const reopened = p.panes[p.view().active].?;
- try std.testing.expect(reopened.pdf != null);
- const pv = reopened.pdf.?;
- // The newest PDF place before the text: page 4, half way down.
- try std.testing.expectEqual(@as(usize, 3), pv.page);
- const want = @as(f64, @floatFromInt(pv.page_starts[3])) + 0.5 * @as(f64, @floatFromInt(pv.page_heights[3]));
- try std.testing.expectApproxEqAbs(want, pv.document_scroll_y, 0.5);
-}
diff --git a/test/process.zig b/test/process.zig
index 0a443a21..67d883ca 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -512,9 +512,11 @@ 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;
+/// The addons the build made (the runner's --addon=, image and pdf),
+/// linked into each session's data directory, where its start scan finds
+/// them.
+pub var addons: [4][:0]const u8 = undefined;
+pub var naddons: usize = 0;
/// A case about one frontend's own behaviour (`--tty`, a killed terminal
/// editor) skips on the other.
@@ -586,9 +588,13 @@ 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 (naddons > 0) 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);
+ };
+ for (addons[0..naddons]) |lib| {
+ const base = std.fs.path.basename(lib);
+ const installed = if (std.mem.startsWith(u8, base, "lib")) base[3..] else base;
+ _ = libc.symlink(lib, try std.fmt.bufPrintSentinel(&bufs[5], "{s}/.local/share/pardes/addons/{s}", .{ dir, installed }, 0));
}
if (opts.init) |text| {
const cfg = try std.fmt.bufPrintSentinel(&bufs[5], "{s}/config", .{dir}, 0);
diff --git a/test/process_test.zig b/test/process_test.zig
index 37dd0954..b1f64a45 100644
--- a/test/process_test.zig
+++ b/test/process_test.zig
@@ -22,14 +22,16 @@ const files = .{
pub fn main(init: std.process.Init) !void {
const all = try init.minimal.args.toSlice(init.arena.allocator());
- // <pardes> [--backend=tui|gui] [--image-addon=<image.so>] [filter]
+ // <pardes> [--backend=tui|gui] [--addon=<lib>]... [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 (std.mem.startsWith(u8, a, "--addon=")) {
+ if (process.naddons == process.addons.len) return error.Usage;
+ process.addons[process.naddons] = try std.Io.Dir.cwd().realPathFileAlloc(init.io, a["--addon=".len..], init.arena.allocator());
+ process.naddons += 1;
} else if (n < args.len) {
args[n] = a;
n += 1;
diff --git a/test/session.zig b/test/session.zig
index 5b608521..8b8ec17f 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -403,24 +403,39 @@ pub const Session = struct {
// pdf:
+ /// The pdf addon (addons/pdf/pdf.c), as the build makes it; a build
+ /// without it (-Dmupdf=false) has none.
+ pub const pdf_addon: ?[]const u8 = if (@import("session_options").has_pdf_addon) @import("session_options").pdf_addon else null;
+
+ /// The pdf addon loaded into the session, once: a test of a PDF in a
+ /// build without it skips.
+ pub fn loadPdf(s: *Session) !void {
+ const lib = pdf_addon orelse return error.SkipZigTest;
+ if (std.mem.indexOf(u8, try s.read("/addons"), "pdf ") != null) return;
+ const real = try std.Io.Dir.cwd().realPathFileAlloc(std.testing.io, lib, s.arena.allocator());
+ try s.write("/ctl", s.at("Addon load {s}\n", .{real}));
+ }
+
/// A Look of `path` at the root (one relative to the working directory
/// made absolute first); the serial of the pane with the keyboard after.
- /// A PDF in a build without them (-Dmupdf=false: no PdfTint in
- /// /commands) skips the test.
+ /// A PDF loads the pdf addon first.
pub fn lookFile(s: *Session, path: []const u8) !u32 {
- if (std.mem.endsWith(u8, path, ".pdf") and std.mem.indexOf(u8, try s.read("/commands"), "PdfTint") == null) return error.SkipZigTest;
+ if (std.mem.endsWith(u8, path, ".pdf")) try s.loadPdf();
var buf: [4096]u8 = undefined;
const abs = if (std.fs.path.isAbsolute(path)) path else s.at("{s}/{s}", .{ buf[0..try std.Io.Dir.cwd().realPath(std.testing.io, &buf)], path });
try s.write("/look", s.at("{s}\n", .{abs}));
return s.focused();
}
- /// The page a PDF pane shows and its pages, from its tag's `[page/pages]`.
+ /// The page a PDF pane shows and its pages, from its tag's `[page/pages]`
+ /// (the pdf addon's prefix, which starts it).
pub fn pdfPage(s: *Session, n: u32) !struct { u32, u32 } {
+ // A kind's prefix is its last frame's: one drawn first.
+ _ = try s.read("/screen");
const tag = try s.read(s.at("/pane/{d}/tag", .{n}));
- const lo = std.mem.indexOf(u8, tag, " [") orelse return error.NoPage;
- const close = std.mem.indexOfScalarPos(u8, tag, lo, ']') orelse return error.NoPage;
- var it = std.mem.splitScalar(u8, tag[lo + 2 .. close], '/');
+ if (!std.mem.startsWith(u8, tag, "[")) return error.NoPage;
+ const close = std.mem.indexOfScalar(u8, tag, ']') orelse return error.NoPage;
+ var it = std.mem.splitScalar(u8, tag[1..close], '/');
return .{ try std.fmt.parseInt(u32, it.next().?, 10), try std.fmt.parseInt(u32, it.next() orelse return error.NoPage, 10) };
}
diff --git a/test/snapshot.zig b/test/snapshot.zig
index 26022a41..51c81dd9 100644
--- a/test/snapshot.zig
+++ b/test/snapshot.zig
@@ -86,9 +86,10 @@ 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;
+/// abs paths of the addons the build made (--addon=, image and pdf), linked
+/// into each script's data directory, where a session's start scan finds them
+var addons: [4][:0]const u8 = undefined;
+var naddons: usize = 0;
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.
@@ -136,8 +137,10 @@ 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, "--addon=")) {
+ if (naddons == addons.len) return error.TooManyAddons;
+ addons[naddons] = try arena.dupeSentinel(u8, try absPath(arena, orig_cwd, a["--addon=".len..]), 0);
+ naddons += 1;
} 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=")) {
@@ -170,7 +173,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, "--addon=") or
std.mem.startsWith(u8, a, "--record=") or
std.mem.startsWith(u8, a, "--tape=") or
std.mem.eql(u8, a, "--dump") or
@@ -637,9 +640,12 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const
// ...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;
+ if (naddons > 0) 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);
+ for (addons[0..naddons]) |lib| {
+ // libpdf.so as pdf.so: the name a build installs it as.
+ const file = std.fs.path.basename(lib);
+ const installed = if (std.mem.startsWith(u8, file, "lib")) file[3..] else file;
+ if (libc.symlink(lib, try std.fmt.allocPrintSentinel(arena, "{s}/pardes/addons/{s}", .{ data_home, installed }, 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