diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-06 06:24:42 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-06 11:19:44 -0300 |
| commit | c1917b949b9580de8bf0977874a210f0266812da (patch) | |
| tree | 447dd2235ea00634f662cd3becf4bceb8a895f41 /test/pdf.zig | |
| parent | 76c55b5bce0f181b0b15b16596c900397dfef544 (diff) | |
| download | pardes-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/pdf.zig')
| -rw-r--r-- | test/pdf.zig | 2246 |
1 files changed, 0 insertions, 2246 deletions
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, §ions.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); -} |
