summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-06 06:24:42 -0300
committerGabriel Schneider <[email protected]>2026-11-06 11:19:44 -0300
commitc1917b949b9580de8bf0977874a210f0266812da (patch)
tree447dd2235ea00634f662cd3becf4bceb8a895f41
parent76c55b5bce0f181b0b15b16596c900397dfef544 (diff)
downloadpardes-c1917b949b9580de8bf0977874a210f0266812da.tar.gz
pardes-c1917b949b9580de8bf0977874a210f0266812da.zip
kinds #14, the core's PDF code gone: pdf.zig and pdf_view.zig leave and every pdf_enabled branch with them; look, Jump, Recent, dumps (one from before the addon opens as its pane), the watch, mouse, keys, the rail and the tag go through Kind for any kind's pane; test/pdf.zig's behaviours are T1 cases over 9P (addons_pdf.zig) and pane cases (a Shadow over a replica, a file changed under it), the harnesses load pdf.so by path
Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
-rw-r--r--docs/typ/builtins-gui.json3
-rw-r--r--docs/typ/builtins-tui.json3
-rw-r--r--src/Core.zig96
-rw-r--r--src/Effect.zig4
-rw-r--r--src/Event.zig14
-rw-r--r--src/Jump.zig77
-rw-r--r--src/Output.zig26
-rw-r--r--src/Store.zig2
-rw-r--r--src/body_layer.zig16
-rw-r--r--src/builtins.zig59
-rw-r--r--src/colors.zig10
-rw-r--r--src/config.zig49
-rw-r--r--src/draw.zig43
-rw-r--r--src/dump.zig67
-rw-r--r--src/edit.zig33
-rw-r--r--src/exec.zig8
-rw-r--r--src/file_watch.zig89
-rw-r--r--src/fs.zig3
-rw-r--r--src/gui/gui.zig61
-rw-r--r--src/host_io.zig26
-rw-r--r--src/keys.zig8
-rw-r--r--src/look.zig301
-rw-r--r--src/macos.zig44
-rw-r--r--src/memory.zig18
-rw-r--r--src/modal.zig2
-rw-r--r--src/mouse.zig102
-rw-r--r--src/ninep/ctl.zig54
-rw-r--r--src/ninep/pane.zig21
-rw-r--r--src/normal.zig23
-rw-r--r--src/panes.zig76
-rw-r--r--src/pardes.zig30
-rw-r--r--src/pdf.zig1904
-rw-r--r--src/pdf_view.zig3721
-rw-r--r--src/replica.zig2
-rw-r--r--src/rollback.zig12
-rw-r--r--src/surface.zig6
-rw-r--r--src/tagline.zig14
-rw-r--r--src/tape.zig12
-rw-r--r--src/terminal.zig5
-rw-r--r--src/tui/tui.zig112
-rw-r--r--src/walk.zig9
-rw-r--r--src/wire.zig55
-rw-r--r--test/behaviour.zig1
-rw-r--r--test/behaviour/addons_pdf.zig231
-rw-r--r--test/behaviour/keys.zig48
-rw-r--r--test/image_harness.zig11
-rw-r--r--test/mode.zig17
-rw-r--r--test/panes.zig313
-rw-r--r--test/pdf.zig2246
-rw-r--r--test/process.zig18
-rw-r--r--test/process_test.zig8
-rw-r--r--test/session.zig29
-rw-r--r--test/snapshot.zig24
53 files changed, 1046 insertions, 9120 deletions
diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json
index 1fe1f0fb..40a99f83 100644
--- a/docs/typ/builtins-gui.json
+++ b/docs/typ/builtins-gui.json
@@ -71,9 +71,6 @@
{"name": "NextColor", "leader": "SPC t n", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Switch to the next bundled theme."},
{"name": "Palette", "leader": "SPC t l", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "the C64 palette or the terminal's own 16"},
{"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."},
- {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."},
- {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."},
- {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."},
{"name": "Pet", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "off, cat, frog", "doc": "The window's companion in the workspace tag's blank space: off, cat or frog."},
{"name": "Petscii", "leader": "SPC t p", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "glyph art over the host's pixels: an image pane's picture, or the kitty graphics a terminal's program placed (yazi's previews)"},
{"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."},
diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json
index 647cdf1b..728bb884 100644
--- a/docs/typ/builtins-tui.json
+++ b/docs/typ/builtins-tui.json
@@ -67,9 +67,6 @@
{"name": "NextColor", "leader": "SPC t n", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Switch to the next bundled theme."},
{"name": "Palette", "leader": "SPC t l", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "the C64 palette or the terminal's own 16"},
{"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."},
- {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."},
- {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."},
- {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."},
{"name": "Petscii", "leader": "SPC t p", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "glyph art over the host's pixels: an image pane's picture, or the kitty graphics a terminal's program placed (yazi's previews)"},
{"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."},
{"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."},
diff --git a/src/Core.zig b/src/Core.zig
index b1195ac2..cd7b4ec5 100644
--- a/src/Core.zig
+++ b/src/Core.zig
@@ -74,7 +74,6 @@ const modal = pardes.modal;
const mouse = pardes.mouse;
const newer_build_words = pardes.newer_build_words;
const pager = pardes.pager;
-const pdf_enabled = pardes.pdf_enabled;
const platform = pardes.platform;
const recent_files = @import("recent.zig");
const sel_slot = pardes.sel_slot;
@@ -164,6 +163,11 @@ pub const View = struct {
header_drag: bool = false,
/// A middle or right sweep held over a column's or the workspace's tag.
header_sweep: ?mouse.HeaderSweep = null,
+ /// The kind's pane a press went to, which has its drag and release
+ /// wherever the pointer goes; and the one the pointer is over, told
+ /// when it leaves (mouse.kindMouse).
+ kind_grab: ?u8 = null,
+ kind_hover: ?u8 = null,
header_scroll: usize = 0,
/// The focused header's first line on screen, which follows its caret
/// when it has more lines than rows.
@@ -180,7 +184,6 @@ image_gpa: std.mem.Allocator,
/// Its kinds of pane (Kind.zig): the compiled-in ones, then what addons
/// brought; the data both cores hold, the code only the authority.
kinds: pardes.Kind.Registry = .{},
-pdf_gpa: std.mem.Allocator,
tree_sitter_gpa: std.mem.Allocator,
opts: Options,
resize_count: usize = 0,
@@ -271,7 +274,6 @@ look_hover_wait: ?look.LookHoverWait = null,
/// resting there does not ask again every frame (look.noteLookHover).
look_hover_refused: ?look.LookHoverWait = null,
look_hover_preview: ?look.LookHoverPreview = null,
-pdf_hover_preview: if (pdf_enabled) ?look.PdfWordPreview else void = if (pdf_enabled) null else {},
/// While a key is replayed across the ranges (normal.replaySels): which
/// range this pass is, in document order, how many there are, and
/// whether this is the first pass; outside a replay, the one range and
@@ -472,7 +474,6 @@ pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes {
.gpa = gpa,
.image_gpa = opts.image_allocator orelse gpa,
.kinds = .started(opts.addons),
- .pdf_gpa = opts.pdf_allocator orelse gpa,
.tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa,
.opts = opts,
.tty_toggle = opts.tty_toggle,
@@ -520,10 +521,18 @@ fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes {
.document => {
const path = opts.file.?;
const opened = initial_doc: {
- if (comptime pdf_enabled) if (look.isPdfPath(path))
- break :initial_doc pardes.panes.Pdf.openPane(p, 0, path, opts.file_line, .last);
- if (p.kinds.forPath(path)) |kind|
- break :initial_doc pardes.Kind.openFile(p, 0, kind, path);
+ if (p.kinds.forPath(path)) |kind| {
+ const made = pardes.Kind.openFile(p, 0, kind, path);
+ // `pardes book.pdf:12`'s place, the kind's to take.
+ if (made) |_| {
+ if (opts.file_line > 0) {
+ var said: pardes.Kind.Buf(160) = .{};
+ var place: [16]u8 = undefined;
+ _ = pardes.Kind.address(p, 0, std.fmt.bufPrint(&place, "{d}", .{opts.file_line}) catch "", &said);
+ }
+ } else |_| {}
+ break :initial_doc made;
+ }
break :initial_doc pardes.panes.File.open(p, 0, path, opts.file_line);
};
if (opened) |_| {} else |err| {
@@ -661,7 +670,7 @@ pub fn recentKeeps(path: []const u8) bool {
return exec.kindOf(local) == .file;
}
-/// A file, PDF or image pane closing: its place noted in Recent, when
+/// A file pane or a kind's (a PDF, a picture) closing: its place noted in Recent, when
/// Recent keeps it.
pub fn noteClosed(p: *Pardes, pane: *const Pane) void {
const d = recentPlace(pane) orelse return;
@@ -674,12 +683,16 @@ pub fn noteClosed(p: *Pardes, pane: *const Pane) void {
pub const RecentPlace = struct { path: []const u8, line: u32, col: u32, aline: u32 = 0, acol: u32 = 0 };
-/// Where a pane is, as Recent keeps it: a file's dot, a PDF's page
-/// (`:page:1`), a kind's pane's path alone (line 0). Null for any other.
+/// Where a pane is, as Recent keeps it: a file's dot, a kind's pane's
+/// path and the first number of its `where` (a PDF's page), 0 for none.
+/// Null for any other.
pub fn recentPlace(pane: *const Pane) ?RecentPlace {
if (recentDot(pane)) |d| return .{ .path = d.path, .line = d.line, .col = d.col, .aline = d.aline, .acol = d.acol };
- if (pane.pdfPath()) |path| return .{ .path = path, .line = @intCast(pane.pdfPage().? + 1), .col = 1 };
- if (pane.addon) |k| if (k.path.len > 0) return .{ .path = k.path, .line = 0, .col = 0 };
+ if (pane.addon) |k| if (k.path.len > 0) {
+ var buf: [32]u8 = undefined;
+ const line = Jump.firstNumber(pardes.Kind.placeOf(@constCast(k), &buf));
+ return .{ .path = k.path, .line = line, .col = @intFromBool(line > 0) };
+ };
return null;
}
@@ -1038,13 +1051,7 @@ pub fn rejectFont(p: *Pardes) void {
fn applyWatchedFileChanged(p: *Pardes, id: u8, bytes: []const u8) bool {
if (id >= MAX_PANES) return false;
const pane = p.panes[id] orelse return false;
- if (comptime pdf_enabled) if (pane.pdf != null) {
- pardes.panes.Pdf.reloadWatched(p, pane) catch |err| {
- p.reportError(id, "PDF reload", err);
- return false;
- };
- return true;
- };
+ if (pane.addon != null) return pardes.Kind.fileChanged(p, id, bytes);
if (pane.file == null) return false;
pardes.panes.File.changed(p, id, bytes);
return if (p.panes[id]) |current|
@@ -1536,7 +1543,6 @@ pub fn update(p: *Pardes, ev: Event) void {
.mouse => |m| m.button == .none and m.kind == .motion,
.output => |o| look.lookHoverPane(p) != o.pane,
.file_changed => |changed| look.lookHoverPane(p) != changed.pane,
- .pdf_scroll => |scroll| look.lookHoverPane(p) != scroll.pane,
else => false,
};
if (!hover_stays) {
@@ -1566,31 +1572,11 @@ pub fn update(p: *Pardes, ev: Event) void {
switch (ev) {
.resize => |sz| {
if (sz.row_metrics) |metrics| v.row_metrics = metrics;
- if (comptime pdf_enabled) {
- var before: [MAX_PANES]?pardes.panes.Pdf.Viewport = @splat(null);
- for (p.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- if (pane.pdf != null) before[id] = pardes.panes.Pdf.paneViewport(p, pane);
- }
- v.screen_w = sz.cols;
- v.screen_h = sz.rows;
- v.cell_pixels.w = @max(1, sz.cell_pixels.w);
- v.cell_pixels.h = @max(1, sz.cell_pixels.h);
- layout.compute(p);
- for (p.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- if (pane.pdf) |pv| {
- if (!std.meta.eql(before[id], pardes.panes.Pdf.paneViewport(p, pane))) {
- pardes.panes.Pdf.captureLayoutAnchor(pv);
- pv.layout_valid = false;
- pv.search_reveal_pending = pv.search_query.len > 0;
- }
- }
- }
- } else {
- v.screen_w = sz.cols;
- v.screen_h = sz.rows;
- }
+ v.screen_w = sz.cols;
+ v.screen_h = sz.rows;
+ v.cell_pixels.w = @max(1, sz.cell_pixels.w);
+ v.cell_pixels.h = @max(1, sz.cell_pixels.h);
+ layout.compute(p);
p.resize_count += 1;
},
.output => |o| {
@@ -1625,16 +1611,6 @@ pub fn update(p: *Pardes, ev: Event) void {
@import("keys.zig").handleKey(p, key);
},
.mouse => |m| mouse.handleMouse(p, m),
- .pdf_scroll => |scroll| {
- if (comptime pdf_enabled) {
- if (scroll.pane < MAX_PANES) {
- if (p.panes[scroll.pane]) |pane| {
- if (pane.hasPdf() and v.frontend.native_images)
- _ = pardes.panes.Pdf.scrollPane(p, pane, @floatCast(scroll.delta_pixels), scroll.glide);
- }
- }
- }
- },
.paste => |bytes| {
p.typedInto();
edit.applyPaste(p, bytes);
@@ -1651,6 +1627,7 @@ pub fn update(p: *Pardes, ev: Event) void {
v.frontend = f;
},
.pointer_leave => {
+ mouse.kindLeave(p);
v.pointer_inside = false;
v.pointer_body_hit = null;
v.pointer_tag_hit = null;
@@ -1955,8 +1932,6 @@ pub fn nextWake(p: *const Pardes) ?u64 {
for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next;
const kinds = pardes.Kind.wake(p);
if (kinds) |due| if (due <= next) return next;
- // A PDF page being rendered on a lane lands on the frame after it is done.
- if (comptime pdf_enabled) for (p.panes) |slot| if (slot) |pane| if (pane.pdf) |st| if (pardes.panes.Pdf.rendering(st)) return next;
// A markdown text's tables still being read from the top (Tables.zig).
for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.tables.busy()) return next;
if (pardes.panes.Query.busy(p)) return next;
@@ -2193,7 +2168,6 @@ pub const Options = struct {
image_allocator: ?std.mem.Allocator = null,
/// What the host's scan of the addon directories found (Addon.scan).
addons: []const pardes.Kind.Loaded = &.{},
- pdf_allocator: ?std.mem.Allocator = null,
tree_sitter_allocator: ?std.mem.Allocator = null,
/// Where each frame's Surface text is built. Hosts pass a purpose-built
/// stack-fallback arena; null means the general allocator.
@@ -2204,7 +2178,7 @@ pub const Options = struct {
pub const Haptic = enum { none, exec, look };
-/// Zero-sized off macOS, the way PdfSlot is off -Dmupdf: no other shell reads
+/// Zero-sized off macOS: no other shell reads
/// the field, so no other shell carries it.
const HapticSlot = if (platform == .macos) Haptic else void;
@@ -2241,7 +2215,7 @@ const FakeTtyQuery = struct {
};
fn bootAndTearDown(gpa: std.mem.Allocator) !void {
- const p = try Pardes.init(gpa, .{ .cols = 56, .rows = 14, .tty_only = true, .frame_allocator = gpa, .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 56, .rows = 14, .tty_only = true, .frame_allocator = gpa, .image_allocator = gpa, .tree_sitter_allocator = gpa });
p.deinit();
}
diff --git a/src/Effect.zig b/src/Effect.zig
index f5ee7ff9..2bcf82f5 100644
--- a/src/Effect.zig
+++ b/src/Effect.zig
@@ -226,8 +226,8 @@ pub fn perform(p: *Pardes, e: Effect) void {
}
},
.watch => |w| if (v.watch_file) |f| {
- // What a watch is about: a real file, or a PDF.
- const path: []const u8 = if (p.panes[w.pane]) |pane| (if (pane.file) |file| (if (file.output == null) file.path else "") else pane.pdfPath() orelse "") else "";
+ // What a watch is about: a real file, or a kind's (a PDF's).
+ const path: []const u8 = if (p.panes[w.pane]) |pane| (if (pane.file) |file| (if (file.output == null) file.path else "") else if (pane.addon) |k| k.path else "") else "";
f(p.host.ctx, w.pane, path, w.on, w.mode);
} else {
p.fallback.watched[w.pane] = w.on;
diff --git a/src/Event.zig b/src/Event.zig
index bf27ff69..63dcb5f2 100644
--- a/src/Event.zig
+++ b/src/Event.zig
@@ -4,7 +4,6 @@ const config = @import("config.zig");
const selection_pipe = @import("selection_pipe.zig");
const Stream = @import("Stream.zig");
const Layer = @import("Layer.zig");
-const pdf_enabled = @import("panes.zig").Pdf.enabled;
const RowMetrics = Layer.Metrics;
const TagHit = Layer.TagHit;
@@ -89,12 +88,12 @@ pub fn hit(key: Key, binding: []const config.Chord) bool {
pub const sel_slot = @backingInt(config.select_button);
-/// Pixel dimensions are meaningful only to the native PDF placement path.
-/// Keep resize events layout-only when that path is not part of the build.
-pub const CellPixels = if (pdf_enabled) struct {
+/// A cell's pixels, as the frontend draws it: what a kind's pictures and a
+/// terminal's kitty images are laid out at.
+pub const CellPixels = struct {
w: u16 = 8,
h: u16 = 16,
-} else struct {};
+};
pub const Event = union(enum) {
key: Key,
@@ -125,11 +124,6 @@ pub const Event = union(enum) {
search: Stream.Batch,
paste: []const u8,
command: []const u8,
- /// Native shells may preserve sub-cell wheel distance in physical pixels.
- /// TTY button events still enter through the ordinary mouse path.
- /// `glide`: a wheel's notch, which the strip glides; a touchpad's
- /// fraction is followed as it comes.
- pdf_scroll: struct { pane: u8, delta_pixels: f32, glide: bool = true },
/// The host pointer left the drawable area. Unlike an out-of-range motion,
/// this must not clamp onto and preview the final grid cell.
pointer_leave,
diff --git a/src/Jump.zig b/src/Jump.zig
index 0d82d104..10014e9e 100644
--- a/src/Jump.zig
+++ b/src/Jump.zig
@@ -41,10 +41,43 @@ pub const Loc = struct {
col: u32,
/// The file it is in (Wyhash of the path), 0 for a pane with none.
path_hash: u64 = 0,
- /// A PDF's place: `line` its page (one-based), `col` how far down it
- /// (pdf_view.Place.at, a fraction of the page in 2^-32).
- pdf: bool = false,
+ /// A kind's pane's place, its `where` (a PDF's `12:0.330000`), with
+ /// `line` its first number.
+ place: Kind.Buf(32) = .{},
};
+const Kind = @import("Kind.zig");
+
+/// A kind's pane's place now, its `where`.
+fn kindPlace(pane: *Pane) ?Kind.Buf(32) {
+ const slot = pane.addon orelse return null;
+ if (!slot.live) return null;
+ var buf: [32]u8 = undefined;
+ const w = Kind.placeOf(slot, &buf);
+ if (w.len == 0) return null;
+ var out: Kind.Buf(32) = .{};
+ out.set(w);
+ return out;
+}
+
+/// A place's first number: a kind's line (a PDF's page).
+/// A kind's place `L:F S` as where it is (L + F, in lines) and its
+/// window's height (S lines); null for one without both.
+fn spanOf(text: []const u8) ?[2]f64 {
+ const sp = std.mem.lastIndexOfScalar(u8, text, ' ') orelse return null;
+ const colon = std.mem.indexOfScalar(u8, text[0..sp], ':') orelse return null;
+ const line = std.fmt.parseFloat(f64, text[0..colon]) catch return null;
+ const frac = std.fmt.parseFloat(f64, text[colon + 1 .. sp]) catch return null;
+ return .{ line + frac, std.fmt.parseFloat(f64, text[sp + 1 ..]) catch return null };
+}
+
+pub fn firstNumber(text: []const u8) u32 {
+ var n: u32 = 0;
+ for (text) |ch| {
+ if (ch < '0' or ch > '9') break;
+ n = n *| 10 +| (ch - '0');
+ }
+ return n;
+}
/// A session for the side-button jump test: four panes of 100 lines in one
/// column, A (pane 0) and B each on a file of its own, C on A's file, and O
@@ -128,22 +161,22 @@ const JumpsTest = struct {
}
};
-/// The file a jump in `pane` is in: a text's, a PDF's.
+/// The file a jump in `pane` is in: a text's, a kind's (a PDF's).
fn jumpPath(pane: *const Pane) ?[]const u8 {
if (Pardes.recentDot(pane)) |d| return d.path;
- return pane.pdfPath();
+ if (pane.addon) |k| if (k.path.len > 0) return k.path;
+ return null;
}
fn samePlace(p: *const Pardes, a: Loc, b: Loc) bool {
if (a.pane != b.pane or a.serial != b.serial) return false;
- // A PDF's places by where they stand on its strip, as a text's by
- // lines: within a body of each other, one visit.
- if (a.pdf and b.pdf) if (p.panes[b.pane]) |pane| {
- const view = panes.Pdf.paneViewport(p, pane) orelse return a.line == b.line;
- const ya = panes.Pdf.placeY(pane, .{ .page = a.line - 1, .at = a.col }) orelse return a.line == b.line;
- const yb = panes.Pdf.placeY(pane, .{ .page = b.line - 1, .at = b.col }) orelse return a.line == b.line;
- return @abs(ya - yb) <= @as(f64, @floatFromInt(view.pixel_h));
- };
+ // A kind's places within a window of each other (`where`'s `L:F S`:
+ // the window S lines), else by their first numbers (a page or the
+ // next), one visit.
+ if (a.place.len > 0 and b.place.len > 0) {
+ if (spanOf(a.place.slice())) |x| if (spanOf(b.place.slice())) |y| return @abs(x[0] - y[0]) <= @max(x[1], y[1]);
+ return @max(a.line, b.line) - @min(a.line, b.line) <= 1;
+ }
if (a.line == 0 or b.line == 0) return true;
const body = @max(1, p.view().rects[b.pane].h -| BOX_H);
return @max(a.line, b.line) - @min(a.line, b.line) <= body;
@@ -191,14 +224,14 @@ pub fn trackJump(p: *Pardes) void {
if (pane.query) |q| if (!q.frozen) return;
const force = v.jumps.force;
v.jumps.force = false;
- const pdf_place = panes.Pdf.place(pane);
+ const place = kindPlace(pane);
const now: Loc = .{
.pane = @intCast(v.active),
.serial = pane.serial,
- .line = if (pdf_place) |at| @intCast(at.page + 1) else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_row) + 1) else 0,
- .col = if (pdf_place) |at| at.at else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0,
+ .line = if (place) |at| firstNumber(at.slice()) else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_row) + 1) else 0,
+ .col = if (place != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0,
.path_hash = if (jumpPath(pane)) |path| std.hash.Wyhash.hash(0, path) else 0,
- .pdf = pdf_place != null,
+ .place = place orelse .{},
};
if (!force and v.jumps.n > 0 and samePlace(p, v.jumps.list[v.jumps.cur], now)) {
v.jumps.list[v.jumps.cur] = now; // same visit; the entry IS where you are
@@ -289,11 +322,12 @@ pub fn jumpBy(p: *Pardes, delta: i32) void {
}
const e = found.?;
const from = v.active;
- look.reopenAt(p, from, e.path, .{ .line = @max(1, j.line), .col = if (j.pdf) 0 else @max(1, j.col) });
+ look.reopenAt(p, from, e.path, .{ .line = @max(1, j.line), .col = if (j.place.len > 0) 0 else @max(1, j.col) });
const opened = p.panes[v.active] orelse return;
const opened_path = jumpPath(opened) orelse return;
if (!std.mem.eql(u8, opened_path, e.path)) return; // it did not open
- if (j.pdf) panes.Pdf.landAt(p, opened, .{ .page = j.line -| 1, .at = j.col });
+ var said: Kind.Buf(160) = .{};
+ if (j.place.len > 0) _ = Kind.address(p, v.active, j.place.slice(), &said);
// Every entry of that file is the reopened pane from here on, so
// a step onto another of them moves in it rather than reopening.
for (v.jumps.list[0..p.view().jumps.n]) |*k| if (k.serial == 0 and k.path_hash == j.path_hash) {
@@ -308,9 +342,10 @@ pub fn jumpBy(p: *Pardes, delta: i32) void {
if (p.panes[v.active]) |source| look.clearNavigationSelection(p, source);
if (v.active != j.pane) look.clearNavigationSelection(p, pane);
v.jumps.cur = next;
- if (pane.pdfPath() != null) {
+ if (pane.addon != null) {
look.focusPaneLine(p, j.pane, .{ .line = 0, .col = 0 }, .keep);
- panes.Pdf.landAt(p, pane, .{ .page = j.line -| 1, .at = if (j.pdf) j.col else 0 });
+ var said: Kind.Buf(160) = .{};
+ if (j.place.len > 0) _ = Kind.address(p, j.pane, j.place.slice(), &said);
return;
}
look.focusPaneLine(p, j.pane, .{ .line = j.line, .col = j.col }, .center);
diff --git a/src/Output.zig b/src/Output.zig
index 006ab7bd..20d672d2 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -27,7 +27,9 @@ pub const Origin = union(enum) {
query: lsp.Kind,
search,
errors,
- pdf_links,
+ /// A kind's list (`pa_api.text`: a +PdfSections, a +Links), named its
+ /// argument: rows of places n/N walk, a Look of one its kind's.
+ kind,
/// The panes a refusal (Exit, Restore, Del, Delcol, get) is over, kept
/// in +Unsaved rather than a notice that goes.
unsaved,
@@ -254,7 +256,7 @@ pub fn traits(o: Origin) Traits {
// rows are `location text`, so n/N walk them
.search => .{ .name = config.search_buffer, .steps = true, .locations = true },
.errors => .{ .name = config.errors_buffer, .doc = true },
- .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true },
+ .kind => .{ .name = "", .steps = true, .locations = true },
.unsaved => .{ .name = config.unsaved_buffer, .doc = true },
.preview => .{ .name = config.preview_buffer, .doc = true },
// Named for its directory, not a `+` name in it.
@@ -291,7 +293,7 @@ pub fn traits(o: Origin) Traits {
pub fn usesLocationsConfig(from: Origin) bool {
const tr = traits(from);
- return tr.steps and !tr.commands and from != .pdf_links and
+ return tr.steps and !tr.commands and from != .kind and
!std.meta.eql(from, Origin{ .query = .completion }) and
!std.meta.eql(from, Origin{ .query = .callstack });
}
@@ -358,7 +360,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u
=> {},
else => return anchor,
},
- .errors, .pdf_links, .unsaved, .dir, .preview => return anchor,
+ .errors, .kind, .unsaved, .dir, .preview => return anchor,
}
if (content.len == 0) return anchor;
const trailing_newline = content[content.len - 1] == '\n';
@@ -437,7 +439,7 @@ pub fn nextResult(content: []const u8, rows: []const locations.Row, path: []cons
pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, content: []u8) !*Pane {
const path = try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{
- std.mem.trimEnd(u8, dir, "/"), traits(from).name,
+ std.mem.trimEnd(u8, dir, "/"), if (from == .kind) arg else traits(from).name,
});
errdefer p.gpa.free(path);
var out: State = .{ .from = from };
@@ -630,8 +632,8 @@ pub fn openJumps(p: *Pardes, id: usize) !void {
// A closed file's entry: marked, and a look at it opens it again.
if (j.serial == 0) {
const e = p.recentByHash(j.path_hash) orelse continue;
- // A PDF's `col` is how far down its page, no Look's column.
- if (j.pdf) {
+ // A kind's place has no Look's column.
+ if (j.place.len > 0) {
try out.writer.print("{s}:{d} (closed)\n", .{ e.path, @max(1, j.line) });
continue;
}
@@ -640,25 +642,23 @@ pub fn openJumps(p: *Pardes, id: usize) !void {
}
const jp = p.panes[j.pane] orelse continue;
var idbuf: [16]u8 = undefined;
- const pdf_path: ?[]const u8 = if (comptime pardes.pdf_enabled) jp.pdfPath() else null;
- const has_path = if (jp.file) |f| f.output == null else pdf_path != null;
+ const kind_path: ?[]const u8 = if (jp.addon) |k| (if (k.path.len > 0) k.path else null) else null;
+ const has_path = if (jp.file) |f| f.output == null else kind_path != null;
const loc: []const u8 = if (has_path)
- (if (jp.file) |f| f.path else pdf_path.?)
+ (if (jp.file) |f| f.path else kind_path.?)
else
std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{jp.serial}) catch unreachable;
const what: []const u8 = if (jp.file) |f|
std.mem.trim(u8, modal.lineSlice(f.content, j.line -| 1), " \t\r")
else if (jp.addon) |k|
k.path
- else if (pdf_path) |path|
- path
else
jp.cwdSlice();
var cut = @min(what.len, 120);
while (cut > 0 and cut < what.len and what[cut] & 0xc0 == 0x80) cut -= 1;
if (j.line == 0)
try out.writer.print("{s} {s}\n", .{ loc, what[0..cut] })
- else if (j.pdf)
+ else if (j.place.len > 0)
try out.writer.print("{s}:{d} {s}\n", .{ loc, j.line, what[0..cut] })
else
try out.writer.print("{s}:{d}:{d} {s}\n", .{ loc, j.line, j.col, what[0..cut] });
diff --git a/src/Store.zig b/src/Store.zig
index 64a8a7be..afe07742 100644
--- a/src/Store.zig
+++ b/src/Store.zig
@@ -106,7 +106,7 @@ pub fn keep(s: *Store, p: *Pardes, id: usize) ?Kept {
gpa.free(owned);
return null;
}
- const what: []const u8 = if (pane.file) |f| f.path else if (pane.pdfPath()) |pdf| pdf else if (pane.addon) |k| k.path else if (pane.command) |c| c else pane.cwdSlice();
+ const what: []const u8 = if (pane.file) |f| f.path else if (pane.addon) |k| k.path else if (pane.command) |c| c else pane.cwdSlice();
var name = gpa.alloc(u8, @min(what.len, 4096)) catch {
gpa.free(owned);
return null;
diff --git a/src/body_layer.zig b/src/body_layer.zig
index dc5e51bf..56c4bc79 100644
--- a/src/body_layer.zig
+++ b/src/body_layer.zig
@@ -15,7 +15,6 @@ const Color = @import("surface.zig").Color;
const CellStyle = @import("surface.zig").CellStyle;
const Cell = @import("surface.zig").Cell;
const Surface = @import("surface.zig").Surface;
-const pdf_enabled = panes.Pdf.enabled;
const Pane = panes.Pane;
const BOX_H = pardes.BOX_H;
const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
@@ -29,7 +28,7 @@ const Layer = @import("Layer.zig");
// ---- drawing a pane body into the surface ----
fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void {
- const body = bodyText(p, p.scratch.allocator(), pane) catch return;
+ const body = bodyText(p.scratch.allocator(), pane) catch return;
const raw = pane.body.mode == .tty;
const tx = r.x + config.GUTTER;
const width = r.w -| config.GUTTER;
@@ -248,7 +247,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
};
const tz_body = tracy.zone(@src(), "bodyText");
const probe_text = pardes.FrameStats.nowNs();
- const body = try bodyText(p, arena, pane);
+ const body = try bodyText(arena, pane);
p.frames.zone(.body_text, probe_text);
tz_body.end();
// A select sweep begun on the tag and dragged into the body marks the
@@ -475,21 +474,12 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
};
}
-pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
+pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
if (pane.addon != null) {
const buf = try arena.alloc(u8, pane.rows -| 1);
@memset(buf, '\n');
return buf;
}
- if (pane.hasPdf()) {
- if (comptime pdf_enabled) return panes.Pdf.visibleText(
- pane.pdf.?,
- p.pdf_gpa,
- arena,
- pane.rows -| BOX_H,
- );
- unreachable;
- }
if (pane.file) |*f| return panes.File.bodyText(arena, pane, f);
return panes.terminal.bodyText(arena, pane);
}
diff --git a/src/builtins.zig b/src/builtins.zig
index 68730166..e5c7753d 100644
--- a/src/builtins.zig
+++ b/src/builtins.zig
@@ -59,7 +59,6 @@ pub fn viewPlatform(p: *const Pardes) []const u8 {
/// The kinds of pane a builtin may be for alone (registry.needs).
pub const PaneKind = enum {
terminal,
- pdf,
image,
/// An image pane, or a terminal, whose program's kitty graphics are
/// pictures too.
@@ -72,7 +71,6 @@ pub const PaneKind = enum {
pub fn has(kind: PaneKind, pane: *const panes.Pane) bool {
return switch (kind) {
.terminal => pane.isTerminal(),
- .pdf => pane.hasPdf(),
.image => pane.addon != null,
.picture => pane.addon != null or pane.isTerminal(),
.program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager),
@@ -84,7 +82,6 @@ pub const PaneKind = enum {
pub fn noun(kind: PaneKind) []const u8 {
return switch (kind) {
.terminal => "a terminal",
- .pdf => "a PDF",
.image => "an image",
.picture => "an image or a terminal",
.program_colors => "a terminal or a +Pager",
@@ -946,49 +943,6 @@ fn stateArg(c: Ctx, comptime T: type, comptime builtin_word: []const u8, comptim
const OnOff = enum { on, off };
-/// Fit the PDF page to the pane by width or by height, flipping between them
-/// (or to the one named, `width|height`).
-pub const PdfFit = struct {
- pub const needs: PaneKind = .pdf;
- pub const enabled = pardes.pdf_enabled;
- pub const takes_arg = true;
- pub fn run(c: Ctx) void {
- const state = c.pane.pdf orelse return;
- if (c.arg != null) {
- const want = stateArg(c, panes.Pdf.FitMode, "PdfFit", "width or height") orelse return;
- if (want == state.fit) return;
- }
- panes.Pdf.toggleFit(c.pane);
- }
-};
-
-/// Tint the PDF page to the theme, or show it as printed, stepping through
-/// them (or to the one named, `disabled|filtered|full`).
-pub const PdfTint = struct {
- pub const needs: PaneKind = .pdf;
- pub const enabled = pardes.pdf_enabled;
- pub const takes_arg = true;
- pub fn run(c: Ctx) void {
- const state = c.pane.pdf orelse return;
- if (c.arg != null) {
- const want = stateArg(c, panes.Pdf.TintMode, "PdfTint", "disabled, filtered or full") orelse return;
- while (state.tint != want) panes.Pdf.toggleTint(c.pane);
- return;
- }
- panes.Pdf.toggleTint(c.pane);
- }
-};
-
-/// List the PDF's sections in a pane, each a place to go.
-pub const PdfSections = struct {
- pub const needs: PaneKind = .pdf;
- pub const output: OutputTraits = .{ .name = config.pdf_sections_buffer, .steps = true, .locations = true };
- pub const enabled = pardes.pdf_enabled;
- pub fn run(c: Ctx) void {
- panes.Pdf.openSections(c.p, c.id);
- }
-};
-
/// Addons, the libraries that bring kinds of pane: `Addon load <path>`,
/// `Addon unload <name>`, `Addon reload <name>`; bare, the kinds here.
pub const Addon = struct {
@@ -1211,11 +1165,14 @@ pub const Zerox = struct {
pub const Save = struct {
pub const takes_arg = true;
pub fn run(c: Ctx) void {
- // A PDF or an image shows a file it does not hold as text: there
- // is nothing of its own to write, bare or to a path. Said, never a
- // silent success.
- if (c.pane.file == null and !c.pane.isTerminal())
- return c.p.reportFailure(c.id, if (c.pane.hasPdf()) "Save: a PDF pane has no text to save" else "Save: an image pane has no text to save");
+ // A kind's pane (an image, a PDF) shows a file it does not hold as
+ // text: there is nothing of its own to write, bare or to a path.
+ // Said, never a silent success.
+ if (c.pane.file == null and !c.pane.isTerminal()) {
+ const kind = if (c.pane.addon) |k| k.nameOf() else "";
+ var said: [64]u8 = undefined;
+ return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Save: a{s} {s} pane has no text to save", .{ if (kind.len > 0 and std.mem.indexOfScalar(u8, "aeiou", kind[0]) != null) "n" else "", kind }) catch "Save: no text to save");
+ }
// A directory's listing is no file to write, bare or to a path, as
// acme's Put does nothing in a directory window.
if (c.pane.file) |file| if (file.listing != null) {
diff --git a/src/colors.zig b/src/colors.zig
index de20cf9b..7bac64ea 100644
--- a/src/colors.zig
+++ b/src/colors.zig
@@ -7,7 +7,6 @@ const std = @import("std");
const Color = @import("surface.zig").Color;
const FontRole = @import("surface.zig").FontRole;
const config = @import("config.zig");
-const pdf_enabled = panes.Pdf.enabled;
const platform = pardes.platform;
const MAX_PANES = pardes.MAX_PANES;
const BOX_H = pardes.BOX_H;
@@ -731,7 +730,6 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool {
p.custom_theme = parsed;
if (old) |theme_value| p.gpa.free(theme_value.name);
_ = p.theme_file_loaded.set(request.path);
- invalidateThemeDependentRasters(p);
_ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept });
p.sync();
return true;
@@ -741,13 +739,6 @@ pub fn finishThemeInitialization(p: *Pardes) void {
p.chrome = ChromeTheme.fromTheme(p.theme());
}
-fn invalidateThemeDependentRasters(p: *Pardes) void {
- if (comptime pdf_enabled) for (p.panes) |slot| {
- const pane = slot orelse continue;
- const pv = pane.pdf orelse continue;
- if (pv.tint != .disabled) pv.invalidateAllRasters();
- };
-}
/// Themes near `name`, a line of them, for a Theme given a name there is
/// none of (all of them, Themes, are too many for a refused write): every
@@ -841,7 +832,6 @@ pub fn setThemeIndex(p: *Pardes, index: usize) void {
p.emit(.{ .theme_file = .{ .generation = generation, .on = false } });
}
p.settings.theme = @intCast(index);
- invalidateThemeDependentRasters(p);
}
test "a theme file that cannot be read is named in the failure" {
diff --git a/src/config.zig b/src/config.zig
index f9fd336f..17a7305a 100644
--- a/src/config.zig
+++ b/src/config.zig
@@ -17,7 +17,7 @@ pub const Chord = struct {
};
// Leader paths apply wherever normal mode reads keys: a body's, a tag's
-// (column and workspace tags too) and a PDF's, never a raw terminal's
+// (column and workspace tags too) and a kind's pane's, never a raw terminal's
// (normal.zig takes `.leader` for every target).
pub const leader: []const Chord = &.{.{ .cp = ' ' }};
@@ -164,11 +164,6 @@ pub const leader_path = paths: {
table.set(.Adopt, null);
table.set(.Upgrade, "sU");
}
- if (pardes.pdf_enabled) {
- table.set(.PdfTint, "ti");
- table.set(.PdfSections, "ts");
- table.set(.PdfFit, "tz");
- }
for (std.enums.values(Builtin)) |b| if (table.get(b)) |p| {
if (std.mem.eql(u8, p, undecided)) @compileError("builtin has no leader path decided: " ++ @tagName(b));
};
@@ -280,7 +275,6 @@ pub const child_term_program = "pardes";
pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit";
pub const pane_builtins_str = "Term Collapse Del";
-pub const pdf_pane_builtins_str = "Term PdfSections PdfTint PdfFit Collapse Del";
pub const file_pane_builtins_str = "Save Term Collapse Del";
/// After a file's, on one a language server speaks for.
pub const lsp_pane_builtins_str = "Def Refs";
@@ -497,9 +491,7 @@ pub const preview_buffer = "+Preview";
pub const unsaved_buffer = "+Unsaved";
pub const themes_buffer = "+Themes";
pub const fonts_buffer = "+Fonts";
-pub const pdf_sections_buffer = "+PdfSections";
pub const diff_buffer = "+Diff";
-pub const pdf_links_buffer = "+Links";
pub const hover_buffer = "+Hover";
pub const lsp_buffer = "+Lsp";
pub const changelog_buffer = "+Changelog";
@@ -1496,13 +1488,33 @@ const doc_typ = struct {
/// The other build's builtins (docs/typ/builtins-*.json), so the docs
/// may name a window-only word in a terminal build's test, and back.
var other_build: []const u8 = "";
+ /// The shipped addons' sources (addons/*/*.c): their words are named
+ /// in the docs too, `PA_WORD("PdfFit", ...`.
+ var addon_sources: []const u8 = "";
+
+ fn loadAddons(gpa: std.mem.Allocator) !void {
+ const io = std.testing.io;
+ var root = try std.Io.Dir.cwd().openDir(io, @import("doc_typ").addons, .{ .iterate = true });
+ defer root.close(io);
+ var kinds = root.iterate();
+ while (try kinds.next(io)) |k| if (k.kind == .directory) {
+ var sub = try root.openDir(io, k.name, .{ .iterate = true });
+ defer sub.close(io);
+ var files = sub.iterate();
+ while (try files.next(io)) |f| if (std.mem.endsWith(u8, f.name, ".c")) {
+ addon_sources = try std.mem.concat(gpa, u8, &.{ addon_sources, try sub.readFileAlloc(io, f.name, gpa, .limited(1 << 20)) });
+ };
+ };
+ }
fn word(w: []const u8) bool {
const name = w[0 .. std.mem.indexOfScalar(u8, w, '+') orelse w.len];
if (std.meta.stringToEnum(Builtin, name) != null) return true;
var buf: [96]u8 = undefined;
const needle = std.fmt.bufPrint(&buf, "{{\"name\": \"{s}\",", .{name}) catch return false;
- return std.mem.indexOf(u8, other_build, needle) != null;
+ if (std.mem.indexOf(u8, other_build, needle) != null) return true;
+ const addon = std.fmt.bufPrint(&buf, "PA_WORD(\"{s}\",", .{name}) catch return false;
+ return std.mem.indexOf(u8, addon_sources, addon) != null;
}
fn chord(tok: []const u8) ?Chord {
@@ -1585,9 +1597,18 @@ const doc_typ = struct {
if (w.end > 0) w.writeByte(' ') catch return false;
w.writeAll(x[0 .. std.mem.indexOfScalar(u8, x, '+') orelse x.len]) catch return false;
}
- const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, diff_pane_builtins_str, pager_pane_builtins_str, pager_diff_pane_builtins_str, diff_view_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str };
+ const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, file_pane_builtins_str, diff_pane_builtins_str, pager_pane_builtins_str, pager_diff_pane_builtins_str, diff_view_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str };
for (tags) |d| if (std.mem.eql(u8, d, w.buffered())) return true;
- return false;
+ // A kind's pane's: Term, its addon's words, Collapse Del (Kind.zig).
+ const shown = w.buffered();
+ if (!std.mem.startsWith(u8, shown, "Term ") or !std.mem.endsWith(u8, shown, " Collapse Del")) return false;
+ var mid = std.mem.tokenizeScalar(u8, shown["Term ".len .. shown.len - " Collapse Del".len], ' ');
+ while (mid.next()) |x| {
+ var buf: [96]u8 = undefined;
+ const addon = std.fmt.bufPrint(&buf, "PA_WORD(\"{s}\",", .{x}) catch return false;
+ if (std.mem.indexOf(u8, addon_sources, addon) == null) return false;
+ }
+ return true;
}
};
@@ -1601,6 +1622,8 @@ test "docs/typ names only words, keys and default tags that exist" {
var found: [3]std.ArrayList([]const u8) = @splat(.empty);
// The arena's: gone with this test, so no later test reads it.
defer doc_typ.other_build = "";
+ defer doc_typ.addon_sources = "";
+ try doc_typ.loadAddons(gpa);
for ([_][]const u8{ "builtins-tui.json", "builtins-gui.json" }) |f| {
const text = dir.readFileAlloc(io, f, gpa, .limited(1 << 20)) catch continue;
doc_typ.other_build = try std.mem.concat(gpa, u8, &.{ doc_typ.other_build, text });
@@ -1701,6 +1724,8 @@ test "the tutor names only words, keys, paths and default tags that exist" {
defer arena.deinit();
const gpa = arena.allocator();
const tutor = @embedFile("tutor.txt");
+ defer doc_typ.addon_sources = "";
+ try doc_typ.loadAddons(gpa);
var found: std.ArrayList([]const u8) = .empty;
try doc_tutor.words(gpa, tutor, &found);
diff --git a/src/draw.zig b/src/draw.zig
index c97e2a6c..8538c6a6 100644
--- a/src/draw.zig
+++ b/src/draw.zig
@@ -28,7 +28,6 @@ const Text = panes.Text;
const Rect = layout.Rect;
const Region = @import("surface.zig").Region;
const TagKind = @import("Layer.zig").Kind;
-const pdf_enabled = panes.Pdf.enabled;
const wordBoundsAtCol = tagline.wordBoundsAtCol;
const BOX_H = pardes.BOX_H;
const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
@@ -67,17 +66,13 @@ pub fn place(p: *Pardes, s: *Surface) void {
const doc: u64 = if (pane.file) |f| std.hash.Wyhash.hash(if (f.output != null) f.revision else 0, f.path) else 0;
s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } });
var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } };
- // An image's rail has no thumb; a native PDF's is measured as its
- // pages are placed (Pdf.draw); every other pane's is here.
+ // A kind's rail is its paint's (drawPane); every other pane's is
+ // here.
if (pane.addon == null and body_h > 0) {
const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{
.total = panes.File.nlines(p.gpa, f),
.offset = f.scroll,
.len = pane.rows,
- } else if (pane.pdfPage()) |page| .{
- .total = if (comptime pdf_enabled) pane.pdf.?.page_count else 1,
- .offset = page,
- .len = 1,
} else blk: {
const gsb = panes.terminal.scrollbar(pane);
break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len };
@@ -182,14 +177,6 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface {
s.rows = v.screen_h;
s.cursor = null;
s.pointer_shape = .arrow;
- if (comptime pdf_enabled) if (p.pdf_hover_preview) |preview| {
- if (preview.probe.link != null and preview.pane < p.panes.len) {
- if (p.panes[preview.pane]) |pane| {
- if (pane.serial == preview.serial and panes.Pdf.paneNativeReady(p, pane))
- s.pointer_shape = .link;
- }
- }
- };
// A look-hover preview means the pointed word is a real Look or Exec
// operand: the same plumbing a click would act on. Hosts that model
// the pointer per-text (the macOS I-beam) read this as "target" and
@@ -319,9 +306,9 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface {
if (at.file) |*f| {
sb_off = f.scroll;
sb_total = panes.File.nlines(p.gpa, f);
- } else if (at.pdfPage()) |page| {
- sb_off = page;
- sb_total = if (comptime pdf_enabled) at.pdf.?.page_count else 0;
+ } else if (at.addon != null) {
+ sb_off = 0;
+ sb_total = 0;
} else {
const sb = panes.terminal.scrollbar(at);
sb_off = sb.offset;
@@ -435,8 +422,6 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r:
if (pane.collapsed) return;
const rail = s.region(.rail, id).?;
- if (comptime pdf_enabled)
- if (pane.hasPdf() and panes.Pdf.draw(p, s, pane, r, id, tx, tw, rail)) return;
if (pane.addon != null) {
// Below the notice chips: a picture is drawn after the cells (the
@@ -445,11 +430,21 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r:
const shown = pane.notices.span();
const body_h = (r.h -| pane.tag_rows) -| shown;
pardes.Kind.draw(p, s, arena, pane, id, tx, body_y + shown, tw, body_h);
- // thumbless, but the same one column as the real scrollbar below —
- // that is the whole point of drawing it, and like that one it runs
- // past the notice bands so the gutter has no notch in it
+ // The same one column as the real scrollbar below, running past
+ // the notice bands so the gutter has no notch in it; its thumb
+ // where this frame's paint said its window is in its whole (a
+ // PDF's strip), none for a kind that said nothing (an image).
s.fill(rail.rect.x, rail.rect.y, 1, rail.rect.h, .{ .bg = .{ .rgb = chrome.scroll_track } });
s.fill(rail.rect.x + 1, rail.rect.y, 1, rail.rect.h, .{ .bg = pane_bg });
+ const k = pane.addon.?;
+ if (k.thumb_span > 0) {
+ const track: f32 = @floatFromInt(rail.rect.h);
+ rail.thumb_y = @intFromFloat(@min(track - 1, @floor(k.thumb_at * track)));
+ rail.thumb_h = @intFromFloat(@min(track - @as(f32, @floatFromInt(rail.thumb_y)), @max(1, k.thumb_span * track)));
+ rail.thumb_at = k.thumb_at;
+ rail.thumb_span = k.thumb_span;
+ s.fill(rail.rect.x, rail.rect.y + rail.thumb_y, 1, rail.thumb_h, .{ .bg = .{ .rgb = chrome.scroll_thumb } });
+ }
return;
}
@@ -566,8 +561,6 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct {
if (k.path.len == 0) return null;
start = std.mem.lastIndexOf(u8, tag[0..@min(prefix_len, tag.len)], k.path) orelse return null;
break :blk k.path;
- } else if (comptime pdf_enabled) blk: {
- break :blk if (pane.pdf) |state| state.path else return null;
} else return null;
const basename = if (std.mem.lastIndexOfScalar(u8, name, '/')) |slash| slash + 1 else 0;
if (basename == name.len) return null;
diff --git a/src/dump.zig b/src/dump.zig
index 38fdbb7d..1d4ee2c2 100644
--- a/src/dump.zig
+++ b/src/dump.zig
@@ -10,7 +10,6 @@ const ctlfs = @import("ninep/tree.zig");
const exec = @import("exec.zig");
const colors = @import("colors.zig");
const config = @import("config.zig");
-const pdf_enabled = pardes.pdf_enabled;
const platform = pardes.platform;
const isolated = pardes.isolated;
const MAX_PANES = pardes.MAX_PANES;
@@ -93,7 +92,7 @@ pub var terminal_gpa: ?std.mem.Allocator = null;
//
// Loading is two halves. `load` makes the core the dump was and nothing
// else (a replica joining a session takes that, phase 5); `revivePane` and
-// `reviveSession` give it to this host: new shells, watches, PDFs opened.
+// `reviveSession` give it to this host: new shells, watches, kinds' panes opened.
/// A session's dump: its core, everything it is but what is the host's,
/// the frame's or worked out again (`replica` in each type, src/walk.zig),
@@ -298,7 +297,7 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes:
p.fs.deinit(gpa);
gpa.destroy(p);
}
- l.allocs = .{ .image = p.image_gpa, .pdf = p.pdf_gpa, .terminal = terminal_gpa };
+ l.allocs = .{ .image = p.image_gpa, .terminal = terminal_gpa };
try l.into(Pardes, p);
const read = l.shared.items.len;
const mounts = try l.get([]const filesystem.Mount);
@@ -372,7 +371,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*
p.fs.deinit(gpa);
gpa.destroy(p);
}
- l.allocs = .{ .image = p.image_gpa, .pdf = p.pdf_gpa, .terminal = terminal_gpa };
+ l.allocs = .{ .image = p.image_gpa, .terminal = terminal_gpa };
try l.into(Pardes, core_at, p);
if (try walk.Get.member(core_at, "views") == null) {
// From before `Pardes.views`: the live view's share is the core's
@@ -441,7 +440,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*
/// A pane that is none of its kinds (a terminal kept slim, or one another
/// build's dump could not give): a terminal, a new emulator for its shell.
fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void {
- if (pane.terminal != null or pane.file != null or pane.addon != null or pane.hasPdf()) return;
+ if (pane.terminal != null or pane.file != null or pane.addon != null or pane.pdf != null) return;
const fresh = try pardes.panes.terminal.create(p.gpa, @max(1, pane.cols), @max(1, pane.rows));
pane.terminal = fresh.terminal;
fresh.terminal = null;
@@ -588,7 +587,8 @@ fn reviveSession(p: *Pardes, previous: ?*Pardes, resumed: bool) !void {
/// A loaded pane given to this host: a terminal a new shell in its old
/// one's directory under its history, a file watched again (one changed on
/// disk since comes back as it is now, one unsaved is marked changed), a
-/// PDF opened again.
+/// kind's pane opened again (a PDF a build before the pdf addon dumped, as
+/// the addon's).
fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool) void {
if (pane.addon) |slot| return reviveSlot(p, id, slot);
if (pane.terminal != null) {
@@ -606,13 +606,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool
p.emitSpawn(id, pane.serial, pane.cwdSlice());
return;
}
- if (comptime pdf_enabled) if (pane.pdf != null) {
- pardes.panes.Pdf.reopen(p, pane) catch |err| {
- p.reportError(id, "Restore", err);
- p.removePane(id, null) catch {};
- };
- return;
- };
+ if (pane.pdf) |old| return revivePdf(p, id, pane, old);
const f = if (pane.file) |*file| file else return;
if (f.output != null or filesystem.localPath(f.path) == null) return;
p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
@@ -667,7 +661,7 @@ pub fn savePane(gpa: std.mem.Allocator, pane: *pardes.panes.Pane, slim: bool) ![
pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane {
var l = try walk.Load(&.{pardes.panes.Pane}).init(p.gpa, bytes);
defer l.deinit();
- l.allocs = .{ .image = p.image_gpa, .pdf = p.pdf_gpa, .terminal = pardes.panes.terminal.emulatorGpa(p.gpa) };
+ l.allocs = .{ .image = p.image_gpa, .terminal = pardes.panes.terminal.emulatorGpa(p.gpa) };
const pane = try p.gpa.create(pardes.panes.Pane);
errdefer {
l.rollback();
@@ -925,11 +919,17 @@ const SlotRecord = struct {
record: ?[]const u8 = null,
values: []const u8 = "",
live: bool = false,
+ /// What decides its next calls (Kind.step): a replica joining keeps
+ /// them, its Shadow calling where the authority's kind does.
+ next_tick: u64 = 0,
+ view: u64 = 0,
+ focused: bool = false,
+ told: []const u8 = "",
};
pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) !void {
var place: [32]u8 = undefined;
- var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live };
+ var r: SlotRecord = .{ .name = s.nameOf(), .version = s.version, .path = s.path, .art = s.art, .record = s.record, .where = s.where_text.slice(), .values = s.values.slice(), .live = s.live, .next_tick = s.next_tick, .view = s.view, .focused = s.focused, .told = s.told.slice() };
var owned: ?[]u8 = null;
defer if (owned) |o| s.gpa.free(o);
if (s.ops != null) {
@@ -966,11 +966,12 @@ pub fn slotRead(out: *Kind.Slot, gpa: std.mem.Allocator, bytes: []const u8) !voi
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const r = try walk.load(SlotRecord, arena.allocator(), bytes, null);
- out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .art = r.art, .live = r.live };
+ out.* = .{ .gpa = gpa, .arena = .init(gpa), .version = r.version, .art = r.art, .live = r.live, .next_tick = r.next_tick, .view = r.view, .focused = r.focused };
errdefer out.free();
@memcpy(out.name[0..@min(15, r.name.len)], r.name[0..@min(15, r.name.len)]);
out.path = try gpa.dupe(u8, r.path);
out.where_text.set(r.where);
+ out.told.set(r.told);
out.values.set(r.values);
if (r.record) |rec| out.record = try gpa.dupe(u8, rec);
}
@@ -981,7 +982,8 @@ pub fn slotFree(s: *Kind.Slot, gpa: std.mem.Allocator) void {
}
/// A loaded pane of a kind opened by its kind, if this core has it, else
-/// a placeholder saying what it waits for.
+/// a placeholder saying what it waits for. One with no record reopens from
+/// its file, its place and its words.
pub fn reviveSlot(p: *Pardes, id: usize, s: *Kind.Slot) void {
const k = p.kinds.byName(s.nameOf()) orelse {
s.live = false;
@@ -989,5 +991,34 @@ pub fn reviveSlot(p: *Pardes, id: usize, s: *Kind.Slot) void {
};
s.ops = p.kinds.ops[k];
s.gen = p.kinds.kinds[k].gen;
- _ = Kind.reopen(p, id, s, null);
+ const bytes: ?[]u8 = if (s.record == null and s.path.len > 0) filesystem.read(p, s.path) catch null else null;
+ defer if (bytes) |b| p.gpa.free(b);
+ const kept = .{ s.next_tick, s.view, s.focused };
+ _ = Kind.reopen(p, id, s, bytes);
+ // A replica's Shadow is the authority's pane as it is: it ticks when
+ // that one does, not because it was loaded (a kind opened here ticks
+ // to lay itself out).
+ if (s.ops == null) s.next_tick, s.view, s.focused = kept;
+}
+
+/// A PDF pane of a dump from before the pdf addon: a pane of the addon's
+/// kind `pdf` on its file, at its page, its fit and tint given again as
+/// its words; a placeholder until the addon is loaded.
+fn revivePdf(p: *Pardes, id: usize, pane: *pardes.panes.Pane, old: *pardes.panes.Pane.LegacyPdf) void {
+ defer {
+ p.image_gpa.free(old.path);
+ p.image_gpa.destroy(old);
+ pane.pdf = null;
+ }
+ const s = p.image_gpa.create(Kind.Slot) catch return;
+ s.* = .{ .gpa = p.image_gpa, .arena = .init(p.image_gpa), .version = 1, .live = true };
+ @memcpy(s.name[0..3], "pdf");
+ s.path = p.image_gpa.dupe(u8, old.path) catch {
+ s.free();
+ return p.image_gpa.destroy(s);
+ };
+ _ = s.where_text.print("{d}", .{old.page + 1});
+ _ = s.values.print("PdfFit {t}\nPdfTint {t}\n", .{ old.fit, old.tint });
+ pane.addon = s;
+ reviveSlot(p, id, s);
}
diff --git a/src/edit.zig b/src/edit.zig
index c6c59604..5fa18c2c 100644
--- a/src/edit.zig
+++ b/src/edit.zig
@@ -12,7 +12,6 @@ const sam = @import("sam_edit.zig");
const panes = @import("panes.zig");
const body_layer = @import("body_layer.zig");
const config = @import("config.zig");
-const pdf_enabled = panes.Pdf.enabled;
const lsp = @import("lsp/lsp.zig");
const syntax = @import("syntax.zig");
const platform = pardes.platform;
@@ -178,10 +177,11 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void {
const named = v.register;
v.register = '+';
defer v.register = named;
- if (comptime pdf_enabled) if (pane.pdf) |pv| {
- if (pv.selection_text.len > 0) setYank(p, pv.selection_text);
+ // A kind's pane: what it has selected (Kind.Slot.selection).
+ if (pane.addon) |k| {
+ if (k.selection.len > 0) setYank(p, k.selection);
return;
- };
+ }
if (pane.body.nsel > 0 and !main_only) {
normal.replaySels(p, &pane.body, .{ .normal = .{ .role = .yank } });
} else {
@@ -200,7 +200,7 @@ pub fn paneText(p: *Pardes, pane: *Pane) ![]u8 {
const from = modal.lineStartOffset(tag, pane.tag_top);
const cut = modal.lineStartOffset(tag, pane.tag_top + pane.tag_rows);
const shown = if (cut < tag.len) tag[from .. cut - 1] else tag[from..];
- return std.fmt.allocPrint(arena, "{s}\n{s}", .{ shown, try body_layer.bodyText(p, arena, pane) });
+ return std.fmt.allocPrint(arena, "{s}\n{s}", .{ shown, try body_layer.bodyText(arena, pane) });
}
pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 {
@@ -212,13 +212,13 @@ pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i
pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void {
var gesture = pane.sel[slot];
- if (pane.hasPdf()) return;
+ if (pane.addon != null) return;
if (gesture.state != .done or @min(gesture.r0, gesture.r1) < pane.tag_rows) return;
if (pane.pointerSelection(gesture) != null) return;
pane.clearPointerSelection(slot);
// Refresh the source map before translating the rendered rectangle.
const raw = pane.isTerminal() and pane.body.mode == .tty;
- const body = try body_layer.bodyText(p, p.scratch.allocator(), pane);
+ const body = try body_layer.bodyText(p.scratch.allocator(), pane);
const terminal_lines = if (pane.file == null and !raw) try panes.terminal.cursorLines(p, pane) else &.{};
const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows);
const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows;
@@ -352,8 +352,7 @@ pub fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool {
/// the active modal selection as text, if any
pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 {
- if (comptime pdf_enabled) if (p.view().frontend.native_images) if (pane.pdf) |pv|
- if (pv.selection != null and pv.selection_text.len > 0) return pv.selection_text;
+ if (pane.addon) |k| if (k.selection.len > 0) return k.selection;
if (!pane.body.vsel.active) return null;
return vselText(p, &pane.body);
}
@@ -390,10 +389,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 {
}
const pane = t.pane() orelse return &.{};
if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f);
- if (pane.hasPdf()) {
- if (comptime pdf_enabled) return panes.Pdf.textLines(pane.pdf.?, p.pdf_gpa, arena);
- unreachable;
- }
+ if (pane.addon != null) return &.{};
return panes.terminal.cursorLines(p, pane);
}
@@ -422,7 +418,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void {
}
const pane = t.pane() orelse return;
pane.pinCursor();
- if (pane.file == null and !pane.hasPdf())
+ if (pane.file == null and pane.addon == null)
t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col);
}
@@ -436,10 +432,7 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 {
}
const pane = t.pane() orelse return "";
if (pane.file) |f| return f.content;
- if (pane.hasPdf()) {
- if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa);
- unreachable;
- }
+ if (pane.addon != null) return "";
const lines = try panes.terminal.cursorLines(p, pane);
return panes.terminal.flatSurface(p, pane, lines);
}
@@ -465,7 +458,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText {
if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 };
const pane = t.pane() orelse return null;
if (pane.file) |f| return .{ .text = f.content, .row0 = 0 };
- if (pane.addon != null or pane.hasPdf()) return null;
+ if (pane.addon != null) return null;
return panes.terminal.editText(p, pane, lo, hi, col);
}
@@ -583,7 +576,7 @@ pub fn clampFileCursor(t: *Text) bool {
}
pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void {
- if (t.what == .body) if (t.pane()) |pane| if (pane.hasPdf()) return;
+ if (t.what == .body) if (t.pane()) |pane| if (pane.addon != null) return;
pinPaneCursor(p, t);
_ = clampFileCursor(t);
// snapshot once per insert session (WITH the pre-insert selection) so
diff --git a/src/exec.zig b/src/exec.zig
index c927cb49..eb42424f 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -20,7 +20,6 @@ const python_lang = blk: {
@setEvalBranchQuota(20_000);
break :blk @import("grammar_manifest.zig").byName("python").?;
};
-const pdf_enabled = panes.Pdf.enabled;
const font_picker = pardes.font_picker;
const fonts = pardes.fonts;
const Pane = panes.Pane;
@@ -120,7 +119,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l
const wrapped = pane.wrapAt(visible);
const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows;
const row = if (raw) panes.terminal.gridOffset(pane) + visible else wrapped.line;
- const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else "";
+ const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else "";
const col = if (raw)
@as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0)))))
else if (clicked.r0 >= pane.tag_rows)
@@ -270,10 +269,7 @@ fn heldPane(p: *Pardes, first: usize, k: usize) ?*Pane {
pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 {
for (0..p.panes.len + 2) |k| {
const t = heldPane(p, first, k) orelse continue;
- if (comptime pdf_enabled) if (p.view().frontend.native_images) if (t.pdf) |pv| {
- if (pv.selection != null and pv.selection_text.len > 0)
- return pv.selection_text;
- };
+ if (t.addon) |kind| if (kind.selection.len > 0) return kind.selection;
if (t.sel[sel_slot].state == .done) {
if (edit.selectionText(p, t, t.sel[sel_slot]) catch null) |tx| return tx;
} else if (t.body.vsel.active and t.body.vsel.explicit) {
diff --git a/src/file_watch.zig b/src/file_watch.zig
index 7b8ccbef..812c1791 100644
--- a/src/file_watch.zig
+++ b/src/file_watch.zig
@@ -2,8 +2,8 @@
//! TTY and SDL hosts. Their event loops still own blocking waits, wake
//! coalescing, and retry scheduling; this file owns the identical synchronous
//! operation each wake performs. Text buffers already own the bytes whose hash
-//! is their generation. Large PDFs use metadata which changes for in-place and
-//! rename-over saves, avoiding a second whole-document allocation.
+//! is their generation. A kind's pane (a PDF) uses metadata which changes for
+//! in-place and rename-over saves, reading its file only when it changed.
//!
//! Two kernels, one transaction: inotify on linux (and FreeBSD 15's, the
//! same events), kqueue on macos. `init`, `wait`, `stop`, `drain`, `markDir`
@@ -30,14 +30,27 @@ pub const Identity = struct {
};
/// The last disk generation accepted by a native shell. Text panes already
-/// need their bytes, so their exact content hash is cheapest. PDF panes reopen
-/// the pathname directly and use metadata, avoiding a second whole-document
-/// allocation merely to discover whether MuPDF should reopen it.
+/// need their bytes, so their exact content hash is cheapest. A kind's pane
+/// uses metadata, its file read only once that moved (a PDF can be large).
pub const Generation = union(enum) {
text: u64,
- pdf: ?Identity,
+ kind: ?Identity,
};
+/// Whether a kind's file is still the bytes its pane opened from.
+fn sameBytes(core: *pardes.Pardes, pane: *const pardes.Pane, path: []const u8) bool {
+ const k = pane.addon orelse return false;
+ if (k.opened == 0) return false;
+ const bytes = filesystem.read(core, path) catch return false;
+ defer core.gpa.free(bytes);
+ return std.hash.Wyhash.hash(0, bytes) == k.opened;
+}
+
+fn kindPath(pane: *const pardes.Pane) ?[]const u8 {
+ const k = pane.addon orelse return null;
+ return if (k.path.len > 0) k.path else null;
+}
+
/// One native directory mark, plus what macos needs beside it.
///
/// `wd` is an inotify wd on linux and an open EVTONLY directory descriptor on
@@ -421,8 +434,8 @@ pub fn unwatchAll(fd: c_int, watches: *Table) void {
}
/// Reconcile one marked pane. A true result requests an immediate second pass:
-/// the PDF pathname changed between the stat before MuPDF reopened it and the
-/// stat after, so committing either identity would lose a generation.
+/// a kind's pathname changed between the stat before its pane reopened and
+/// the stat after, so committing either identity would lose a generation.
pub fn reloadPane(
core: *pardes.Pardes,
io: std.Io,
@@ -439,7 +452,7 @@ pub fn reloadPane(
// the next in-place save would otherwise wake nobody. A no-op elsewhere,
// and a no-op here too when the inode has not moved.
if (comptime builtin.os.tag == .macos) {
- if (watches[id]) |*live| remarkFile(live, if (pane.file) |f| f.path else pane.pdfPath());
+ if (watches[id]) |*live| remarkFile(live, if (pane.file) |f| f.path else kindPath(pane));
}
if (pane.file) |file| {
@@ -453,7 +466,7 @@ pub fn reloadPane(
const hash = std.hash.Wyhash.hash(0, bytes);
switch (watched.generation) {
.text => |accepted| if (accepted == hash) return false,
- .pdf => {},
+ .kind => {},
}
// The pane holds the disk's text already (a Zerox twin saved, its
// other twin watching the same file): nothing reloaded, nothing said.
@@ -479,31 +492,32 @@ pub fn reloadPane(
return false;
}
- const path = pane.pdfPath() orelse return false;
+ const path = kindPath(pane) orelse return false;
const before = identify(io, path) catch return false;
switch (watched.generation) {
- .pdf => |accepted| if (accepted) |identity| {
+ .kind => |accepted| if (accepted) |identity| {
if (identity.eql(before)) return false;
- } else if (pardes.panes.Pdf.sameBytes(core, pane)) {
- // Armed over the bytes the pane opened (a text's baseline is its
- // content, a PDF's is what it read): nothing to reload. Parsing
- // the document again doubled every PDF's open.
+ } else if (sameBytes(core, pane, path)) {
+ // Armed over the bytes the pane opened: nothing to reload
+ // (opening it again doubled every PDF's open). Changed between
+ // the open and the arm, it reloads.
if (watches[id]) |*live| if (live.serial == watched.serial) {
- live.generation = .{ .pdf = before };
+ live.generation = .{ .kind = before };
};
return false;
},
.text => {},
}
+ // Its kind reads the file again (Kind.fileChanged): on the tape, no bytes.
if (!core.reloadWatchedFile(@intCast(id), &.{})) return false;
const current = core.panes[id] orelse return false;
if (current.serial != watched.serial) return false;
- const current_path = current.pdfPath() orelse return false;
+ const current_path = kindPath(current) orelse return false;
const after = identify(io, current_path) catch return true;
if (!before.eql(after)) return true;
if (watches[id]) |*live| {
if (live.serial == watched.serial)
- live.generation = .{ .pdf = after };
+ live.generation = .{ .kind = after };
}
if (announce) {
var msg_buf: [256]u8 = undefined;
@@ -531,9 +545,9 @@ pub fn applyEffect(
if (pane.file) |file| {
path = file.path;
generation = .{ .text = std.hash.Wyhash.hash(0, file.content) };
- } else if (pane.pdfPath()) |pdf_path| {
- path = pdf_path;
- generation = .{ .pdf = null };
+ } else if (kindPath(pane)) |kind_path| {
+ path = kind_path;
+ generation = .{ .kind = null };
}
};
watchPane(fd, watches, id, path, serial, generation);
@@ -623,7 +637,7 @@ pub fn reloadTheme(
const hash = std.hash.Wyhash.hash(0, bytes);
switch (watched.generation) {
.text => |accepted| if (accepted == hash) return false,
- .pdf => unreachable,
+ .kind => unreachable,
}
if (!colors.loadThemeFile(core, watched.serial, bytes)) return false;
core.invalidate();
@@ -760,6 +774,35 @@ test "ordinary file watches still reconcile changes between open and watch" {
try std.testing.expectEqualStrings("opened\n", pane.file.?.content);
}
+test "a kind's pane whose file changed between its open and its watch opens again from it" {
+ if (comptime !supported or !filesystem.platform_has_fs) return;
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "pic.ppm", .data = "opened\n" });
+ var path_buf: [256]u8 = undefined;
+ const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/pic.ppm", .{tmp.sub_path});
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ const id: u8 = @intCast(core.freeSlot().?);
+ _ = try pardes.Kind.open(core, id, pardes.Kind.test_kind.of(core), path, "opened\n");
+ while (core.nextEffect()) |_| {}
+ const fd = init(true);
+ if (fd < 0) return error.NoWatcher;
+ defer _ = libc.close(fd);
+ var watches: Table = @splat(null);
+ defer unwatchAll(fd, &watches);
+ // The file as it opened: armed, nothing opened again.
+ try std.testing.expect(!applyEffect(core, io, fd, &watches, id, true, .reconcile));
+ try std.testing.expectEqual(std.hash.Wyhash.hash(0, "opened\n"), core.panes[id].?.addon.?.opened);
+ // Changed before the watch arms: opened again from it.
+ try std.testing.expect(!applyEffect(core, io, fd, &watches, id, false, .reconcile));
+ try tmp.dir.writeFile(io, .{ .sub_path = "pic.ppm", .data = "changed before watch\n" });
+ try std.testing.expect(!applyEffect(core, io, fd, &watches, id, true, .reconcile));
+ try std.testing.expectEqual(std.hash.Wyhash.hash(0, "changed before watch\n"), core.panes[id].?.addon.?.opened);
+}
+
test "explicit OS directory watches refresh prefix-preserving listings" {
if (comptime !supported or !filesystem.platform_has_fs) return;
const gpa = std.testing.allocator;
diff --git a/src/fs.zig b/src/fs.zig
index 835b191a..b5ee2d9e 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -53,9 +53,7 @@ const source_files = [_]Source{
.{ .path = "src/File.zig", .contents = @embedFile("File.zig") },
.{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") },
.{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") },
- .{ .path = "src/image.zig", .contents = @embedFile("image.zig") },
.{ .path = "src/terminal.zig", .contents = @embedFile("terminal.zig") },
- .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") },
.{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") },
.{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") },
.{ .path = "src/look.zig", .contents = @embedFile("look.zig") },
@@ -1464,7 +1462,6 @@ pub fn unmount(p: *Pardes, name: []const u8) !void {
const pane = slot orelse continue;
const paths = [_][]const u8{
if (pane.file) |file| file.path else "",
- if (comptime pardes.pdf_enabled) (if (pane.pdf) |pdf| pdf.path else "") else "",
if (pane.addon) |k| k.path else "",
Pardes.paneDir(pane),
};
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index 1125ff03..e7cd539a 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -482,20 +482,16 @@ fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cel
fn resizeOf(v: *const pardes.Pardes.View, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) ?pardes.Event {
const metrics: pardes.RowMetrics = .{ .body_w = @intCast(cell_w), .body_h = @intCast(cell_h), .tagline_w = @intCast(tag_w), .tagline_h = @intCast(tag_h) };
const same_metrics = std.meta.eql(metrics, v.row_metrics);
- if (comptime pardes.pdf_enabled) {
- const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16)));
- const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16)));
- if (cols == v.screen_w and rows == v.screen_h and
- cell_px_w == v.cell_pixels.w and cell_px_h == v.cell_pixels.h and same_metrics) return null;
- return .{ .resize = .{
- .cols = cols,
- .rows = rows,
- .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h },
- .row_metrics = metrics,
- } };
- }
- if (cols == v.screen_w and rows == v.screen_h and same_metrics) return null;
- return .{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = metrics } };
+ const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16)));
+ const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16)));
+ if (cols == v.screen_w and rows == v.screen_h and
+ cell_px_w == v.cell_pixels.w and cell_px_h == v.cell_pixels.h and same_metrics) return null;
+ return .{ .resize = .{
+ .cols = cols,
+ .rows = rows,
+ .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h },
+ .row_metrics = metrics,
+ } };
}
const TouchPoint = struct {
@@ -1697,7 +1693,6 @@ fn localSession(
var opts = opts_in;
opts.addons = pardes.Addon.scan();
opts.image_allocator = allocs.image;
- opts.pdf_allocator = allocs.pdf;
opts.tree_sitter_allocator = allocs.tree_sitter;
opts.frame_allocator = allocs.frame;
var pw: c_int = 0;
@@ -2030,21 +2025,15 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
const have: ?*replica.Have = if (far) &have_store else null;
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.start(io, allocs.image);
- pardes.pdf.start(allocs.pdf);
- }
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.Kind.heap = allocs.addon;
pardes.syntax.start(allocs.tree_sitter);
defer {
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.stop();
- pardes.pdf.stop();
- }
+ pardes.TerminalImages.stop();
pardes.syntax.stop();
}
var o = opts_in;
o.image_allocator = allocs.image;
- o.pdf_allocator = allocs.pdf;
var joined: replica.Joined = undefined;
var r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
@@ -2910,22 +2899,12 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void {
resetScroll(g);
};
if (hit) |id| {
- const pdf_target = if (comptime pardes.pdf_enabled)
- core.view().frontend.native_images and core.panes[id].?.pdfPage() != null
- else
- false;
const pane = core.panes[id].?;
- if (pdf_target) {
- resetScroll(g);
- in.post(.{ .pdf_scroll = .{
- .pane = @intCast(id),
- .delta_pixels = -w.y * @as(f32, @floatFromInt(g.cell_h)),
- .glide = notchOf(w.y, w.integer_y) != null,
- } });
- } else if (!w.mods.shift and pane.isTerminal() and pardes.panes.terminal.ownsWheel(pane)) {
- // The program's (codex, htop, less): every whole
- // turn goes to it, no glide, for nothing of ours
- // moves. Shift keeps the wheel pardes's.
+ if (pane.addon != null or (!w.mods.shift and pane.isTerminal() and pardes.panes.terminal.ownsWheel(pane))) {
+ // The program's (codex, htop, less), or a kind's (a
+ // PDF's strip): every whole turn goes to it, no glide,
+ // for nothing of ours moves. Shift keeps a terminal's
+ // wheel pardes's.
resetScroll(g);
g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y);
while (g.program_wheel >= 1) : (g.program_wheel -= 1)
@@ -5314,9 +5293,7 @@ fn renderFrame(
const caret_alpha: f32 = if (gliding) 0.85 + 0.15 * std.math.clamp(1 - g.caret.remaining(now) / 0.5, 0, 1) else 1;
g.cursor_quad_alpha = if (quad_mode) caret_alpha * blink_alpha else 0;
// The probe's view of this frame's motion (FrameStats.Frame).
- // A focused PDF's strip is the core's (pdf_view.draw).
- const pdf_focus = if (core.panes[core.view().active]) |pane| pane.hasPdf() else false;
- if (!pdf_focus) core.frames.scroll = g.glide.follow.offset;
+ core.frames.scroll = g.glide.follow.offset;
core.frames.caret = caretRow(g, surface, now) orelse 0;
const cursors_shown = !quad_mode;
var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh);
diff --git a/src/host_io.zig b/src/host_io.zig
index 9cc34465..44061c4d 100644
--- a/src/host_io.zig
+++ b/src/host_io.zig
@@ -167,24 +167,18 @@ pub fn testClock() ?u64 {
return if (libc.getenv("PARDES_TEST_CLOCK")) |v| (if (std.mem.span(v).len != 0) 0 else null) else null;
}
-/// The image, PDF and syntax subsystems a frontend's session draws with,
-/// on `allocs` (pardes.memory.init); PDF pages render on lanes off the
-/// loop (pdf_view.workers). `stopWorkers` is its defer.
+/// The kitty images and syntax subsystems a frontend's session draws with,
+/// on `allocs` (pardes.memory.init), and what kinds keep past a call (their
+/// heap, `pa_api.heap`: the pdf addon's documents and pages). `stopWorkers`
+/// is its defer.
pub fn startWorkers(io: std.Io, allocs: pardes.memory.Allocators) void {
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.start(io, allocs.image);
- pardes.pdf.start(allocs.pdf);
- pardes.panes.Pdf.workers = io;
- }
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.Kind.heap = allocs.addon;
pardes.syntax.start(allocs.tree_sitter);
}
pub fn stopWorkers() void {
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.stop();
- pardes.panes.Pdf.dropKept();
- pardes.pdf.stop();
- }
+ pardes.TerminalImages.stop();
pardes.syntax.stop();
}
@@ -2152,10 +2146,10 @@ pub const exec_command_max = pardes.exec.command_max;
/// graphics by the pixels (yazi's previews; pardes nested in a pane).
pub fn ptyWinsize(core: ?*const pardes.Pardes, cols: u16, rows: u16) posix.winsize {
var ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 };
- if (comptime pardes.pdf_enabled) if (core) |c| {
+ if (core) |c| {
ws.xpixel = std.math.cast(u16, @as(u32, cols) * c.view().cell_pixels.w) orelse 0;
ws.ypixel = std.math.cast(u16, @as(u32, rows) * c.view().cell_pixels.h) orelse 0;
- };
+ }
return ws;
}
@@ -3597,7 +3591,7 @@ pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, pat
if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) {
if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) {
.text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) },
- .pdf => {},
+ .kind => {},
};
};
var mbuf: [256]u8 = undefined;
diff --git a/src/keys.zig b/src/keys.zig
index ee14a48a..e6b417a9 100644
--- a/src/keys.zig
+++ b/src/keys.zig
@@ -228,11 +228,12 @@ pub fn handleKey(p: *Pardes, key: Key) void {
return panes.terminal.forwardKey(p, p.view().active, key);
}
// A kind's pane that takes keys takes them all, as a raw terminal
- // does, but Esc, which leaves (and Shift-Esc, above).
+ // does; Esc too, first, when its kind is of 2.1 (a PDF's drops its
+ // search), and not taken it leaves (and Shift-Esc, above, at once).
if (header == null and pane.focus == .body and pane.prompt == .none) if (pane.addon) |slot| if (pardes.Kind.takesKeys(p, slot)) {
p.view().prefix = .none;
- if (key.cp == Key.escape and !key.ctrl and !key.alt) return exec.runBuiltin(p, .Last, p.view().active, "", null);
if (pardes.Kind.key(p, p.view().active, key)) return;
+ if (key.cp == Key.escape and !key.ctrl and !key.alt) return exec.runBuiltin(p, .Last, p.view().active, "", null);
};
if (p.view().prefix == .leader) return leaderKey(p, key);
if (p.view().prefix == .window) {
@@ -367,7 +368,7 @@ pub fn handleKey(p: *Pardes, key: Key) void {
return;
}
edit.pinPaneCursor(p, &pane.body);
- const explicit = (p.view().frontend.native_images and pane.hasPdfSelection()) or
+ const explicit = (if (pane.addon) |k| k.selection.len > 0 else false) or
(pane.body.vsel.active and pane.body.vsel.explicit);
if (explicit) {
if (exec.chordEachSel(p, pane, cmd)) return;
@@ -386,7 +387,6 @@ pub fn handleKey(p: *Pardes, key: Key) void {
mouse.dispatchPointerBuiltin(p, p.view().active, cmd, operand.text, .{ .on_tag = false, .operand = operand });
return;
}
- if (t.mode == .normal and t.what == .body and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key);
if (t.what == .tag and t.mode == .insert and tagline.typedIntoName(p, pane, key)) return;
// A tag's prefix is read-only: a key whose edit reached into it
// changes nothing, not even where the cursor is.
diff --git a/src/look.zig b/src/look.zig
index 42ed0fb1..7ac8798b 100644
--- a/src/look.zig
+++ b/src/look.zig
@@ -5,7 +5,6 @@ const libc = std.c;
const pardes = @import("pardes.zig");
const exec = @import("exec.zig");
const config = @import("config.zig");
-const pdf_enabled = @import("pardes_config").mupdf;
const diff = @import("diff.zig");
const platform_has_fs = filesystem.platform_has_fs;
const layout = @import("layout.zig");
@@ -18,7 +17,6 @@ const normal = @import("normal.zig");
const edit = @import("edit.zig");
const colors = @import("colors.zig");
const Color = @import("surface.zig").Color;
-const pdf = panes.Pdf.pdf;
const Pane = panes.Pane;
const MAX_PANES = pardes.MAX_PANES;
const Layer = @import("Layer.zig");
@@ -174,54 +172,22 @@ test "parsePathLine: `end` separates a whole-token target from a lenient read" {
try std.testing.expectEqualStrings(whole, parsePathLine(whole).path);
}
-pub const FileKind = if (pdf_enabled) enum { text, pdf } else enum { text };
-
pub const FileTarget = struct {
path: []const u8,
at: Spot,
- kind: FileKind = .text,
};
pub const Target = union(enum) {
none,
dir: []const u8, // resolved absolute path, in caller's buf
file: FileTarget,
- /// A file a kind opens (Kind.forPath): a picture.
- kind: struct { path: []const u8, kind: u8 },
+ /// A file a kind opens (Kind.forPath): a picture, a PDF; `at` the place
+ /// written after it (`book.pdf:12:3`), the kind's to take.
+ kind: struct { path: []const u8, kind: u8, at: Spot = .{} },
url: []const u8,
pane: struct { id: usize, at: Spot },
};
-pub fn isPdfPath(path: []const u8) bool {
- if (comptime !pdf_enabled) return false;
- return std.ascii.endsWithIgnoreCase(path, ".pdf");
-}
-
-test "PDF file kinds exist only in MuPDF-enabled builds" {
- try std.testing.expectEqual(pdf_enabled, isPdfPath("manual.PDF"));
- try std.testing.expect(!isPdfPath("manual.pdf.txt"));
- try std.testing.expectEqual(
- pdf_enabled,
- std.meta.stringToEnum(FileKind, "pdf") != null,
- );
- try std.testing.expect(std.meta.stringToEnum(std.meta.Tag(Target), "pdf") == null);
-}
-
-test ".pdf Look paths are ordinary files when MuPDF is disabled" {
- if (!platform_has_fs) return;
- var realbuf: [4096]u8 = undefined;
- const target = resolve(null, "docs/design.pdf", ".", &realbuf);
- switch (target) {
- .file => |file| {
- if (comptime pdf_enabled)
- try std.testing.expectEqual(FileKind.pdf, file.kind)
- else
- try std.testing.expectEqual(FileKind.text, file.kind);
- },
- else => return error.PdfDidNotResolveAsFile,
- }
-}
-
pub const Span = struct { start: usize, end: usize };
const lead_trim = "([{<\"'`*";
@@ -366,12 +332,7 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu
const found = filesystem.resolve(p, word, cwd, realbuf) orelse return .none;
if (found.dir) return .{ .dir = found.path };
- if (comptime pdf_enabled) if (isPdfPath(found.path)) return .{ .file = .{
- .path = found.path,
- .at = pl.at,
- .kind = .pdf,
- } };
- if (p) |pp| if (pp.kinds.forPath(found.path)) |k| return .{ .kind = .{ .path = found.path, .kind = k } };
+ if (p) |pp| if (pp.kinds.forPath(found.path)) |k| return .{ .kind = .{ .path = found.path, .kind = k, .at = pl.at } };
return .{ .file = .{ .path = found.path, .at = pl.at } };
}
@@ -406,19 +367,6 @@ pub const FileWordSpan = struct {
hi: i32, // exclusive
};
-pub const PdfWordPreview = if (pdf_enabled) struct {
- col: u16,
- row: u16,
- pane: usize,
- serial: u32,
- probe: panes.Pdf.WordProbe,
-
- fn deinit(preview: *@This(), gpa: std.mem.Allocator) void {
- preview.probe.deinit(gpa);
- preview.* = undefined;
- }
-} else void;
-
fn noteLookSource(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
var w: usize = 0;
@@ -586,19 +534,11 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart,
var out_len: usize = 0;
var nrows: usize = 0;
var anchor: ?usize = null;
- if (pane.hasPdf()) {
- if (comptime pdf_enabled) {
- const found = try panes.Pdf.searchRows(
- pane.pdf.?,
- p.pdf_gpa,
- pat,
- start == .cursor,
- out,
- );
- out_len = found.bytes;
- nrows = found.rows;
- anchor = found.anchor;
- }
+ if (pane.addon != null) {
+ // A kind's own rows, if it has a search.
+ const rows = Kind.search(p, id, pat, out) orelse "";
+ out_len = rows.len;
+ nrows = std.mem.count(u8, rows, "\n");
} else {
const lines = try edit.paneCursorLines(p, &pane.body);
// a real file names itself; a terminal or an output buffer has no path
@@ -889,20 +829,11 @@ fn landLookSpot(p: *Pardes, id: usize, pane: *Pane, spot: Pane.LookSpot) void {
}
pub fn cancelLookHover(p: *Pardes) void {
- if (comptime pdf_enabled) if (p.pdf_hover_preview) |*preview| {
- if (preview.pane < p.panes.len) if (p.panes[preview.pane]) |pane| {
- if (pane.serial == preview.serial) if (pane.pdf) |pv|
- pv.invalidateRaster(preview.probe.page);
- };
- preview.deinit(p.pdf_gpa);
- p.pdf_hover_preview = null;
- };
p.look_hover_wait = null;
p.look_hover_preview = null;
}
pub fn lookHoverPane(p: *const Pardes) ?usize {
- if (comptime pdf_enabled) if (p.pdf_hover_preview) |preview| return preview.pane;
if (p.look_hover_preview) |preview| return preview.pane;
if (p.look_hover_wait) |waiting| return waiting.pane;
return null;
@@ -913,8 +844,6 @@ fn noteLookHover(p: *Pardes, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_h
const pane = p.panes[id] orelse return cancelLookHover(p);
_ = edit.pointerTextSelection(p, id, col, row, body_hit, tag_hit) orelse return cancelLookHover(p);
- if (comptime pdf_enabled) if (p.pdf_hover_preview) |shown|
- if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial) return;
if (p.look_hover_preview) |shown|
if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and mouse.sameBodyCell(shown.body_hit, body_hit) and Layer.sameCell(shown.tag_hit, tag_hit)) return;
if (p.look_hover_wait) |waiting|
@@ -954,21 +883,6 @@ pub fn advanceLookHover(p: *Pardes) void {
p.look_hover_refused = waiting.*;
return cancelLookHover(p);
};
- if (comptime pdf_enabled) if (!pointed.on_tag and panes.Pdf.paneNativeReady(p, pane)) {
- const probe = panes.Pdf.probeAt(p, pane, waiting.col, waiting.row) orelse
- return cancelLookHover(p);
- const ready = waiting.*;
- p.look_hover_wait = null;
- p.pdf_hover_preview = .{
- .col = ready.col,
- .row = ready.row,
- .pane = ready.pane,
- .serial = ready.serial,
- .probe = probe,
- };
- pane.pdf.?.invalidateRaster(probe.page);
- return;
- };
const operand = exec.operandAt(p, pane, pointed.sel, true, true);
if (operand.text == null or operand.text.?.len == 0) {
p.look_hover_refused = waiting.*;
@@ -995,14 +909,8 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke
p.view().active = id;
if (pane.collapsed) layout.toggleCollapse(p, id);
pane.body.normal.clear();
- if (pane.hasPdf()) {
- if (landing == .keep) return;
- if (comptime pdf_enabled) {
- const pv = pane.pdf.?;
- if (pv.focusLocation(p.pdf_gpa, at.line, at.col)) panes.Pdf.resetPageChrome(pane);
- }
- return;
- }
+ // A kind's place is its `address`'s (lookKind).
+ if (pane.addon != null) return;
if (at.line == 0) return;
if (pane.file) |*f| {
if (at.line > panes.File.nlines(p.gpa, f)) return;
@@ -1036,9 +944,6 @@ fn openPaneTarget(p: *const Pardes, path: []const u8, at: Spot) ?Target {
for (p.panes, 0..) |slot, i| {
const tt = slot orelse continue;
if (tt.addon) |k| if (std.mem.eql(u8, k.path, path)) {
- return .{ .pane = .{ .id = i, .at = .{} } };
- };
- if (comptime pdf_enabled) if (tt.pdf) |pv| if (std.mem.eql(u8, pv.path, path)) {
return .{ .pane = .{ .id = i, .at = at } };
};
const ff = if (tt.file) |*f| f else continue;
@@ -1066,10 +971,6 @@ pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void {
pane.body.sticky_col = -1;
for (0..pane.sel.len) |slot| pane.clearPointerSelection(slot);
pane.sel = @splat(.{});
- if (comptime pdf_enabled) if (pane.pdf) |state| {
- state.clearDrag();
- state.clearSelection(p.pdf_gpa);
- };
if (v.drag == .select and p.panes[v.drag.select.id] == pane) v.drag = .none;
}
@@ -1142,7 +1043,6 @@ fn canonicalLookLocation(p: *Pardes, id: usize, text: []const u8) ?[]const u8 {
if (target.id >= p.panes.len) return null;
const pane = p.panes[target.id] orelse return null;
if (pane.file) |file| return locationText(p, file.path, target.at);
- if (comptime pdf_enabled) if (pane.pdf) |doc| return locationText(p, doc.path, target.at);
if (pane.addon) |k| if (k.path.len > 0) return locationText(p, k.path, target.at);
var path: [32]u8 = undefined;
return locationText(p, std.fmt.bufPrint(&path, config.pane_addr ++ "{d}", .{pane.serial}) catch return null, target.at);
@@ -1150,47 +1050,6 @@ fn canonicalLookLocation(p: *Pardes, id: usize, text: []const u8) ?[]const u8 {
}
}
-pub fn pdfLinkLocation(p: *Pardes, pane: *const Pane, link: if (pdf_enabled) pdf.Link else void) ?[]const u8 {
- if (comptime !pdf_enabled) return null;
- const state = pane.pdf orelse return null;
- const id = panes.paneIdOf(p, pane) orelse return null;
- return switch (link.destination) {
- .none => null,
- .internal => |dest| if (dest.page < state.document.pages)
- locationText(p, state.path, .{ .line = dest.page + 1 })
- else
- null,
- .external => |uri| canonicalLookLocation(p, id, uri),
- };
-}
-
-pub fn followPdfLink(p: *Pardes, id: usize, probe: *const panes.Pdf.WordProbe) void {
- if (comptime !pdf_enabled) return;
- const pane = p.panes[id] orelse return;
- const link = probe.link orelse return;
- const target = pdfLinkLocation(p, pane, link) orelse return;
- clearNavigationSelection(p, pane);
- if (canonicalLookLocation(p, id, probe.text)) |visible| {
- if (!std.mem.eql(u8, visible, target)) {
- const content = std.fmt.allocPrint(p.gpa, "{s}\n{s}\n", .{ visible, target }) catch |err|
- return p.reportError(id, "PDF link choices", err);
- panes.Output.fillResults(p, id, std.fs.path.dirname(pane.pdf.?.path) orelse ".", .pdf_links, "", content, null) catch |err|
- return p.reportError(id, "PDF link choices", err);
- return;
- }
- }
- switch (link.destination) {
- .internal => |dest| {
- p.noteHaptic(.look);
- noteLookSource(p, id);
- p.view().active = id;
- panes.Pdf.revealOutlineDestination(p, pane, dest);
- },
- .external => lookAt(p, id, target),
- .none => {},
- }
-}
-
/// A look that found nothing: said on the message row, logged as an `err`
/// record, and marked so that /look reads back nothing (ninep/ctl.zig run).
/// The most of a looked-at path or text a miss repeats; past it, its
@@ -1227,25 +1086,6 @@ fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void {
p.reportError(id, std.fmt.bufPrint(&said, "look: {s}", .{missText(path, &cut)}) catch "look", err);
}
-fn missedPage(p: *Pardes, id: usize, path: []const u8, page: usize) void {
- var cut: [miss_path_cap + "…".len]u8 = undefined;
- missed(p, id, "{s} has no page {d}", .{ missText(path, &cut), page });
-}
-
-/// `file.pdf:P:H` names hit H of the pane's search on page P: none there,
-/// or no search, is a miss as a page past the last is.
-fn missedHit(p: *Pardes, id: usize, path: []const u8, page: usize, hit: usize) void {
- var cut: [miss_path_cap + "…".len]u8 = undefined;
- missed(p, id, "{s} has no search hit {d} on page {d}", .{ missText(path, &cut), hit, page });
-}
-
-/// The open PDF pane showing `path`, if one does.
-fn pdfPaneOf(p: *Pardes, path: []const u8) ?*panes.Pdf.State {
- if (comptime !pdf_enabled) return null;
- for (p.panes) |slot| if (slot) |pane| if (pane.pdf) |pv| if (std.mem.eql(u8, pv.path, path)) return pv;
- return null;
-}
-
fn missedLine(p: *Pardes, id: usize, path: []const u8, line: usize) void {
var cut: [miss_path_cap + "…".len]u8 = undefined;
missed(p, id, "{s} has no line {d}", .{ missText(path, &cut), line });
@@ -1481,7 +1321,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void {
}
const pane = p.panes[target] orelse return;
const f = pane.file orelse {
- if (comptime pdf_enabled) if (pane.pdf) |pv| return lookPdfPage(p, id, target, pv, expr);
+ if (pane.addon != null) return lookKind(p, id, target, expr, open == null and target != id);
if ((by_serial or path.len == 0) and pane.isTerminal()) return lookTerminalAddress(p, id, target, expr);
// Named as the pane is, the bare `:addr` (path empty) included.
var serial_name: [32]u8 = undefined;
@@ -1521,26 +1361,40 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void {
v.active = target;
}
-/// A PDF's address is its page: `:N` turns to page N, one past its last a
-/// miss, and `:N:H` to page N's search hit H, as `book.pdf:N:H` (a PDF
-/// search's row) does. It has no text to hold a byte offset (`#N`) or a
-/// pattern: any other address is refused with what it takes.
-fn lookPdfPage(p: *Pardes, id: usize, target: usize, pv: *panes.Pdf.State, expr: []const u8) void {
+/// A place in a kind's pane, its `address`'s: one looked at in a list the
+/// kind made (`text`, a +PdfSections) handed with the list's name first.
+/// A miss is said as the kind said it (`<path> has no page 99`), and a
+/// pane opened for it goes again, as for a file's line past its end.
+fn lookKind(p: *Pardes, id: usize, target: usize, expr_raw: []const u8, opened: bool) void {
+ const slot = p.panes[target].?.addon.?;
+ const expr = std.mem.trim(u8, expr_raw, " \t");
+ var buf: [512]u8 = undefined;
+ const from: []const u8 = if (p.panes[id]) |src| if (src.file) |f| if (f.output) |o| if (o.from == .kind) o.arg() else "" else "" else "" else "";
+ const text = if (from.len > 0) std.fmt.bufPrint(&buf, "{s} {s}", .{ from, expr }) catch expr else expr;
+ var said: Kind.Buf(160) = .{};
+ if (Kind.address(p, target, text, &said)) {
+ if (p.panes[target]) |pane| clearNavigationSelection(p, pane);
+ p.view().active = target;
+ return;
+ }
+ var serial_name: [32]u8 = undefined;
+ const subject = if (slot.path.len > 0) slot.path else std.fmt.bufPrint(&serial_name, config.pane_addr ++ "{d}", .{p.panes[target].?.serial}) catch "the pane";
var cut: [miss_path_cap + "…".len]u8 = undefined;
- const trimmed = std.mem.trim(u8, expr, " \t");
- const colon = std.mem.indexOfScalar(u8, trimmed, ':') orelse trimmed.len;
- const no_text = "{s}: a PDF has no text to address; its address is a page, :N";
- const page = std.fmt.parseInt(usize, trimmed[0..colon], 10) catch
- return missed(p, id, no_text, .{missText(pv.path, &cut)});
- const hit = if (colon < trimmed.len) std.fmt.parseInt(usize, trimmed[colon + 1 ..], 10) catch
- return missed(p, id, no_text, .{missText(pv.path, &cut)}) else 0;
- if (page == 0) return missedPage(p, id, pv.path, 0);
- if (page > pv.page_count) return missedPage(p, id, pv.path, page);
- if (!pv.hitExists(p.pdf_gpa, page, hit)) return missedHit(p, id, pv.path, page, hit);
- const pane = p.panes[target].?;
- clearNavigationSelection(p, pane);
- if (pv.focusLocation(p.pdf_gpa, page, hit)) panes.Pdf.resetPageChrome(pane);
- p.view().active = target;
+ const name = missText(subject, &cut);
+ if (opened) {
+ var kept: [miss_path_cap + "…".len]u8 = undefined;
+ @memcpy(kept[0..name.len], name);
+ p.removePane(target, null) catch {};
+ if (p.panes[id] != null) p.view().active = id;
+ return missed(p, id, "{s} {s}", .{ kept[0..name.len], if (said.len > 0) said.slice() else "is no text to address" });
+ }
+ missed(p, id, "{s} {s}", .{ name, if (said.len > 0) said.slice() else "is no text to address" });
+}
+
+/// A place as `address` takes it: `12`, `12:3`.
+fn spotText(at: Spot, buf: *[32]u8) []const u8 {
+ if (at.col == 0) return std.fmt.bufPrint(buf, "{d}", .{at.line}) catch "";
+ return std.fmt.bufPrint(buf, "{d}:{d}", .{ at.line, at.col }) catch "";
}
fn closeAndMiss(p: *Pardes, id: usize, opened: usize, name: []const u8, why: []const u8) void {
@@ -1599,9 +1453,11 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void {
lookAt(p, from, path);
const id = p.view().active;
const pane = p.panes[id] orelse return;
- // A PDF's place is its page, the last if it has fewer now.
- if (comptime pdf_enabled) if (pane.pdf) |pv| if (std.mem.eql(u8, pv.path, path)) {
- if (at.line > 0 and pv.focusLocation(p.pdf_gpa, @min(at.line, pv.page_count), 0)) panes.Pdf.resetPageChrome(pane);
+ // A kind's place is its `address`'s (a PDF's page), quietly.
+ if (pane.addon) |k| if (std.mem.eql(u8, k.path, path)) {
+ var said: Kind.Buf(160) = .{};
+ var place: [32]u8 = undefined;
+ if (at.line > 0) _ = Kind.address(p, id, spotText(.{ .line = at.line }, &place), &said);
return;
};
const f = if (pane.file) |*file| file else return;
@@ -1757,12 +1613,11 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
// (or, after line 0, as an address).
if (zeroColumnTail(trimmed)) return p.reportFailure(id, @import("ninep/addr.zig").e_col_zero);
if (addressed(trimmed)) |ad| return lookAddress(p, id, ad.path, ad.expr);
- // `:N` on a PDF is its page N, never a search for the text.
- if (comptime pdf_enabled) if (pane.hasPdf() and trimmed.len > 1 and trimmed[0] == ':')
+ // `:N` on a kind's pane is its place N (a PDF's page), never a search
+ // for the text.
+ if (pane.addon != null and trimmed.len > 1 and trimmed[0] == ':')
return lookAddress(p, id, "", trimmed[1..]);
const pl = parsePathLine(trimmed);
- if (comptime pdf_enabled) if (pane.hasPdf()) clearNavigationSelection(p, pane);
- if (comptime pdf_enabled) if (panes.Pdf.lookSection(p, id, pl.path, pl.at)) return;
var realbuf: [4096]u8 = undefined;
// What is looked for is the place without its trailing `:`, `@p33:`
// and `a.txt:` as much as `a.txt:2:`.
@@ -1797,13 +1652,11 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]});
}
const target = p.panes[t.id].?;
- // A PDF's page past its last is a miss, as a line past a file's
- // end is: never the last page in its place (opening one, the
- // same: Pdf.openPane's .refuse).
- if (comptime pdf_enabled) if (target.pdf) |pv| {
- if (t.at.line > pv.page_count) return missedPage(p, id, pv.path, t.at.line);
- if (!pv.hitExists(p.pdf_gpa, @max(1, t.at.line), t.at.col)) return missedHit(p, id, pv.path, @max(1, t.at.line), t.at.col);
- };
+ // A place in a kind's pane is its `address`'s, a miss its to say.
+ if (target.addon != null and t.at.line > 0) {
+ var place: [32]u8 = undefined;
+ return lookKind(p, id, t.id, spotText(t.at, &place), false);
+ }
// A directory's pane, looked at again: read again.
if (target.file) |f| if (f.listing != null) return panes.Dir.show(p, id, t.id);
const before = v.active;
@@ -1823,25 +1676,6 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
panes.Dir.look(p, id, dir);
},
.file => |target| {
- if (comptime pdf_enabled) if (target.kind == .pdf) {
- // A hit of a search: one of the open pane's, checked by
- // focusPaneByPath's pane; a PDF not open has none.
- if (target.at.col > 0) if (pdfPaneOf(p, target.path)) |pv| {
- if (!pv.hitExists(p.pdf_gpa, @max(1, target.at.line), target.at.col)) return missedHit(p, id, target.path, @max(1, target.at.line), target.at.col);
- } else return missedHit(p, id, target.path, @max(1, target.at.line), target.at.col);
- if (focusPaneByPath(p, target.path, target.at)) return;
- const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots);
- // Said with its path and why, as an image that cannot be read
- // is; a page past its last is a miss, as for an open one.
- _ = panes.Pdf.openPane(p, free, target.path, target.at.line, .refuse) catch |err| {
- if (err == error.NoSuchPage) return missedPage(p, id, target.path, target.at.line);
- var said: [miss_path_cap + 64]u8 = undefined;
- var cut: [miss_path_cap + "…".len]u8 = undefined;
- return p.reportError(id, std.fmt.bufPrint(&said, "look: {s}: not a PDF pardes can read", .{missText(target.path, &cut)}) catch "look: not a PDF pardes can read", err);
- };
- exec.placeNew(p, id, id, free, .doc);
- return;
- };
// An open pane on this path too short for the line: a miss that
// touches nothing.
if (openPaneTarget(p, target.path, target.at)) |open| if (p.panes[open.pane.id].?.file) |*f|
@@ -1884,7 +1718,23 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
settleLine(p, id, target.path, target.at, before, opened);
},
.kind => |target| {
- if (focusPaneByPath(p, target.path, .{})) return;
+ var place: [32]u8 = undefined;
+ // A row of a list a kind's pane made (a +PdfSections) is that
+ // pane's place, never another's of the same file: none once it
+ // is gone.
+ const from_list = if (p.panes[id]) |src| if (src.file) |f| if (f.output) |o| o.from == .kind else false else false else false;
+ if (from_list) {
+ for (p.panes, 0..) |slot, owner| if (slot) |op| if (op.search_pane == id) if (op.addon) |k| if (std.mem.eql(u8, k.path, target.path)) {
+ if (target.at.line > 0) return lookKind(p, id, owner, spotText(target.at, &place), false);
+ p.view().active = owner;
+ return;
+ };
+ return missed(p, id, "{s}: the pane its list is of is gone", .{target.path});
+ }
+ if (focusPaneByPath(p, target.path, .{})) {
+ if (target.at.line > 0) lookKind(p, id, v.active, spotText(target.at, &place), false);
+ return;
+ }
const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots);
const made = Kind.openFile(p, free, target.kind, target.path) catch |err|
return lookOpenFailed(p, id, target.path, err);
@@ -1898,6 +1748,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: {s}", .{ missText(target.path, &cut), made.addon.?.refused.slice() }) catch "look: refused");
}
exec.placeNew(p, id, id, free, .doc);
+ if (target.at.line > 0) lookKind(p, id, free, spotText(target.at, &place), true);
},
}
}
diff --git a/src/macos.zig b/src/macos.zig
index 685e9d2f..3fa018c0 100644
--- a/src/macos.zig
+++ b/src/macos.zig
@@ -228,7 +228,7 @@ const FileWatches = struct {
if (!std.mem.eql(u8, watched.path, path)) return;
switch (watched.generation_on_disk) {
.text => watched.generation_on_disk = .{ .text = hash },
- .pdf => {},
+ .kind => {},
}
}
@@ -289,9 +289,9 @@ test "mac file watch generations own paths, coalesce, and reject stale callbacks
try std.testing.expect(!watches.retry(3, second));
try std.testing.expect(watches.entries[3] == null);
- _ = try watches.replace(std.testing.allocator, 4, "/tmp/book.pdf", 77, .{ .pdf = null });
+ _ = try watches.replace(std.testing.allocator, 4, "/tmp/book.pdf", 77, .{ .kind = null });
watches.restampText(4, "/tmp/book.pdf", 123);
- try std.testing.expect(watches.entries[4].?.generation_on_disk.pdf == null);
+ try std.testing.expect(watches.entries[4].?.generation_on_disk.kind == null);
}
const file_watcher_swift = @embedFile("macos/Sources/FileWatcher.swift");
@@ -499,7 +499,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void {
.boot = .tty,
.frame_allocator = allocs.frame,
.image_allocator = allocs.image,
- .pdf_allocator = allocs.pdf,
+
.tree_sitter_allocator = allocs.tree_sitter,
};
if (captureEnv(config_arena.allocator())) |*env| {
@@ -510,14 +510,9 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void {
if (found.dir) |d| crash.setDir(d);
}
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.start(io, allocs.image);
- pardes.pdf.start(allocs.pdf);
- }
- errdefer if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.stop();
- pardes.pdf.stop();
- };
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.Kind.heap = allocs.addon;
+ errdefer pardes.TerminalImages.stop();
pardes.syntax.start(allocs.tree_sitter);
errdefer pardes.syntax.stop();
@@ -607,10 +602,7 @@ export fn pardes_deinit() void {
if (st.changed_cells.len > 0) st.gpa.free(st.changed_cells);
if (st.images.len > 0) st.gpa.free(st.images);
st.core.deinit();
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.stop();
- pardes.pdf.stop();
- }
+ pardes.TerminalImages.stop();
pardes.syntax.stop();
st.config_arena.deinit();
st.prompt_rcs.deinit();
@@ -870,7 +862,7 @@ fn refreshCwds(ctx: ?*anyopaque) void {
fn paneWatchPath(core: *const pardes.Pardes, pane: u8) ?[]const u8 {
const value = core.panes[pane] orelse return null;
if (value.file) |file| return file.path;
- if (comptime pardes.pdf_enabled) if (value.pdfPath()) |path| return path;
+ if (value.addon) |k| if (k.path.len > 0) return k.path;
return null;
}
@@ -878,8 +870,8 @@ fn watchInitialGeneration(st: *State, pane: u8, path: []const u8) ?file_watch.Ge
const value = st.core.panes[pane] orelse return null;
if (value.file) |file| if (std.mem.eql(u8, file.path, path))
return .{ .text = std.hash.Wyhash.hash(0, file.content) };
- if (comptime pardes.pdf_enabled) if (value.pdf) |pdf| if (std.mem.eql(u8, pdf.path, path))
- return .{ .pdf = null };
+ if (value.addon) |k| if (std.mem.eql(u8, k.path, path))
+ return .{ .kind = null };
return null;
}
@@ -943,7 +935,7 @@ fn reloadWatchedTheme(st: *State, announce: bool) bool {
const hash = std.hash.Wyhash.hash(0, bytes);
switch (watched.generation_on_disk) {
.text => |accepted| if (accepted == hash) return false,
- .pdf => unreachable,
+ .kind => unreachable,
}
if (!colors.loadThemeFile(st.core, watched.serial, bytes, true)) return false;
const live = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false;
@@ -994,9 +986,8 @@ fn reloadWatchedFile(st: *State, pane: u8, announce: bool) bool {
active.retries_left = 0;
break :text .committed;
},
- .pdf => |old_identity| pdf: {
- if (comptime !pardes.pdf_enabled) break :pdf .no_change;
- const state_before = if (current.pdf) |pdf_before| pdf_before else break :pdf .no_change;
+ .kind => |old_identity| pdf: {
+ const state_before = if (current.addon) |k| k else break :pdf .no_change;
if (!std.mem.eql(u8, state_before.path, watched.path)) break :pdf .no_change;
const before = file_watch.identify(st.io, watched.path) catch {
retryWatchedFile(st, pane, generation);
@@ -1010,7 +1001,7 @@ fn reloadWatchedFile(st: *State, pane: u8, announce: bool) bool {
const after = st.core.panes[pane] orelse break :pdf .changed_uncommitted;
if (after.serial != watched.serial) break :pdf .changed_uncommitted;
- const pdf_state = if (after.pdf) |pdf_after| pdf_after else break :pdf .changed_uncommitted;
+ const pdf_state = if (after.addon) |k| k else break :pdf .changed_uncommitted;
if (!std.mem.eql(u8, pdf_state.path, watched.path)) break :pdf .changed_uncommitted;
const after_identity = file_watch.identify(st.io, watched.path) catch {
retryWatchedFile(st, pane, generation);
@@ -1023,7 +1014,7 @@ fn reloadWatchedFile(st: *State, pane: u8, announce: bool) bool {
const active = if (st.file_watches.entries[pane]) |*entry| entry else break :pdf .changed_uncommitted;
if (active.generation != generation or active.serial != after.serial)
break :pdf .changed_uncommitted;
- active.generation_on_disk = .{ .pdf = after_identity };
+ active.generation_on_disk = .{ .kind = after_identity };
active.retries_left = 0;
break :pdf .committed;
},
@@ -2099,7 +2090,6 @@ export fn pardes_active_dirty() bool {
fn activeFilePath(st: *State) ?[]const u8 {
const pane = st.core.panes[st.core.view().active] orelse return null;
if (pane.file) |*f| return if (f.output == null) f.path else null;
- if (comptime pardes.pdf_enabled) if (pane.pdfPath()) |path| return path;
if (pane.addon) |k| return k.path;
return null;
}
@@ -2820,7 +2810,7 @@ test "mac row metrics ABI preserves PDF cell dimensions and the unrendered grid"
state.?.config_arena.deinit();
state = null;
}
- if (comptime pardes.pdf_enabled) core.view().cell_pixels = .{ .w = 22, .h = 39 };
+ core.view().cell_pixels = .{ .w = 22, .h = 39 };
const pixels = core.view().cell_pixels;
try std.testing.expectEqual(@as(u16, 0), core.surface.cols);
pardes_row_metrics(22, 39, 17, 30);
diff --git a/src/memory.zig b/src/memory.zig
index e3fa4ac9..31b04b99 100644
--- a/src/memory.zig
+++ b/src/memory.zig
@@ -53,7 +53,9 @@ pub const limits = struct {
pub const host = 512 * MiB;
pub const tree_sitter = 256 * MiB;
pub const image = 256 * MiB;
- pub const pdf = if (!config.mupdf) 64 * KiB else 512 * MiB;
+ /// What kinds keep past a call (`pa_api.heap`): the pdf addon's
+ /// documents, MuPDF's own memory and the pages' pixels.
+ pub const addon = 512 * MiB;
/// One language query's working memory (its parsed answers, the rows
/// it writes): a hard bound, nothing spills. Callstack walks until it
/// would leave less than its rendering reserve.
@@ -70,7 +72,7 @@ pub const Allocators = struct {
lsp: Allocator,
tree_sitter: Allocator,
image: Allocator,
- pdf: Allocator,
+ addon: Allocator,
};
/// One arena's fixed region on a native target, handed out in runs of 4 KiB
@@ -286,8 +288,8 @@ var tree_sitter_bits: [bitsFor(limits.arena.tree_sitter)]u64 = @splat(0);
var tree_sitter_region: Region = .{ .size = limits.arena.tree_sitter, .bits = &tree_sitter_bits };
var image_bits: [bitsFor(limits.arena.image)]u64 = @splat(0);
var image_region: Region = .{ .size = limits.arena.image, .bits = &image_bits };
-var pdf_bits: [bitsFor(limits.arena.pdf)]u64 = @splat(0);
-var pdf_region: Region = .{ .size = limits.arena.pdf, .bits = &pdf_bits };
+var addon_bits: [bitsFor(limits.arena.addon)]u64 = @splat(0);
+var addon_region: Region = .{ .size = limits.arena.addon, .bits = &addon_bits };
var host_bits: [bitsFor(limits.arena.host)]u64 = @splat(0);
var host_region: Region = .{ .size = limits.arena.host, .bits = &host_bits };
@@ -429,7 +431,7 @@ fn pinned(allocator: Allocator, bytes: []const u8, alignment: std.mem.Alignment)
/// was freed (a V8 Callstack page left 21 MiB free in its heap; this returned
/// 20). Walks every arena and the heap, so for rare, large events only.
pub fn trim() void {
- inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &pdf_region, &host_region }) |r| r.trim();
+ inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &addon_region, &host_region }) |r| r.trim();
if (comptime builtin.os.tag != .linux or builtin.abi.isMusl() or !builtin.link_libc) return;
const glibc = struct {
extern "c" fn malloc_trim(pad: usize) c_int;
@@ -472,7 +474,7 @@ pub fn init(fallback: Allocator) Allocators {
.lsp = lsp_region.init(spill),
.tree_sitter = tree_sitter_region.init(spill),
.image = image_region.init(spill),
- .pdf = pdf_region.init(spill),
+ .addon = addon_region.init(spill),
};
}
@@ -481,7 +483,7 @@ pub fn deinit() void {
if (!debug_enabled) return;
var leaked = false;
// The host's arena lives as long as the process (`host`).
- inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &pdf_region }) |r| leaked = r.deinit() or leaked;
+ inline for (.{ &pardes_region, &frame_region, &lsp_region, &tree_sitter_region, &image_region, &addon_region }) |r| leaked = r.deinit() or leaked;
if (leaked) @panic("allocator leaks detected");
}
@@ -547,7 +549,7 @@ test "memory limits preserve desktop capacities" {
try std.testing.expectEqual(512 * MiB, limits.arena.lsp);
try std.testing.expectEqual(256 * MiB, limits.arena.tree_sitter);
try std.testing.expectEqual(256 * MiB, limits.arena.image);
- try std.testing.expectEqual(if (config.mupdf) 512 * MiB else 64 * KiB, limits.arena.pdf);
+ try std.testing.expectEqual(512 * MiB, limits.arena.addon);
}
test "a pinned blob's free is put off until its last pin goes" {
diff --git a/src/modal.zig b/src/modal.zig
index 894fbaf8..c510adc1 100644
--- a/src/modal.zig
+++ b/src/modal.zig
@@ -244,7 +244,7 @@ pub const Normal = struct {
pub const Find = enum { forward, backward, till_forward, till_backward };
/// What a key sequence asks for: the command and what it was given. The
- /// text's executor (normal.zig) and a PDF's (pdf_view.zig) both take it.
+ /// text's executor (normal.zig) takes it.
pub const Action = struct {
role: Role,
count: u32 = 1,
diff --git a/src/mouse.zig b/src/mouse.zig
index 7eab8322..6e8c1719 100644
--- a/src/mouse.zig
+++ b/src/mouse.zig
@@ -14,8 +14,6 @@ const edit = @import("edit.zig");
const body_layer = @import("body_layer.zig");
const builtins = @import("builtins.zig");
const config = @import("config.zig");
-const pdf_enabled = panes.Pdf.enabled;
-const pdf = panes.Pdf.pdf;
const platform = pardes.platform;
const Pane = panes.Pane;
const MAX_PANES = pardes.MAX_PANES;
@@ -52,9 +50,6 @@ pub const Drag = union(enum) {
/// Where the sweep began in the text, once it has scrolled: its
/// press row may be off the screen.
anchor: ?modal.Cursor = null,
- /// This gesture began over a usable native PDF raster. The payload is
- /// zero-bit when PDF support is absent.
- pdf: panes.Pdf.PointerDrag = .{},
/// Where its body was in the frontend's frame at its last hit there:
/// a sweep that leaves it is clamped back onto it (`bodyHitForPane`).
body: ?Layer.Place = null,
@@ -385,7 +380,9 @@ fn tracksMouse(pane: *const Pane) bool {
/// program's, reported without the Shift that chose it. True when the
/// event was the program's.
/// The pointer over the body of a pane whose kind takes the mouse: the
-/// kind's, a press focusing the pane first.
+/// kind's, a press focusing the pane first, its drag and release the
+/// kind's wherever they go (clamped to its body); a pointer leaving the
+/// body is told as a motion at 0xffff.
fn kindMouse(p: *Pardes, m: Mouse) bool {
const v = p.view();
if (v.drag != .none or v.header_drag or v.header_sweep != null) return false;
@@ -396,13 +393,30 @@ fn kindMouse(p: *Pardes, m: Mouse) bool {
const r = v.rects[id];
const top = p.bodyTop(pane, r) + pane.notices.span();
const x0 = r.x + config.GUTTER;
- if (m.col < x0 or m.col >= r.x + r.w or m.row < top or m.row >= r.y + r.h) continue;
+ const inside = m.col >= x0 and m.col < r.x + r.w and m.row >= top and m.row < r.y + r.h;
+ const grabbed = v.kind_grab != null and v.kind_grab.? == id and (m.kind == .drag or m.kind == .release);
+ if (!inside and !grabbed) continue;
+ if (v.kind_hover != null and v.kind_hover.? != id) kindLeave(p);
+ v.kind_hover = @intCast(id);
if (m.kind == .press) v.active = id;
- return pardes.Kind.mouse(p, id, m, m.col - x0, m.row - top);
+ if (m.kind == .press and m.button != .wheel_up and m.button != .wheel_down and m.button != .wheel_left and m.button != .wheel_right) v.kind_grab = @intCast(id);
+ if (m.kind == .release) v.kind_grab = null;
+ const col = std.math.clamp(m.col, x0, r.x + r.w -| 1) - x0;
+ const row = std.math.clamp(m.row, top, r.y + r.h -| 1) - top;
+ return pardes.Kind.mouse(p, id, m, col, row);
}
+ kindLeave(p);
return false;
}
+/// The pointer has left the kind's pane it was over: told so, once.
+pub fn kindLeave(p: *Pardes) void {
+ const v = p.view();
+ const id = v.kind_hover orelse return;
+ v.kind_hover = null;
+ _ = pardes.Kind.mouse(p, id, .{ .button = .none, .kind = .motion, .col = 0, .row = 0 }, 0xffff, 0xffff);
+}
+
fn programMouse(p: *Pardes, m: Mouse) bool {
const v = p.view();
const button: ?panes.terminal.MouseButton = switch (m.button) {
@@ -699,9 +713,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
_ = config.wheelTick(&v.wheel_guard, true);
const id = hovered orelse return;
const pane = p.panes[id].?;
- if (pane.hasPdf())
- panes.Pdf.verticalWheel(p, pane, if (m.button == .wheel_up) -1 else 1)
- else if (!programWheel(p, id, m, mcol, mrow))
+ if (!programWheel(p, id, m, mcol, mrow))
pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows);
},
.wheel_left, .wheel_right => {
@@ -711,10 +723,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
const pane = p.panes[id].?;
if (programWheel(p, id, m, mcol, mrow)) {
// the program's
- } else if (pane.hasPdf()) {
- panes.Pdf.horizontalWheel(p, pane, if (m.button == .wheel_right) 1 else -1);
- // ponytail: no right clamp — overscroll shows blank and the
- // next cursor move or left wheel pulls it back
} else if (pane.file != null and !p.settings.wrap) {
// wrapped there is nothing off to the right to reach
const line = panes.File.sourceLine(pane, pane.body.cur_row);
@@ -740,8 +748,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
if (v.drag == .select and v.drag.select.button == config.look_button) {
if (p.panes[v.drag.select.id]) |t| {
t.sel[@backingInt(config.look_button)].state = .none;
- if (comptime pdf_enabled)
- panes.Pdf.pointerCancel(t, v.drag.select.pdf);
}
v.drag = .none;
return;
@@ -827,14 +833,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
.button = config.select_button,
.ctrl = m.ctrl,
.body = bodyPlace(m.body_hit, pane),
- .pdf = panes.Pdf.pointerStart(
- p,
- pane,
- config.select_button,
- mcol,
- mrow,
- pointed.on_tag,
- ),
} };
}
},
@@ -858,8 +856,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
if (v.drag == .select) {
if (p.panes[v.drag.select.id]) |t| {
t.sel[@backingInt(v.drag.select.button)].state = .none;
- if (comptime pdf_enabled)
- panes.Pdf.pointerCancel(t, v.drag.select.pdf);
}
v.drag = .none;
return;
@@ -885,16 +881,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
.id = id,
.button = m.button,
.body = bodyPlace(m.body_hit, pane),
- // A native body gesture stays native even when its
- // point later misses a letterbox or selection.
- .pdf = panes.Pdf.pointerStart(
- p,
- pane,
- m.button,
- mcol,
- mrow,
- pointed.on_tag,
- ),
},
};
}
@@ -979,7 +965,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo
// from the pointer.
const body_y = p.bodyTop(pane, r);
const body_h = r.h -| pane.tag_rows;
- s.edge = if (s.button != config.select_button or pane.sel[b].r0 < tag_rows or pane.file == null or pane.hasPdf() or body_h == 0)
+ s.edge = if (s.button != config.select_button or pane.sel[b].r0 < tag_rows or pane.file == null or body_h == 0)
0
else if (mrow < body_y)
-1
@@ -997,8 +983,6 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo
else
@as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + tag_rows;
if (pane.sel[b].r1 < tag_rows) pane.sel[b].c1 += @as(i32, pane.tag_scroll);
- if (comptime pdf_enabled)
- panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow);
}
},
.none => {},
@@ -1140,7 +1124,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void {
if (rows.len == 0) return;
const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0);
const endpoint = rows[if (forward) rows.len - 1 else 0];
- const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return;
+ const body = body_layer.bodyText(p.scratch.allocator(), pane) catch return;
const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.terminal.gridOffset(pane))));
const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo;
pane.body.cur_row = pane.surfRow(endpoint.row);
@@ -1251,32 +1235,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void {
},
.select => |s| {
const pane = p.panes[s.id] orelse return;
- if (comptime pdf_enabled) {
- if (s.pdf.native) {
- var release = panes.Pdf.pointerRelease(
- p,
- pane,
- s.pdf,
- s.button,
- s.chorded,
- );
- defer release.deinit(p.pdf_gpa);
- if (release.probe) |*probe| if (probe.link != null) {
- look.followPdfLink(p, s.id, probe);
- return;
- };
- // A native PDF page has no byte offsets of its own to
- // report, so a scripted pane cannot intercept this one.
- if (release.action) |action| dispatchPointerBuiltin(
- p,
- s.id,
- if (action == .look) config.look_cmd else config.exec_cmd,
- release.text,
- null,
- );
- return;
- }
- }
if (s.chorded) {
// a cut/paste chord consumed this drag; the release is inert
pane.sel[@backingInt(s.button)].state = .none;
@@ -1402,16 +1360,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void {
fn chordCutPaste(p: *Pardes, cut: bool) void {
const s = &p.view().drag.select;
const pane = p.panes[s.id] orelse return;
- if (comptime pdf_enabled) if (pane.pdf) |pv| {
- if (!s.chorded) {
- s.chorded = true;
- pane.sel[sel_slot].state = .none;
- }
- // A PDF is immutable: its Cut-side chord is Snarf (copy), while
- // Paste has no document mutation to perform.
- if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text);
- return;
- };
if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) {
// A sweep over the tag cuts from and pastes into the tag's own text;
// the part of it over the prefix is not the tag's to cut, so the
diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig
index 42d9f3bd..53128c5e 100644
--- a/src/ninep/ctl.zig
+++ b/src/ninep/ctl.zig
@@ -442,10 +442,9 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 {
var idbuf: [48]u8 = undefined;
const id = exec_line.replId(&idbuf, pane);
if (id.len > 0) w.print("{s} ", .{id}) catch {};
- // Then what its tag does not say: Collapse, and a PDF's PdfFit and
- // PdfTint, in the words they take.
+ // Then what its tag does not say: Collapse, and a kind's own fields (a
+ // PDF's PdfFit and PdfTint, in the words they take).
if (pane.collapsed) w.writeAll("collapsed ") catch {};
- if (comptime pardes.pdf_enabled) if (pane.pdf) |pv| w.print("fit:{s} tint:{s} ", .{ @tagName(pv.fit), @tagName(pv.tint) }) catch {};
if (pane.addon != null) {
var fields: [128]u8 = undefined;
const kind_fields = pardes.Kind.ctlRead(pane, &fields);
@@ -1544,7 +1543,7 @@ test "an address looked at in an image pane names the image, never an empty subj
try testing.expect(th.logHas(p, "look: /tmp/pardes-pic.ppm is no text to address"));
}
-test "Save and Save path on an image pane are refused with why, never a silent success" {
+test "Save and Save path on a kind's pane (a picture) are refused with why, never a silent success" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
const id = p.freeSlot().?;
@@ -1552,7 +1551,7 @@ test "Save and Save path on an image pane are refused with why, never a silent s
for ([_][]const u8{ "Save\n", "Save /tmp/pardes-copy.ppm\n" }) |line| {
const r = wr(p, Node.of(doc.serial, .ctl), line);
try testing.expectEqual(Status.err, r.reply.status);
- try testing.expectEqualStrings("Save: an image pane has no text to save", r.reply.ename);
+ try testing.expectEqualStrings("Save: a test pane has no text to save", r.reply.ename);
}
}
@@ -1574,9 +1573,6 @@ test "a builtin for one kind of pane is refused on another, and still acts on it
try testing.expectEqual(Status.err, r.reply.status);
try testing.expectEqualStrings(case[1], r.reply.ename);
}
- if (pardes.pdf_enabled) for ([_][]const u8{ "PdfFit\n", "PdfTint\n", "PdfSections\n" }) |line| {
- try testing.expectEqual(Status.err, wr(p, Node.of(serial, .ctl), line).reply.status);
- };
const id = p.freeSlot().?;
// A picture shown: the core's art words follow the kind's prefix.
const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", "P6\n1 1\n255\n\x01\x02\x03");
@@ -2160,48 +2156,6 @@ test "a language server question that finds nothing, cannot be answered, or is a
try testing.expectEqual(E.INVAL, wr(p, Node.of(img.serial, .body), "text\n").errno());
}
-test "a truncated PDF fails its look with its path and why" {
- if (comptime !pardes.pdf_enabled) return;
- const p = try withFile(testing.allocator, "x\n");
- defer p.deinit();
- var tmp = testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try @import("mupdf").testFixture(testing.allocator, "links.pdf");
- defer testing.allocator.free(bytes);
- try tmp.dir.writeFile(testing.io, .{ .sub_path = "cut.pdf", .data = bytes[0..40] });
- var dir_buf: [4096]u8 = undefined;
- const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
- var line: [4200]u8 = undefined;
- const r = wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/cut.pdf\n", .{dir}));
- try testing.expectEqual(Status.err, r.reply.status);
- try testing.expect(std.mem.indexOf(u8, r.reply.ename, "cut.pdf: not a PDF pardes can read: ") != null);
-}
-
-test "a PDF's body reads its page's text layer, and takes no write" {
- if (comptime !pardes.pdf_enabled) return;
- const p = try withFile(testing.allocator, "x\n");
- defer p.deinit();
- var tmp = testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try @import("mupdf").testFixture(testing.allocator, "links.pdf");
- defer testing.allocator.free(bytes);
- try tmp.dir.writeFile(testing.io, .{ .sub_path = "doc.pdf", .data = bytes });
- var dir_buf: [4096]u8 = undefined;
- const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
- var line: [4200]u8 = undefined;
- _ = wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/doc.pdf\n", .{dir}));
- p.sync();
- const doc = p.panes[p.view().active].?;
- try testing.expect(doc.hasPdf());
- const body = Node.of(doc.serial, .body);
- try testing.expect(std.mem.indexOf(u8, rd(p, body, 0, 4096).bytes, "target.txt") != null);
- // Read from an offset, as a mount's chunked reads ask: the text from there.
- const whole = try testing.allocator.dupe(u8, rd(p, body, 0, 4096).bytes);
- defer testing.allocator.free(whole);
- try testing.expectEqualStrings(whole[3..], rd(p, body, 3, 4096).bytes);
- try testing.expectEqual(E.INVAL, wr(p, body, "more\n").errno());
-}
-
test "workspace symbols, Symbols and Diagnostics share their directory's one +Search" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig
index 92d28b99..704f1ac8 100644
--- a/src/ninep/pane.zig
+++ b/src/ninep/pane.zig
@@ -145,7 +145,6 @@ pub fn dirtyOf(pane: *const Pane) bool {
/// The pane's name: its file, its document, or a terminal's directory.
pub fn nameOf(p: *Pardes, pane: *const Pane) []const u8 {
if (pane.file) |*f| return f.path;
- if (pane.pdfPath()) |path| return path;
if (pane.addon) |k| if (k.path.len > 0) return k.path;
const cwd = pane.cwdSlice();
// A shell given no directory was started in the session's, and is
@@ -155,7 +154,6 @@ pub fn nameOf(p: *Pardes, pane: *const Pane) []const u8 {
pub fn kindOf(pane: *const Pane) []const u8 {
if (pane.file != null) return "text";
- if (pane.pdfPath() != null) return "pdf";
if (pane.addon) |k| return k.nameOf();
// A command's pane is no shell to type into: a script choosing a
// terminal by kind must not pick one.
@@ -350,7 +348,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 {
const pf = &pane.fs;
return switch (f) {
// A terminal's body reads its screen and history, as text.
- .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len,
+ .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len,
// What addr selects, generated by each read: no length, as acme's
// data and xdata have none.
.data, .xdata => 0,
@@ -452,14 +450,11 @@ fn readFlag(p: *Pardes, req: Req, on: bool) Reply {
return tree.stagedReply(p, req);
}
-/// The text layer of the page a PDF pane shows (MuPDF's extraction, kept
-/// with the page), null for any other pane.
-/// A document's text, read-only: a PDF's text layer, a kind's `body`.
-fn pdfText(p: *Pardes, pane: *Pane) ?[]const u8 {
- if (pane.addon != null) return pardes.Kind.body(pane, p.scratch.allocator()) catch null;
- if (comptime !pardes.pdf_enabled) return null;
- const pv = pane.pdf orelse return null;
- return pv.ensureText(p.pdf_gpa);
+/// A kind's pane's text, read-only: its `body` (a PDF's: the text layer
+/// of the page shown); null for any other pane.
+fn kindText(p: *Pardes, pane: *Pane) ?[]const u8 {
+ if (pane.addon == null) return null;
+ return pardes.Kind.body(pane, p.scratch.allocator()) catch null;
}
fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
@@ -474,8 +469,8 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
.len = clip(n),
} } };
}
- // A PDF's body is its text layer, the page shown's: read-only.
- if (pdfText(p, pane)) |text| return tree.window(p, req, text);
+ // A kind's body is its text (a PDF's, the page shown's): read-only.
+ if (kindText(p, pane)) |text| return tree.window(p, req, text);
if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane);
const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch
return Reply.fail(req.tag, E.NOMEM);
diff --git a/src/normal.zig b/src/normal.zig
index d5ce5f4a..1fa5bf11 100644
--- a/src/normal.zig
+++ b/src/normal.zig
@@ -1,6 +1,6 @@
//! Helix normal mode: a key read against the configured bindings becomes
//! modal actions, replayed across every selection, and each action is done
-//! to the pane; PDF panes get their own normal keys.
+//! to the pane (a kind's pane takes its own keys first, Kind.key).
const pardes = @import("pardes.zig");
const tagline = @import("tagline.zig");
const exec = @import("exec.zig");
@@ -13,7 +13,6 @@ const panes = @import("panes.zig");
const edit = @import("edit.zig");
const config = @import("config.zig");
const keyboard = @import("keys.zig");
-const pdf_enabled = panes.Pdf.enabled;
const Pane = panes.Pane;
const Text = panes.Text;
const Key = pardes.Key;
@@ -852,7 +851,10 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void {
return panes.startPrompt(p, pane, &pane.body, .{ .search = config.search_marker }),
// In a file's text, n and N step its places while they answer for
// the register (Places.answersN); else helix's search of the register.
- .search_next, .search_prev => if (t.what == .body and pane.file != null and pane.places.answersN(p, pane))
+ // A kind's pane walks its `/`'s +Search (look.zig runSearch).
+ .search_next, .search_prev => if (t.what == .body and pane.addon != null)
+ return look.lookWalk(p, if (a.role == .search_next) 1 else -1)
+ else if (t.what == .body and pane.file != null and pane.places.answersN(p, pane))
return pane.places.step(p, pane, a.role == .search_next, a.count, t.select)
else
return searchStep(p, t, text, a.role == .search_next, a.count),
@@ -860,7 +862,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void {
searchSelection(p, t, text, a.role == .search_selection_word);
// The pattern is line 1 of this text's query pane, made or
// reused, the keyboard staying here: n and N step its places.
- if (t.what == .body and pane.file != null and !pane.hasPdf() and pane.query == null) {
+ if (t.what == .body and pane.file != null and pane.query == null) {
const name = if (v.register != 0) v.register else '/';
const pat = p.registers.value(name, 0) orelse return;
panes.Query.open(p, v.active, .text, pat, false);
@@ -910,19 +912,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) void {
}
}
-pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void {
- if (comptime !pdf_enabled) return;
- if (pane.pdf == null) return;
- if (pane.body.normal.prefix == null and isPrefix(key, 'f')) {
- pane.body.normal.clear();
- return exec.runBuiltin(p, .PdfSections, p.view().active, "", null);
- }
- switch (modal.Normal.parse(&pane.body.normal, normalInput(key))) {
- .pending, .ignored, .unbound => {},
- .action => |action| panes.Pdf.applyNormal(p, pane, action),
- }
-}
-
test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
diff --git a/src/panes.zig b/src/panes.zig
index cfe09f33..1ec78bbc 100644
--- a/src/panes.zig
+++ b/src/panes.zig
@@ -20,7 +20,6 @@ const Cell = pardes.Cell;
const BOX_H = pardes.BOX_H;
const MAX_PANES = pardes.MAX_PANES;
const effect_path_cap = pardes.effect_path_cap;
-const pdf_enabled = Pdf.enabled;
/// An owned editable buffer and the absolute surface row of its first line.
/// Files use row zero; terminal overlays may begin anywhere in scrollback.
@@ -35,9 +34,9 @@ pub const Pane = struct {
.derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" },
.authority = .{"fs"},
.len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } },
- // A picture's and a PDF's memory is their own allocators' (a dump
- // loaded makes it there).
- .alloc = .{ .{ "addon", "image" }, .{ "pdf", "pdf" }, .{ "terminal", "terminal" } },
+ // A picture's memory is its own allocator's (a dump loaded makes
+ // it there).
+ .alloc = .{ .{ "addon", "image" }, .{ "pdf", "image" }, .{ "terminal", "terminal" } },
};
/// The words that throw unsaved text away (builtins.zig warnModified).
pub const Discarding = enum { Exit, Restore, get, Del, Delcol };
@@ -78,10 +77,14 @@ pub const Pane = struct {
col1: i32,
};
- /// A PDF's state is its own allocation in the pdf region, as a
- /// terminal's is its own: inline, its raster slots would be every
- /// pane's, and every rollback copy's.
- const PdfSlot = if (Pdf.enabled) ?*Pdf.State else void;
+ /// A PDF pane as a dump of a build before the pdf addon kept it, read
+ /// to open it as the addon's (dump.zig revivePane); never written.
+ pub const LegacyPdf = struct {
+ path: []u8 = &.{},
+ page: usize = 0,
+ fit: enum { width, height } = .width,
+ tint: enum { disabled, filtered, full } = .filtered,
+ };
/// What an open prompt is asking. The answer is typed into `input`.
pub const Prompt = union(enum) {
@@ -203,7 +206,7 @@ pub const Pane = struct {
file: ?File.State = null,
/// A pane of a kind (Kind.zig): a picture, or one a library brought.
addon: ?*@import("Kind.zig").Slot = null,
- pdf: PdfSlot = if (Pdf.enabled) null else {},
+ pdf: ?*LegacyPdf = null,
prompt: Prompt = .none,
/// The text an open prompt answers for: `s`/`S` select in it and `|`
/// pipes it. A header's is whichever has the keyboard; `/` and Save's
@@ -502,8 +505,7 @@ pub const Pane = struct {
}
pub fn isTerminal(pane: *const Pane) bool {
- const no_pdf = if (comptime Pdf.enabled) pane.pdf == null else true;
- return pane.file == null and pane.addon == null and no_pdf;
+ return pane.file == null and pane.addon == null and pane.pdf == null;
}
/// The one coloring choice keyed on what a pane IS, so the highlight
@@ -526,16 +528,6 @@ pub const Pane = struct {
return .none;
}
- pub fn pdfPath(pane: *const Pane) ?[]const u8 {
- if (comptime Pdf.enabled) if (pane.pdf) |pv| return pv.path;
- return null;
- }
-
- pub fn pdfPage(pane: *const Pane) ?usize {
- if (comptime Pdf.enabled) if (pane.pdf) |pv| return pv.page;
- return null;
- }
-
pub fn surfRow(pane: *const Pane, g: i32) i32 {
const o = pane.ovl orelse return g;
if (g <= o.row) return g;
@@ -556,7 +548,6 @@ pub const Pane = struct {
/// current scroll offset: file top line, or the scrollback offset
pub fn scroll(pane: *Pane) i32 {
if (pane.file) |f| return @intCast(f.scroll);
- if (comptime Pdf.enabled) if (pane.pdf) |pv| return @intCast(pv.text_scroll);
return pane.surfRow(terminal.gridOffset(pane) + pane.pan);
}
@@ -592,17 +583,7 @@ pub const Pane = struct {
f.scroll = next;
f.syntax_dirty = true;
}
- } else if (hasPdf(pane)) {
- if (comptime Pdf.enabled) {
- const pv = pane.pdf.?;
- const max: i64 = @intCast(modal.lineCount(pv.text) -| 1);
- pv.text_scroll = @intCast(std.math.clamp(
- @as(i64, @intCast(pv.text_scroll)) + delta,
- 0,
- max,
- ));
- }
- } else {
+ } else if (pane.addon == null) {
// the vt scrolls in SHELL rows; convert through the edit buffer
const off = terminal.gridOffset(pane);
terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off);
@@ -654,10 +635,6 @@ pub const Pane = struct {
const lines: i32 = @intCast(File.nlines(pane.gpa, f));
to = @min(to, if (off == 0 and pane.textFits()) @max(pane.body.cur_row, lines - 1 - @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) else lines - 1);
}
- if (comptime Pdf.enabled) {
- if (pane.pdf) |pv|
- to = @min(to, @as(i32, @intCast(modal.lineCount(pv.text) -| 1)));
- }
pane.scrollBy(@max(0, to - last));
}
}
@@ -685,7 +662,7 @@ pub const Pane = struct {
pub fn pinCursor(pane: *Pane) void {
if (pane.body.cur_pinned) return;
- if (pane.file != null or hasPdf(pane)) {
+ if (pane.file != null or pane.addon != null) {
pane.body.cur_row = pane.scroll();
pane.body.cur_col = 0;
} else {
@@ -695,17 +672,6 @@ pub const Pane = struct {
}
pane.body.cur_pinned = true;
}
-
- pub fn hasPdf(pane: *const Pane) bool {
- return if (comptime Pdf.enabled) pane.pdf != null else false;
- }
-
- pub fn hasPdfSelection(pane: *const Pane) bool {
- return if (comptime Pdf.enabled)
- if (pane.pdf) |pv| pv.selection != null and pv.selection_text.len > 0 else false
- else
- false;
- }
};
pub const Text = @import("Text.zig");
@@ -723,8 +689,6 @@ pub const Dir = @import("Dir.zig");
pub const mini = @import("mini.zig");
-pub const Pdf = @import("pdf_view.zig");
-
pub const terminal = @import("terminal.zig");
test {
@@ -735,7 +699,6 @@ test {
_ = Dir;
_ = mini;
_ = @import("Kind.zig");
- _ = Pdf;
_ = terminal;
}
@@ -776,7 +739,7 @@ pub fn retirePane(p: *Pardes, pane: *Pane) void {
// A query pane's places, in whatever panes it fed, go with it.
if (pane.query != null) panes.Query.release(p, pane);
if (pane.file) |*file| panes.File.leaveTwins(p, file);
- const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf();
+ const watched = (if (pane.file) |f| f.output == null else false) or (if (pane.addon) |k| k.path.len > 0 else false);
for (p.panes, 0..) |slot, id| if (slot == pane) {
if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } });
if (pane.isTerminal()) p.emit(.{ .close_pty = .{ .pane = @intCast(id) } });
@@ -803,7 +766,10 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void {
if (pane.command) |line| p.gpa.free(line);
if (pane.shell) |bin| p.gpa.free(bin);
@import("Kind.zig").close(p, pane);
- if (comptime pdf_enabled) if (pane.pdf) |pv| panes.Pdf.deinitPane(p, pane, pv);
+ if (pane.pdf) |old| {
+ p.image_gpa.free(old.path);
+ p.image_gpa.destroy(old);
+ }
if (pane.file) |*file| panes.File.deinit(p, pane, file);
if (pane.ovl) |o| p.gpa.free(o.text);
views.tornDown(p, pane);
@@ -996,8 +962,6 @@ pub fn paneDir(pane: *const Pane) []const u8 {
.none => {},
}
if (pane.file) |f| return panes.Dir.ofName(f.path);
- if (comptime pdf_enabled) if (pane.pdf) |pv|
- return std.fs.path.dirname(pv.path) orelse "/";
if (pane.addon) |k| if (k.path.len > 0) return std.fs.path.dirname(k.path) orelse "/";
return pane.cwdSlice();
}
diff --git a/src/pardes.zig b/src/pardes.zig
index 58f8fa17..ecbc0633 100644
--- a/src/pardes.zig
+++ b/src/pardes.zig
@@ -69,8 +69,6 @@ pub const builtins_json = @import("builtins_json.zig");
const limits = memory.limits;
const selection_pipe = @import("selection_pipe.zig");
pub const config = @import("config.zig");
-pub const pdf_enabled = panes.Pdf.enabled;
-pub const pdf = panes.Pdf.pdf;
pub const memory = @import("memory.zig");
pub const tape = @import("tape.zig");
pub const walk = @import("walk.zig");
@@ -111,24 +109,15 @@ pub const can_attach = platform == .tui or platform == .gui;
pub const fonts = if (font_picker) @import("fonts.zig") else struct {};
-pub const PdfRasterPolicy = panes.Pdf.RasterPolicy;
-
-pub const kitty_pdf_raster_policy: PdfRasterPolicy = .{
- .dpi = 96,
- .max_dimension = 1200,
- .match_viewport = false,
-};
-pub const sdl_pdf_raster_policy: PdfRasterPolicy = .{
- .dpi = 192,
- .max_dimension = 4096,
- .match_viewport = true,
-};
-pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) {
- .tui => kitty_pdf_raster_policy,
- // Both pixel shells rasterize for a real display and can afford it; the
- // wire-bandwidth argument that shapes the Kitty policy does not apply.
- .gui, .macos => sdl_pdf_raster_policy,
-};
+/// The raster a frontend wants a kind's picture at (Kind.viewOf, a
+/// `pa_view`): a terminal's kitty images go down a wire, so smaller; a
+/// window rasterizes for its display.
+pub const RasterPolicy = struct { dpi: u16, max_dimension: u16, match_viewport: bool };
+/// A view's: a window's denser than a terminal's. By the view's frontend,
+/// never the build's, so every core of a session asks a kind alike.
+pub fn rasterPolicy(windowed: bool) RasterPolicy {
+ return if (windowed) .{ .dpi = 192, .max_dimension = 4096, .match_viewport = true } else .{ .dpi = 96, .max_dimension = 1200, .match_viewport = false };
+}
pub const Pane = panes.Pane;
const Text = panes.Text;
@@ -149,7 +138,6 @@ pub const MAX_TAG_ROWS = 8;
/// bands: a band to a tag, however many lines it has.
pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1 + MAX_PANES * Pane.Notices.max;
pub const NOTICE_LAYER_BASE = MAX_PANES + MAX_COLS + 1;
-pub const PDF_PAGE_GAP_PX = panes.Pdf.page_gap_px;
/// Columns a session holds (each costs about 8 KB of state, a column tag
/// being most of it).
pub const MAX_COLS = 16;
diff --git a/src/pdf.zig b/src/pdf.zig
deleted file mode 100644
index 7cfb86d5..00000000
--- a/src/pdf.zig
+++ /dev/null
@@ -1,1904 +0,0 @@
-//! Exception-safe MuPDF runtime wrapper. MuPDF's public API throws with
-//! setjmp/longjmp; pdf_bridge.c catches every such throw before control returns
-//! to Zig. This module is present in native builds unless `-Dmupdf=false`.
-const std = @import("std");
-const c_heap = @import("c_heap");
-
-const c = @import("pdf_c"); // src/pdf_bridge.h, translated by build.zig
-
-/// What MuPDF allocates from, itself and the libraries it bundles (they all
-/// allocate through its context): `start`'s allocator, through the shared C
-/// heap. MuPDF's allocator functions carry a user pointer the heap does not
-/// need.
-var bridge_allocator: std.mem.Allocator = undefined;
-const bridge_heap = c_heap.Heap(&bridge_allocator);
-var bridge_started = false;
-
-fn bridgeAlloc(_: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
- return bridge_heap.malloc(size);
-}
-
-fn bridgeRealloc(_: ?*anyopaque, block: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
- return bridge_heap.realloc(block, size);
-}
-
-fn bridgeFree(_: ?*anyopaque, block: ?*anyopaque) callconv(.c) void {
- bridge_heap.free(block);
-}
-
-/// Installs the allocator used by all subsequently opened PDF documents and
-/// by MuPDF itself. Call once before opening any documents.
-pub fn start(allocator: std.mem.Allocator) void {
- if (bridge_started) @panic("PDF allocator is already started");
- bridge_allocator = allocator;
- const descriptor = c.pardes_pdf_allocator{
- .user = null,
- .alloc = bridgeAlloc,
- .realloc = bridgeRealloc,
- .free = bridgeFree,
- };
- if (c.pardes_pdf_set_allocator(&descriptor) != c.PARDES_PDF_OK)
- @panic("cannot start PDF allocator while documents are live");
- bridge_started = true;
-}
-
-/// Restores libc and MuPDF's default allocator. Every Document must have been
-/// destroyed first so no allocation can outlive its allocator domain.
-pub fn stop() void {
- if (!bridge_started) @panic("PDF allocator is not started");
- if (c.pardes_pdf_set_allocator(null) != c.PARDES_PDF_OK)
- @panic("cannot stop PDF allocator while documents are live");
- bridge_started = false;
- bridge_allocator = undefined;
-}
-
-test "custom allocator owns a complete PDF document lifecycle" {
- start(std.testing.allocator);
- defer stop();
-
- var document = try openTestFile("docs/design.pdf");
- defer document.deinit();
- const raster = try document.render(std.testing.allocator, 0, .{}, &.{});
- defer std.testing.allocator.free(raster.rgba);
- try std.testing.expect(raster.rgba.len > 0);
-}
-
-test "two lanes render two pages of one document at once, each as the base renders it, and a cookie aborts" {
- const gpa = std.testing.allocator;
- var base = try openTestFile("docs/design.pdf");
- defer base.deinit();
- try std.testing.expect(base.pages >= 2);
- const Lane = struct {
- doc: Document,
- page: usize,
- out: ?Render = null,
- fn run(lane: *@This()) void {
- lane.doc.laneOpen() catch return;
- lane.out = lane.doc.render(std.testing.allocator, lane.page, .{}, &.{}) catch null;
- }
- };
- // Cloned on the base's thread; each lane's document opened on its own.
- var lanes = [2]Lane{ .{ .doc = try base.laneClone(), .page = 0 }, .{ .doc = try base.laneClone(), .page = 1 } };
- defer for (&lanes) |*lane| {
- if (lane.out) |r| gpa.free(r.rgba);
- lane.doc.deinit();
- };
- var threads: [2]std.Thread = undefined;
- for (&threads, &lanes) |*t, *lane| t.* = try std.Thread.spawn(.{}, Lane.run, .{lane});
- for (threads) |t| t.join();
- for (lanes) |lane| {
- const want = try base.render(gpa, lane.page, .{}, &.{});
- defer gpa.free(want.rgba);
- try std.testing.expect(std.mem.eql(u8, want.rgba, lane.out.?.rgba));
- }
- // An abort set before the run stops it at its first operator.
- var cookie = std.mem.zeroes(Cookie);
- cookie.abort = 1;
- lanes[0].doc.setCookie(&cookie);
- try std.testing.expectError(error.Aborted, lanes[0].doc.render(gpa, 1, .{}, &.{}));
- lanes[0].doc.setCookie(null);
-}
-
-/// One raster-quality request. `minimum_*` asks MuPDF for enough source pixels
-/// to avoid backend upscaling; `max_dimension` caps a raster row always, and
-/// the page's height unless that would draw it below `display_*`, the size
-/// the page is shown at (0: no floor). A page taller than that is never one
-/// allocation: its owner renders bands of it (`Raster.band`).
-pub const RenderRequest = struct {
- dpi: u16 = 144,
- minimum_width: u32 = 0,
- minimum_height: u32 = 0,
- max_dimension: u16 = 1600,
- display_width: u32 = 0,
- display_height: u32 = 0,
-
- pub fn eql(a: RenderRequest, b: RenderRequest) bool {
- return std.meta.eql(a, b);
- }
-};
-
-pub const absolute_max_render_dimension: u16 = 4096;
-/// The most one render buffer holds: a whole page, or one band of a page
-/// taller than this.
-pub const max_owned_raster_bytes: usize = @as(usize, absolute_max_render_dimension) *
- absolute_max_render_dimension * 4;
-/// Maximum native outline rows accepted atomically from one document.
-pub const max_outline_items: usize = c.PARDES_PDF_MAX_OUTLINE_ITEMS;
-
-/// Page-space geometry is normalized to the page bounds, not a render. It
-/// therefore survives DPI changes and can be shared by Kitty and SDL.
-pub const Cookie = c.pardes_pdf_cookie;
-pub const Point = c.pardes_pdf_point;
-pub const Quad = c.pardes_pdf_quad;
-
-pub const HighlightKind = enum(c_int) {
- custom = c.PARDES_PDF_HIGHLIGHT_CUSTOM,
- search = c.PARDES_PDF_HIGHLIGHT_SEARCH,
- selection = c.PARDES_PDF_HIGHLIGHT_SELECTION,
-};
-
-/// RGBA is straight (not premultiplied). `kind` remains available to the UI as
-/// semantic metadata; the caller-supplied RGBA is authoritative for rendering.
-pub const Highlight = extern struct {
- quad: Quad,
- rgba: [4]u8,
- kind: HighlightKind,
-
- pub fn init(quad: Quad, rgba: [4]u8, kind: HighlightKind) Highlight {
- return .{ .quad = quad, .rgba = rgba, .kind = kind };
- }
-};
-
-comptime {
- if (@sizeOf(Highlight) != @sizeOf(c.pardes_pdf_highlight) or
- @alignOf(Highlight) != @alignOf(c.pardes_pdf_highlight) or
- @offsetOf(Highlight, "quad") != @offsetOf(c.pardes_pdf_highlight, "quad") or
- @offsetOf(Highlight, "rgba") != @offsetOf(c.pardes_pdf_highlight, "rgba") or
- @offsetOf(Highlight, "kind") != @offsetOf(c.pardes_pdf_highlight, "kind"))
- @compileError("Highlight must match pardes_pdf_highlight's C ABI");
-}
-
-pub const Render = struct {
- rgba: []u8,
- width: usize,
- height: usize,
-};
-
-/// Pane-local PDF color treatment. The core owns when this changes; keeping
-/// the pixel transform here lets the renderer benchmark and any future PDF
-/// consumer exercise exactly the same fixed-point rule.
-pub const TintMode = enum {
- disabled,
- filtered,
- full,
-
- pub fn next(mode: TintMode) TintMode {
- return switch (mode) {
- .disabled => .filtered,
- .filtered => .full,
- .full => .disabled,
- };
- }
-};
-
-pub const TintColors = struct {
- background: [3]u8,
- foreground: [3]u8,
-};
-
-fn tintTargets(colors: TintColors) [256][3]u8 {
- var targets: [256][3]u8 = undefined;
- for (&targets, 0..) |*target, luminance| {
- inline for (0..3) |channel| {
- target[channel] = @intCast(
- (@as(u32, colors.foreground[channel]) * @as(u32, @intCast(255 - luminance)) +
- @as(u32, colors.background[channel]) * @as(u32, @intCast(luminance)) + 127) / 255,
- );
- }
- }
- return targets;
-}
-
-const tint_chroma_residuals: [511]i16 = table: {
- var values: [511]i16 = undefined;
- for (&values, 0..) |*value, index| {
- const residual: i16 = @as(i16, @intCast(index)) - 255;
- value.* = @divTrunc(residual * 3, 4);
- }
- break :table values;
-};
-
-const tint_clamped_sums: [638]u8 = table: {
- @setEvalBranchQuota(2000);
- var values: [638]u8 = undefined;
- for (&values, 0..) |*value, index| {
- const sum: i16 = @as(i16, @intCast(index)) - 191;
- value.* = @intCast(std.math.clamp(sum, 0, 255));
- }
- break :table values;
-};
-
-inline fn filteredTintChannel(target: u8, source: u8, residual_base: i16) u8 {
- const chroma = tint_chroma_residuals[@intCast(residual_base + source)];
- return tint_clamped_sums[@intCast(@as(i16, target) + chroma + 191)];
-}
-
-/// Rewrite packed straight-alpha RGBA in place without allocating.
-///
-/// Source luminance is Rec. 601's 77/150/29 integer approximation. `full`
-/// linearly maps source black to theme foreground and source white to theme
-/// background. `filtered` starts with that same themed target, then adds 3/4
-/// of each source channel's signed distance from source luminance, clamped to
-/// a byte. Thus grayscale is identical in both modes while filtered color
-/// retains the source hue/chroma. Alpha is never touched.
-pub fn tintRgba(rgba: []u8, mode: TintMode, colors: TintColors) !void {
- if (rgba.len % 4 != 0) return error.InvalidRgbaLength;
- if (mode == .disabled) return;
-
- const targets = tintTargets(colors);
- const pixels = std.mem.bytesAsSlice([4]u8, rgba);
- switch (mode) {
- .disabled => unreachable,
- .full => tintPixels(pixels, .full, &targets),
- .filtered => tintPixels(pixels, .filtered, &targets),
- }
-}
-
-/// The whole rule for ONE pixel, and the reason the memo below is exact: the
-/// transform reads nothing but this packed word, and alpha rides through
-/// untouched, so the word is a complete cache key.
-inline fn tintPixel(word: u32, comptime mode: TintMode, targets: *const [256][3]u8) u32 {
- var pixel: [4]u8 = @bitCast(word);
- const red = pixel[0];
- const green = pixel[1];
- const blue = pixel[2];
- const luminance: u8 = @intCast((@as(u32, red) * 77 +
- @as(u32, green) * 150 +
- @as(u32, blue) * 29 + 128) >> 8);
- const target = targets[luminance];
- switch (mode) {
- .disabled => comptime unreachable,
- .full => {
- pixel[0] = target[0];
- pixel[1] = target[1];
- pixel[2] = target[2];
- },
- .filtered => {
- const residual_base: i16 = 255 - @as(i16, luminance);
- pixel[0] = filteredTintChannel(target[0], red, residual_base);
- pixel[1] = filteredTintChannel(target[1], green, residual_base);
- pixel[2] = filteredTintChannel(target[2], blue, residual_base);
- },
- }
- return @bitCast(pixel);
-}
-
-/// Alpha-less packed tint for every grayscale level. See tintWord: this one
-/// table serves BOTH modes, which is why it takes no mode.
-fn grayTintTable(targets: *const [256][3]u8) [256]u32 {
- var table: [256]u32 = undefined;
- for (&table, targets) |*word, target|
- word.* = @bitCast([4]u8{ target[0], target[1], target[2], 0 });
- return table;
-}
-
-const tint_alpha_mask: u32 = @bitCast([4]u8{ 0, 0, 0, 0xff });
-
-/// One pixel, with the two shortcuts that make a full-page tint affordable.
-///
-/// Rec. 601's integer weights sum to exactly 256, so for r == g == b the
-/// luminance dot product is the channel value itself, and `filtered`'s chroma
-/// residual is then exactly zero — both modes collapse to the themed target
-/// for that level. A text page's raster is overwhelmingly grayscale, so this
-/// arm carries almost every pixel at one table load. Colour falls through to
-/// the general rule, unchanged.
-inline fn tintWord(
- word: u32,
- comptime mode: TintMode,
- targets: *const [256][3]u8,
- gray: *const [256]u32,
-) u32 {
- const pixel: [4]u8 = @bitCast(word);
- if (pixel[0] == pixel[1] and pixel[1] == pixel[2])
- return gray[pixel[0]] | (word & tint_alpha_mask);
- return tintPixel(word, mode, targets);
-}
-
-/// Pixels per run test. Sixteen is four SSE2 registers: one branch says
-/// "this whole span repeats the previous pixel", which is the shape of the
-/// paper margins and of any flat fill.
-const tint_run_pixels = 16;
-
-/// A rasterized page is mostly flat — paper, then runs of one ink value — and
-/// the transform reads nothing but the packed word, so a one-entry memo tested
-/// a span at a time turns those runs into one comparison and one store. That,
-/// plus the grayscale collapse above, is what lets a fling afford to tint a
-/// whole freshly rasterized page inside a single frame. Colour-photographic
-/// content pays the span comparison and nothing else; the arithmetic is
-/// byte-for-byte the scalar rule in every arm.
-fn tintPixels(pixels: [][4]u8, comptime mode: TintMode, targets: *const [256][3]u8) void {
- const gray = grayTintTable(targets);
- const Run = @Vector(tint_run_pixels, u32);
- var memo_key: u32 = undefined;
- var memo_value: u32 = undefined;
- var memo_valid = false;
- var at: usize = 0;
- while (at + tint_run_pixels <= pixels.len) : (at += tint_run_pixels) {
- const span = pixels[at..][0..tint_run_pixels];
- if (memo_valid) {
- const words: Run = @bitCast(span.*);
- if (@reduce(.And, words == @as(Run, @splat(memo_key)))) {
- span.* = @bitCast(@as(Run, @splat(memo_value)));
- continue;
- }
- }
- for (span) |*pixel| {
- memo_key = @bitCast(pixel.*);
- memo_value = tintWord(memo_key, mode, targets, &gray);
- pixel.* = @bitCast(memo_value);
- }
- memo_valid = true;
- }
- while (at < pixels.len) : (at += 1) {
- const pixel = &pixels[at];
- const word: u32 = @bitCast(pixel.*);
- pixel.* = @bitCast(tintWord(word, mode, targets, &gray));
- }
-}
-
-fn tintRgbaReference(rgba: []u8, mode: TintMode, colors: TintColors) !void {
- if (rgba.len % 4 != 0) return error.InvalidRgbaLength;
- if (mode == .disabled) return;
- var at: usize = 0;
- while (at < rgba.len) : (at += 4) {
- const source = rgba[at..][0..3];
- const luminance: u8 = @intCast((@as(u32, source[0]) * 77 +
- @as(u32, source[1]) * 150 +
- @as(u32, source[2]) * 29 + 128) >> 8);
- for (0..3) |channel| {
- const target: i32 = @intCast((@as(u32, colors.foreground[channel]) * (255 - @as(u32, luminance)) +
- @as(u32, colors.background[channel]) * @as(u32, luminance) + 127) / 255);
- const chroma = if (mode == .filtered)
- @divTrunc(
- (@as(i32, source[channel]) - @as(i32, luminance)) * 3,
- 4,
- )
- else
- 0;
- rgba[at + channel] = @intCast(std.math.clamp(target + chroma, 0, 255));
- }
- }
-}
-
-fn tintTestByte(state: *u64) u8 {
- state.* = state.* *% 6364136223846793005 +% 1442695040888963407;
- return @truncate(state.* >> 32);
-}
-
-test "PDF tint lookup tables are exact over every signed chroma residual" {
- for (tint_chroma_residuals, 0..) |actual, index| {
- const residual: i16 = @as(i16, @intCast(index)) - 255;
- try std.testing.expectEqual(@divTrunc(residual * 3, 4), actual);
- }
- for (tint_clamped_sums, 0..) |actual, index| {
- const sum: i16 = @as(i16, @intCast(index)) - 191;
- try std.testing.expectEqual(
- @as(u8, @intCast(std.math.clamp(sum, 0, 255))),
- actual,
- );
- }
-}
-
-test "optimized PDF tint matches scalar rule for every endpoint combination" {
- const modes = [_]TintMode{ .full, .filtered };
- for (0..8) |background_mask| {
- for (0..8) |foreground_mask| {
- const colors: TintColors = .{
- .background = .{
- if (background_mask & 1 == 0) 0 else 255,
- if (background_mask & 2 == 0) 0 else 255,
- if (background_mask & 4 == 0) 0 else 255,
- },
- .foreground = .{
- if (foreground_mask & 1 == 0) 0 else 255,
- if (foreground_mask & 2 == 0) 0 else 255,
- if (foreground_mask & 4 == 0) 0 else 255,
- },
- };
- var source: [8 * 2 * 4]u8 = undefined;
- var at: usize = 0;
- for (0..8) |source_mask| {
- for ([_]u8{ 0, 255 }) |alpha| {
- source[at..][0..4].* = .{
- if (source_mask & 1 == 0) 0 else 255,
- if (source_mask & 2 == 0) 0 else 255,
- if (source_mask & 4 == 0) 0 else 255,
- alpha,
- };
- at += 4;
- }
- }
- for (modes) |mode| {
- var expected = source;
- var actual = source;
- try tintRgbaReference(&expected, mode, colors);
- try tintRgba(&actual, mode, colors);
- try std.testing.expectEqualSlices(u8, &expected, &actual);
- }
- }
- }
-}
-
-test "optimized PDF tint matches scalar rule across deterministic broad samples" {
- const modes = [_]TintMode{ .full, .filtered };
- var state: u64 = 0x7061_7264_6573_5449;
- for (0..64) |_| {
- const colors: TintColors = .{
- .background = .{ tintTestByte(&state), tintTestByte(&state), tintTestByte(&state) },
- .foreground = .{ tintTestByte(&state), tintTestByte(&state), tintTestByte(&state) },
- };
- var source: [512 * 4]u8 = undefined;
- for (&source) |*byte| byte.* = tintTestByte(&state);
- for (modes) |mode| {
- var expected = source;
- var actual = source;
- try tintRgbaReference(&expected, mode, colors);
- try tintRgba(&actual, mode, colors);
- try std.testing.expectEqualSlices(u8, &expected, &actual);
- }
- }
-}
-
-// The memo, its tint_run_pixels span test, and the grayscale collapse only
-// engage on repeated or achromatic pixels, and the span loop leaves a tail on
-// any pixel count that is not a multiple of tint_run_pixels. None of that is
-// visible to the random corpus above, so drive flat runs, run boundaries, and
-// every remainder against the reference rule directly.
-test "optimized PDF tint matches scalar rule across runs, boundaries, and every tail" {
- const modes = [_]TintMode{ .full, .filtered };
- const colors: TintColors = .{
- .background = .{ 0x08, 0x12, 0x2a },
- .foreground = .{ 0xbd, 0xa4, 0x71 },
- };
- // Paper, ink, antialiased edge, saturated colour, and a transparent pixel
- // that shares its RGB with an opaque one — the memo key must include alpha
- // or that pair would tint from one cached word.
- const palette = [_][4]u8{
- .{ 0xff, 0xff, 0xff, 0xff },
- .{ 0x00, 0x00, 0x00, 0xff },
- .{ 0x7f, 0x80, 0x81, 0xff },
- .{ 0xff, 0x00, 0x00, 0xff },
- .{ 0xff, 0xff, 0xff, 0x00 },
- };
- var state: u64 = 0x7061_7264_6573_5254;
- var pixels: [37][4]u8 = undefined;
- for (0..96) |round| {
- // Alternate long flat runs against pixel-by-pixel churn so the block
- // fast path, the per-pixel memo, and the miss path all run.
- var run_left: usize = 0;
- var current: [4]u8 = palette[round % palette.len];
- for (&pixels) |*pixel| {
- if (run_left == 0) {
- run_left = 1 + (tintTestByte(&state) % 9);
- current = if (tintTestByte(&state) & 3 == 0)
- .{ tintTestByte(&state), tintTestByte(&state), tintTestByte(&state), tintTestByte(&state) }
- else
- palette[tintTestByte(&state) % palette.len];
- }
- run_left -= 1;
- pixel.* = current;
- }
- for (0..pixels.len + 1) |count| {
- const source = std.mem.sliceAsBytes(pixels[0..count]);
- for (modes) |mode| {
- var expected: [pixels.len * 4]u8 = undefined;
- var actual: [pixels.len * 4]u8 = undefined;
- @memcpy(expected[0..source.len], source);
- @memcpy(actual[0..source.len], source);
- try tintRgbaReference(expected[0..source.len], mode, colors);
- try tintRgba(actual[0..source.len], mode, colors);
- try std.testing.expectEqualSlices(u8, expected[0..source.len], actual[0..source.len]);
- }
- }
- }
-}
-
-test "PDF tint mode cycle is exact" {
- try std.testing.expectEqual(TintMode.filtered, TintMode.disabled.next());
- try std.testing.expectEqual(TintMode.full, TintMode.filtered.next());
- try std.testing.expectEqual(TintMode.disabled, TintMode.full.next());
-}
-
-test "full PDF tint maps black and white to dark and light theme endpoints" {
- const dark: TintColors = .{
- .background = .{ 0x12, 0x12, 0x12 },
- .foreground = .{ 0x94, 0x94, 0x94 },
- };
- var dark_pixels = [_]u8{ 0, 0, 0, 17, 255, 255, 255, 231 };
- try tintRgba(&dark_pixels, .full, dark);
- try std.testing.expectEqualSlices(u8, &.{ 0x94, 0x94, 0x94, 17 }, dark_pixels[0..4]);
- try std.testing.expectEqualSlices(u8, &.{ 0x12, 0x12, 0x12, 231 }, dark_pixels[4..8]);
-
- const light: TintColors = .{
- .background = .{ 0xea, 0xff, 0xff },
- .foreground = .{ 0x00, 0x00, 0x00 },
- };
- var light_pixels = [_]u8{ 0, 0, 0, 0, 255, 255, 255, 255 };
- try tintRgba(&light_pixels, .full, light);
- try std.testing.expectEqualSlices(u8, &.{ 0x00, 0x00, 0x00, 0 }, light_pixels[0..4]);
- try std.testing.expectEqualSlices(u8, &.{ 0xea, 0xff, 0xff, 255 }, light_pixels[4..8]);
-}
-
-test "filtered PDF tint preserves fixed-point source chroma and alpha" {
- const colors: TintColors = .{
- .background = .{ 20, 40, 60 },
- .foreground = .{ 220, 200, 180 },
- };
- var full = [_]u8{ 255, 0, 0, 37 };
- var filtered = full;
- try tintRgba(&full, .full, colors);
- try tintRgba(&filtered, .filtered, colors);
- // Red has integer luma 77. The themed target is {160,152,144}; adding
- // 3/4 of its {178,-77,-77} chroma residual yields this clamped result.
- try std.testing.expectEqualSlices(u8, &.{ 160, 152, 144, 37 }, &full);
- try std.testing.expectEqualSlices(u8, &.{ 255, 95, 87, 37 }, &filtered);
-
- var gray_full = [_]u8{ 128, 128, 128, 91 };
- var gray_filtered = gray_full;
- try tintRgba(&gray_full, .full, colors);
- try tintRgba(&gray_filtered, .filtered, colors);
- try std.testing.expectEqualSlices(u8, &gray_full, &gray_filtered);
- try std.testing.expectEqual(@as(u8, 91), gray_filtered[3]);
-}
-
-test "disabled PDF tint is byte-identical and malformed RGBA is rejected unchanged" {
- const colors: TintColors = .{
- .background = .{ 1, 2, 3 },
- .foreground = .{ 4, 5, 6 },
- };
- var pixels = [_]u8{ 9, 80, 170, 0, 250, 33, 71, 199 };
- const before = pixels;
- try tintRgba(&pixels, .disabled, colors);
- try std.testing.expectEqualSlices(u8, &before, &pixels);
-
- var malformed = [_]u8{ 11, 22, 33 };
- const malformed_before = malformed;
- try std.testing.expectError(error.InvalidRgbaLength, tintRgba(&malformed, .full, colors));
- try std.testing.expectEqualSlices(u8, &malformed_before, &malformed);
-}
-
-pub const PageSize = struct {
- width: f32,
- height: f32,
-};
-
-pub const SearchQuad = struct {
- quad: Quad,
- /// Zero-based logical hit. One hit may have several oriented quads.
- hit: usize,
-};
-
-pub const SearchResults = struct {
- quads: []SearchQuad,
- hit_count: usize,
-
- pub fn deinit(results: *SearchResults, gpa: std.mem.Allocator) void {
- gpa.free(results.quads);
- results.* = undefined;
- }
-};
-
-pub const Selection = struct {
- quads: []Quad,
- /// Word-snapped endpoints; pass these to `Document.copySelection`.
- start: Point,
- end: Point,
-
- /// Hit-test without flattening oriented text quads to axis-aligned boxes.
- /// The bridge delegates to MuPDF's geometry predicate and cannot throw.
- pub fn contains(selection: *const Selection, point: Point) bool {
- if (!validPoint(point)) return false;
- for (selection.quads) |quad| {
- if (c.pardes_pdf_point_inside_quad(point, quad) != 0) return true;
- }
- return false;
- }
-
- pub fn deinit(selection: *Selection, gpa: std.mem.Allocator) void {
- gpa.free(selection.quads);
- selection.* = undefined;
- }
-};
-
-pub const OutlineInternalDestination = struct {
- /// Zero-based document page number.
- page: usize,
- /// MuPDF page-space viewing coordinates; null when the PDF destination
- /// omits that axis (for example, a Fit destination omits both).
- x: ?f32,
- y: ?f32,
-};
-
-pub const OutlineDestination = union(enum) {
- none,
- internal: OutlineInternalDestination,
- external: []const u8,
-};
-
-pub const Link = struct {
- page: usize,
- quad: Quad,
- /// Owned independently of the document's current-page cache. External
- /// destination slices point into this same allocation.
- uri: []u8,
- destination: OutlineDestination,
-
- pub fn deinit(link: *Link, gpa: std.mem.Allocator) void {
- gpa.free(link.uri);
- link.* = undefined;
- }
-};
-
-pub const OutlineEntry = struct {
- /// Zero for a root row; rows are in stable pre-order depth-first order.
- depth: u8,
- /// Null preserves a missing /Title; a present empty title is "".
- title: ?[]const u8,
- destination: OutlineDestination,
-};
-
-/// All title and external-URI slices point into `bytes`. This fixed two-allocation
-/// representation avoids one allocation per row while keeping deinit deterministic.
-pub const Outline = struct {
- entries: []OutlineEntry,
- bytes: []u8,
-
- pub fn deinit(outline: *Outline, gpa: std.mem.Allocator) void {
- gpa.free(outline.entries);
- gpa.free(outline.bytes);
- outline.* = undefined;
- }
-};
-
-test "oriented selection containment delegates to MuPDF quad geometry" {
- const quads = [_]Quad{.{
- .ul = .{ .x = 0.10, .y = 0.10 },
- .ur = .{ .x = 0.70, .y = 0.20 },
- .ll = .{ .x = 0.20, .y = 0.80 },
- .lr = .{ .x = 0.80, .y = 0.90 },
- }};
- const selection = Selection{
- .quads = @constCast(quads[0..]),
- .start = quads[0].ul,
- .end = quads[0].lr,
- };
- try std.testing.expect(selection.contains(.{ .x = 0.45, .y = 0.50 }));
- try std.testing.expect(!selection.contains(.{ .x = 0.05, .y = 0.85 }));
- try std.testing.expect(!selection.contains(.{ .x = -0.1, .y = 0.5 }));
-}
-
-pub const Document = struct {
- /// None in a document loaded from a dump until its PDF is opened again
- /// (pdf_view.reopen).
- handle: ?*c.pardes_pdf_document = null,
- pages: usize,
-
- /// The open document is MuPDF's, made from the file's bytes (src/walk.zig).
- pub const replica = .{ .derived = .{"handle"} };
-
- pub fn deinit(document: *Document) void {
- c.pardes_pdf_close(document.handle);
- document.* = undefined;
- }
-
- pub fn openBytes(bytes: []const u8) !Document {
- var page_count: c_int = 0;
- const handle = c.pardes_pdf_open_memory(bytes.ptr, bytes.len, &page_count) orelse
- return error.OpenFailed;
- return .{ .handle = handle, .pages = @intCast(page_count) };
- }
-
- /// A render lane of this document (`pardes_pdf_lane_clone`): its own
- /// cloned context, its own document opened (`laneOpen`) on the thread
- /// that renders with it. Deinit every lane before `base`.
- pub fn laneClone(base: *Document) !Document {
- const handle = c.pardes_pdf_lane_clone(base.handle) orelse return error.OpenFailed;
- return .{ .handle = handle, .pages = base.pages };
- }
-
- pub fn laneOpen(lane: *Document) !void {
- if (c.pardes_pdf_lane_open(lane.handle) != c.PARDES_PDF_OK) return error.OpenFailed;
- }
-
- /// The cookie this document's renders run under until set again: set
- /// its `abort` from any thread and a render stops at its next operator
- /// (`error.Aborted`).
- pub fn setCookie(document: *Document, cookie: ?*Cookie) void {
- c.pardes_pdf_set_cookie(document.handle, cookie);
- }
-
- /// Link annotations are loaded only for the pointed page, separately from
- /// text/raster work. Returned URIs survive cache eviction and page changes.
- pub fn linkAt(document: *Document, gpa: std.mem.Allocator, page: usize, point: Point) !?Link {
- const page_number = try document.checkedPage(page);
- if (!validPoint(point)) return null;
- var raw: c.pardes_pdf_link = std.mem.zeroes(c.pardes_pdf_link);
- if (c.pardes_pdf_link_at(document.handle, page_number, point, &raw) != c.PARDES_PDF_OK)
- return error.LinkFailed;
- if (raw.uri == null or raw.uri_len == 0) return null;
- if (raw.uri_len > c.PARDES_PDF_MAX_LINK_URI_BYTES or !validQuad(raw.quad)) return error.BadLink;
- const borrowed: [*]const u8 = @ptrCast(raw.uri);
- const text = borrowed[0..raw.uri_len];
- if (!std.unicode.utf8ValidateSlice(text) or std.mem.trim(u8, text, " ").len == 0 or
- std.ascii.eqlIgnoreCase(text, "file://")) return null;
- for (text) |byte| if (byte < ' ') return null;
- const uri = try gpa.dupe(u8, text);
- errdefer gpa.free(uri);
- const destination: OutlineDestination = switch (raw.destination_kind) {
- c.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL => blk: {
- if (raw.page < 0 or @as(usize, @intCast(raw.page)) >= document.pages or
- raw.has_x > 1 or raw.has_y > 1 or
- (raw.has_x != 0 and !std.math.isFinite(raw.x)) or
- (raw.has_y != 0 and !std.math.isFinite(raw.y))) return error.BadLink;
- break :blk .{ .internal = .{
- .page = @intCast(raw.page),
- .x = if (raw.has_x != 0) raw.x else null,
- .y = if (raw.has_y != 0) raw.y else null,
- } };
- },
- c.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL => .{ .external = uri },
- else => return error.BadLink,
- };
- return .{ .page = page, .quad = raw.quad, .uri = uri, .destination = destination };
- }
-
- pub fn copyRectangle(document: *Document, gpa: std.mem.Allocator, page: usize, quad: Quad) ![]u8 {
- const page_number = try document.checkedPage(page);
- if (!validQuad(quad)) return error.InvalidPoint;
- var text: c.pardes_pdf_owned_text = std.mem.zeroes(c.pardes_pdf_owned_text);
- if (c.pardes_pdf_copy_rectangle(document.handle, page_number, quad, &text) != c.PARDES_PDF_OK)
- return error.SelectionFailed;
- defer c.pardes_pdf_drop_owned_text(document.handle, text.handle);
- if (text.len == 0) return &.{};
- if (text.data == null) return error.BadText;
- const source: [*]const u8 = @ptrCast(text.data);
- return gpa.dupe(u8, source[0..text.len]);
- }
-
- /// Load and flatten the PDF-native outline/bookmarks. MuPDF's temporary
- /// tree and the bridge's flat view are both dropped before this returns.
- pub fn outline(
- document: *Document,
- gpa: std.mem.Allocator,
- ) !Outline {
- var raw: c.pardes_pdf_outline_result =
- std.mem.zeroes(c.pardes_pdf_outline_result);
- const status = c.pardes_pdf_load_outline(document.handle, &raw);
- if (status == c.PARDES_PDF_LIMIT_EXCEEDED)
- return error.OutlineLimitExceeded;
- if (status != c.PARDES_PDF_OK)
- return error.OutlineFailed;
- defer c.pardes_pdf_drop_outline_result(document.handle, raw.handle);
-
- if (raw.item_count > c.PARDES_PDF_MAX_OUTLINE_ITEMS or
- raw.bytes_len > c.PARDES_PDF_MAX_OUTLINE_BYTES or
- (raw.item_count != 0 and raw.items == null) or
- (raw.bytes_len != 0 and raw.bytes == null))
- return error.BadOutline;
-
- const bytes = try gpa.alloc(u8, raw.bytes_len);
- errdefer gpa.free(bytes);
- if (raw.bytes_len != 0) {
- const source: [*]const u8 = @ptrCast(raw.bytes);
- @memcpy(bytes, source[0..raw.bytes_len]);
- }
-
- const entries = try gpa.alloc(OutlineEntry, raw.item_count);
- errdefer gpa.free(entries);
- if (raw.item_count != 0) {
- const source: [*]const c.pardes_pdf_outline_item =
- @ptrCast(raw.items);
- var previous_depth: u8 = 0;
- for (entries, source[0..raw.item_count], 0..) |*entry, item, index| {
- if (item.depth >= c.PARDES_PDF_MAX_OUTLINE_DEPTH or
- item.depth > std.math.maxInt(u8) or
- item.title_present > 1 or item.has_x > 1 or
- item.has_y > 1)
- return error.BadOutline;
- const depth: u8 = @intCast(item.depth);
- if ((index == 0 and depth != 0) or
- (index != 0 and depth > previous_depth + 1))
- return error.BadOutline;
- previous_depth = depth;
-
- const title = if (item.title_present != 0) title: {
- const value = try outlineBytes(bytes, item.title_offset, item.title_len);
- if (!std.unicode.utf8ValidateSlice(value))
- return error.BadOutline;
- break :title value;
- } else title: {
- if (item.title_offset != 0 or item.title_len != 0)
- return error.BadOutline;
- break :title null;
- };
-
- const destination: OutlineDestination = switch (item.destination_kind) {
- c.PARDES_PDF_OUTLINE_DESTINATION_NONE => .none,
- c.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL => internal: {
- if (item.page < 0 or
- @as(usize, @intCast(item.page)) >= document.pages or
- (item.has_x != 0 and !std.math.isFinite(item.x)) or
- (item.has_y != 0 and !std.math.isFinite(item.y)))
- return error.BadOutline;
- break :internal .{ .internal = .{
- .page = @intCast(item.page),
- .x = if (item.has_x != 0) item.x else null,
- .y = if (item.has_y != 0) item.y else null,
- } };
- },
- c.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL => external: {
- const uri = try outlineBytes(bytes, item.uri_offset, item.uri_len);
- if (!std.unicode.utf8ValidateSlice(uri))
- return error.BadOutline;
- break :external .{ .external = uri };
- },
- else => return error.BadOutline,
- };
- entry.* = .{ .depth = depth, .title = title, .destination = destination };
- }
- }
- return .{ .entries = entries, .bytes = bytes };
- }
-
- /// Return crop/rotation-aware page dimensions without allocating pixels.
- pub fn pageSize(document: *Document, page: usize) !PageSize {
- const page_number = try document.checkedPage(page);
- var size: c.pardes_pdf_page_size = std.mem.zeroes(c.pardes_pdf_page_size);
- if (c.pardes_pdf_get_page_size(document.handle, page_number, &size) != c.PARDES_PDF_OK or
- !std.math.isFinite(size.width) or !std.math.isFinite(size.height) or
- size.width <= 0 or size.height <= 0)
- return error.BadPageSize;
- return .{ .width = size.width, .height = size.height };
- }
-
- /// Render one zero-based page whole into allocator-owned packed RGBA,
- /// baking `highlights` in: the tests' and benches' render. The view
- /// renders bands into buffers it owns (`renderIntoAtWithPaper`).
- pub fn render(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- request: RenderRequest,
- highlights: []const Highlight,
- ) !Render {
- const raster = try document.measureRenderAt(page, request);
- if (raster.len > max_owned_raster_bytes) return error.PixmapTooLarge;
- const rgba = try gpa.alloc(u8, raster.len);
- errdefer gpa.free(rgba);
- try document.renderIntoAtWithPaper(page, request, raster, raster.wholePage(), highlights, rgba, false);
- return .{ .rgba = rgba, .width = raster.width, .height = raster.height };
- }
-
- /// Exactly the raster this request will produce, without producing it.
- /// Split out of the render so a caller holding a retired buffer of the
- /// same length can hand it straight back instead of making the allocator
- /// fetch (and later return) fresh pages for every page it flies past.
- pub fn measureRenderAt(
- document: *Document,
- page: usize,
- request: RenderRequest,
- ) !Raster {
- const bounded = try boundedRequest(document, page, request);
- var raw_layout: c.pardes_pdf_raster_layout = std.mem.zeroes(c.pardes_pdf_raster_layout);
- if (c.pardes_pdf_measure_render(
- document.handle,
- @intCast(page),
- &bounded,
- &raw_layout,
- ) != c.PARDES_PDF_OK) return error.RenderFailed;
- // The page's shape, not an allocation: a page taller than
- // `max_owned_raster_bytes` allows is rendered a band at a time.
- return checkedRasterLayout(raw_layout);
- }
-
- /// Rasterize `band` of a page into `rgba`, which MUST be exactly
- /// `band.len` bytes for a `band` taken from the same `measureRenderAt`
- /// shape and request. On any failure the buffer's contents are unspecified
- /// and it still belongs to the caller. `transparent_paper` preserves the
- /// PDF's content coverage when the host paints paper separately.
- pub fn renderIntoAtWithPaper(
- document: *Document,
- page: usize,
- request: RenderRequest,
- raster: Raster,
- band: Raster.Band,
- highlights: []const Highlight,
- rgba: []u8,
- transparent_paper: bool,
- ) !void {
- if (rgba.len != band.len) return error.BadPixmap;
- if (band.height == 0 or band.y + band.height > raster.height)
- return error.BadPixmap;
- if (band.len > max_owned_raster_bytes) return error.PixmapTooLarge;
- const bounded = try boundedRequest(document, page, request);
- if (highlights.len > c.PARDES_PDF_MAX_RESULT_QUADS) return error.RenderFailed;
- const highlight_ptr: ?[*]const c.pardes_pdf_highlight =
- if (highlights.len == 0) null else @ptrCast(highlights.ptr);
- const status = c.pardes_pdf_render_into(
- document.handle,
- @intCast(page),
- &bounded,
- highlight_ptr,
- highlights.len,
- rgba.ptr,
- rgba.len,
- @intCast(raster.width),
- @intCast(raster.height),
- @intCast(raster.stride),
- @intCast(band.y),
- @intCast(band.height),
- @intFromBool(transparent_paper),
- );
- if (status == c.PARDES_PDF_ABORTED) return error.Aborted;
- if (status != c.PARDES_PDF_OK) return error.RenderFailed;
- }
-
- /// Only the highlight pass of `renderIntoAtWithPaper`, over `rgba`, which
- /// holds `band` of this page as that render left it before highlighting
- /// (opaque paper). Rendering with highlights equals rendering without and
- /// then this, row for row: the render draws highlights over the finished
- /// page, and so does this.
- pub fn paintHighlightsAt(
- document: *Document,
- page: usize,
- request: RenderRequest,
- raster: Raster,
- band: Raster.Band,
- highlights: []const Highlight,
- rgba: []u8,
- ) !void {
- if (rgba.len != band.len) return error.BadPixmap;
- if (band.height == 0 or band.y + band.height > raster.height)
- return error.BadPixmap;
- const bounded = try boundedRequest(document, page, request);
- if (highlights.len > c.PARDES_PDF_MAX_RESULT_QUADS) return error.RenderFailed;
- if (c.pardes_pdf_paint_highlights(
- document.handle,
- @intCast(page),
- &bounded,
- if (highlights.len == 0) null else @ptrCast(highlights.ptr),
- highlights.len,
- rgba.ptr,
- rgba.len,
- @intCast(raster.width),
- @intCast(raster.height),
- @intCast(raster.stride),
- @intCast(band.y),
- @intCast(band.height),
- ) != c.PARDES_PDF_OK) return error.RenderFailed;
- }
-
- pub const Rows = struct { start: usize, end: usize };
-
- /// The rows of `request`'s raster that painting `highlights` can touch,
- /// by the transform the render itself uses (rotation included). Empty
- /// when nothing would paint.
- pub fn highlightRows(
- document: *Document,
- page: usize,
- request: RenderRequest,
- highlights: []const Highlight,
- ) !Rows {
- const bounded = try boundedRequest(document, page, request);
- var row_start: c_int = 0;
- var row_end: c_int = 0;
- if (c.pardes_pdf_highlight_rows(
- document.handle,
- @intCast(page),
- &bounded,
- if (highlights.len == 0) null else @ptrCast(highlights.ptr),
- highlights.len,
- &row_start,
- &row_end,
- ) != c.PARDES_PDF_OK) return error.RenderFailed;
- return .{ .start = @intCast(row_start), .end = @intCast(row_end) };
- }
-
- /// `request` as the bridge takes it, refused when the page or a size is
- /// out of range.
- fn boundedRequest(
- document: *Document,
- page: usize,
- request: RenderRequest,
- ) !c.pardes_pdf_request {
- _ = try document.checkedPage(page);
- if (request.dpi == 0 or request.max_dimension == 0 or
- request.max_dimension > absolute_max_render_dimension)
- return error.InvalidRenderRequest;
- return .{
- .dpi = request.dpi,
- .minimum_width = clampInt(request.minimum_width),
- .minimum_height = clampInt(request.minimum_height),
- .max_dimension = request.max_dimension,
- .display_width = clampInt(request.display_width),
- .display_height = clampInt(request.display_height),
- };
- }
-
- fn clampInt(value: u32) c_int {
- return @intCast(@min(value, @as(u32, @intCast(std.math.maxInt(c_int)))));
- }
-
- /// Plain UTF-8-ish text projection for one zero-based page. MuPDF owns the
- /// temporary buffer; callers receive an allocator-owned copy.
- pub fn pageText(document: *Document, gpa: std.mem.Allocator, page: usize) ![]u8 {
- const page_number = try document.checkedPage(page);
- var text: c.pardes_pdf_text = std.mem.zeroes(c.pardes_pdf_text);
- if (c.pardes_pdf_page_text(document.handle, page_number, &text) != 0)
- return error.TextFailed;
- defer c.pardes_pdf_drop_text(document.handle, text.handle);
- if (text.len == 0) return gpa.dupe(u8, "");
- if (text.data == null) return error.BadText;
- const bytes: [*]const u8 = @ptrCast(text.data);
- return gpa.dupe(u8, bytes[0..text.len]);
- }
-
- /// Case-insensitive single-page search. MuPDF's iterative search owns a
- /// retained reference to the cached structured-text page while running;
- /// this wrapper copies every borrowed oriented quad before dropping it.
- /// The C bridge doubles capacity up to 65,536 aggregate quads and returns
- /// TooManyResults atomically rather than silently truncating beyond it.
- pub fn search(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- needle: []const u8,
- ) !SearchResults {
- const page_number = try document.checkedPage(page);
- if (std.mem.indexOfScalar(u8, needle, 0) != null)
- return error.InvalidNeedle;
- const needle_z = try gpa.dupeSentinel(u8, needle, 0);
- defer gpa.free(needle_z);
-
- var found: c.pardes_pdf_search_result =
- std.mem.zeroes(c.pardes_pdf_search_result);
- const status = c.pardes_pdf_search_page(document.handle, page_number, needle_z.ptr, &found);
- if (status == c.PARDES_PDF_LIMIT_EXCEEDED)
- return error.TooManyResults;
- if (status != c.PARDES_PDF_OK)
- return error.SearchFailed;
- defer c.pardes_pdf_drop_search_result(document.handle, found.handle);
-
- if (found.quad_count != 0 and found.quads == null)
- return error.BadGeometry;
- const quads = try gpa.alloc(SearchQuad, found.quad_count);
- errdefer gpa.free(quads);
- if (found.quad_count != 0) {
- const source: [*]const c.pardes_pdf_search_quad = @ptrCast(found.quads);
- for (quads, source[0..found.quad_count]) |*dest, item| {
- if (item.hit >= found.hit_count or !validQuad(item.quad))
- return error.BadGeometry;
- dest.* = .{ .quad = item.quad, .hit = item.hit };
- }
- }
- return .{ .quads = quads, .hit_count = found.hit_count };
- }
-
- /// Word-snap two normalized page points and return allocator-owned,
- /// orientation-preserving highlight geometry.
- pub fn select(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- selection_start: Point,
- selection_end: Point,
- ) !Selection {
- const page_number = try document.checkedPage(page);
- if (!validPoint(selection_start) or !validPoint(selection_end))
- return error.InvalidPoint;
-
- var selected: c.pardes_pdf_selection =
- std.mem.zeroes(c.pardes_pdf_selection);
- const status = c.pardes_pdf_select(
- document.handle,
- page_number,
- selection_start,
- selection_end,
- &selected,
- );
- if (status == c.PARDES_PDF_LIMIT_EXCEEDED)
- return error.TooManyResults;
- if (status != c.PARDES_PDF_OK)
- return error.SelectionFailed;
- defer c.pardes_pdf_drop_selection(document.handle, selected.handle);
-
- if (selected.quad_count != 0 and selected.quads == null)
- return error.BadGeometry;
- if (!validPoint(selected.start) or !validPoint(selected.end))
- return error.BadGeometry;
- const quads = try gpa.alloc(Quad, selected.quad_count);
- errdefer gpa.free(quads);
- if (selected.quad_count != 0) {
- const source: [*]const Quad = @ptrCast(selected.quads);
- for (quads, source[0..selected.quad_count]) |*dest, item| {
- if (!validQuad(item)) return error.BadGeometry;
- dest.* = item;
- }
- }
- return .{
- .quads = quads,
- .start = selected.start,
- .end = selected.end,
- };
- }
-
- /// Copy UTF-8 text between normalized page points. For word selection,
- /// pass the snapped endpoints returned by `select`. MuPDF's temporary
- /// fz_malloc string is always freed after making the allocator-owned copy.
- pub fn copySelection(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- selection_start: Point,
- selection_end: Point,
- ) ![]u8 {
- const page_number = try document.checkedPage(page);
- if (!validPoint(selection_start) or !validPoint(selection_end))
- return error.InvalidPoint;
-
- var text: c.pardes_pdf_owned_text =
- std.mem.zeroes(c.pardes_pdf_owned_text);
- if (c.pardes_pdf_copy_selection(
- document.handle,
- page_number,
- selection_start,
- selection_end,
- &text,
- ) != c.PARDES_PDF_OK) return error.TextFailed;
- defer c.pardes_pdf_drop_owned_text(document.handle, text.handle);
- if (text.len == 0) return gpa.dupe(u8, "");
- if (text.data == null) return error.BadText;
- const bytes: [*]const u8 = @ptrCast(text.data);
- return gpa.dupe(u8, bytes[0..text.len]);
- }
-
- fn checkedPage(document: *const Document, page: usize) !c_int {
- if (page >= document.pages or page > std.math.maxInt(c_int))
- return error.PageOutOfRange;
- return @intCast(page);
- }
-};
-
-fn outlineBytes(bytes: []const u8, offset: usize, len: usize) ![]const u8 {
- if (offset > bytes.len or len > bytes.len - offset)
- return error.BadOutline;
- return bytes[offset .. offset + len];
-}
-
-fn validPoint(point: Point) bool {
- return std.math.isFinite(point.x) and std.math.isFinite(point.y) and
- point.x >= 0 and point.x <= 1 and point.y >= 0 and point.y <= 1;
-}
-
-fn validQuad(quad: Quad) bool {
- return validPoint(quad.ul) and validPoint(quad.ur) and
- validPoint(quad.ll) and validPoint(quad.lr);
-}
-
-/// The exact shape of the raster a render request produces. `len` is the
-/// packed RGBA byte count a FULL-page `renderIntoAtWithPaper` demands, so a caller can
-/// match a retired buffer against it before deciding to allocate.
-pub const Raster = struct {
- width: usize,
- height: usize,
- stride: usize,
- len: usize,
-
- /// The rows a reader can actually see are usually a fraction of a page:
- /// flinging through a manual, a page is on screen for one frame showing a
- /// couple of hundred of its twelve hundred rows. `Band` is that fraction,
- /// and rendering one is the same rendering clipped — see the bridge's
- /// comment and the test that proves the rows are identical.
- pub const Band = struct {
- y: usize,
- height: usize,
- /// bytes of a `y`/`height` band at this raster's stride
- len: usize,
- };
-
- /// The whole page as a band, which is what a reader at rest gets.
- pub fn wholePage(raster: Raster) Band {
- return .{ .y = 0, .height = raster.height, .len = raster.len };
- }
-
- /// Clamp a wanted row range to the page and return it as a band. A range
- /// that misses the page entirely comes back as its nearest single row
- /// rather than as an error: the caller is describing a viewport, and a
- /// viewport that has just left a page is not a malformed request.
- pub fn band(raster: Raster, first_row: usize, rows: usize) Band {
- const y = @min(first_row, raster.height - 1);
- const height = @min(@max(rows, 1), raster.height - y);
- return .{ .y = y, .height = height, .len = raster.stride * height };
- }
-};
-
-fn checkedRasterLayout(raw: c.pardes_pdf_raster_layout) !Raster {
- if (raw.width < 1 or raw.height < 1 or raw.stride < 1)
- return error.BadPixmap;
- const width: usize = @intCast(raw.width);
- const height: usize = @intCast(raw.height);
- const stride: usize = @intCast(raw.stride);
- const expected_stride = std.math.mul(usize, width, 4) catch
- return error.BadPixmap;
- if (stride != expected_stride) return error.BadPixmap;
- const len = std.math.mul(usize, stride, height) catch
- return error.BadPixmap;
- if (raw.samples_len != len) return error.BadPixmap;
- return .{ .width = width, .height = height, .stride = stride, .len = len };
-}
-
-fn expectOpaque(rgba: []const u8) !void {
- if (rgba.len % 4 != 0) return error.BadPixmap;
- var alpha: usize = 3;
- while (alpha < rgba.len) : (alpha += 4)
- try std.testing.expectEqual(@as(u8, 0xff), rgba[alpha]);
-}
-
-/// TEST-ONLY: a PDF file read whole and opened from memory, as the view
-/// opens one.
-fn openTestFile(path: []const u8) !Document {
- const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, path, std.testing.allocator, .unlimited);
- defer std.testing.allocator.free(bytes);
- return Document.openBytes(bytes);
-}
-
-/// TEST-ONLY (here and in the core's tests, which run in the repository's
-/// root): one of test/pdf-fixtures' PDFs, whole. `outline.pdf`, an outline
-/// of every kind (a branch with neither title nor destination over a UTF-16
-/// child, an empty title, an external link); `offset-rotated.pdf`, one page
-/// with an offset CropBox and /Rotate 90 and no outline; `links.pdf`,
-/// external, internal, same-URI and link-only annotations; `tall.pdf`, one
-/// `tall_test_page` labelled every 100 pt; `rotated-link*.pdf`, a link on
-/// the rotated page by URI, empty URI, JavaScript, a missing destination.
-pub fn testFixture(gpa: std.mem.Allocator, comptime name: []const u8) ![]u8 {
- return std.Io.Dir.cwd().readFileAlloc(std.testing.io, "test/pdf-fixtures/" ++ name, gpa, .unlimited);
-}
-
-fn allocateGeneratedPdf(
- gpa: std.mem.Allocator,
- offsets: []usize,
- context: anytype,
- comptime emit: anytype,
-) ![]u8 {
- @memset(offsets, 0);
- var bytes: std.Io.Writer.Allocating = .init(gpa);
- defer bytes.deinit();
- try emit(&bytes.writer, offsets, context);
- return bytes.toOwnedSlice();
-}
-
-fn beginPdfObject(bytes: *std.Io.Writer, offsets: []usize, number: usize) !void {
- offsets[number] = bytes.end;
- try bytes.print("{d} 0 obj\n", .{number});
-}
-
-fn finishGeneratedPdf(bytes: *std.Io.Writer, offsets: []const usize) !void {
- const xref = bytes.end;
- try bytes.print("xref\n0 {d}\n0000000000 65535 f \n", .{offsets.len});
- for (offsets[1..]) |offset|
- try bytes.print("{d:0>10} 00000 n \n", .{offset});
- try bytes.print(
- "trailer\n<< /Size {d} /Root 1 0 R >>\nstartxref\n{d}\n%%EOF\n",
- .{ offsets.len, xref },
- );
-}
-
-/// The tall test page: 600 x 9000 pt, fifteen A4 pages' height on one.
-pub const tall_test_page: PageSize = .{ .width = 600, .height = 9000 };
-
-test "a tall page rasterizes at the size it is shown, however many max_dimensions tall" {
- var document = try openTestFile("test/pdf-fixtures/tall.pdf");
- defer document.deinit();
- const size = try document.pageSize(0);
- try std.testing.expectEqual(tall_test_page.width, size.width);
- try std.testing.expectEqual(tall_test_page.height, size.height);
-
- // Shown 960 px wide (fit width): 960 px a row, 14400 rows, though that is
- // far past max_dimension. The old clamp of the longest side made this
- // 273 x 4096, drawn 3.5 times too large.
- const shown: RenderRequest = .{ .dpi = 192, .minimum_width = 960, .minimum_height = 600, .max_dimension = 4096, .display_width = 960 };
- const tall = try document.measureRenderAt(0, shown);
- try std.testing.expectEqual(@as(usize, 960), tall.width);
- try std.testing.expectEqual(@as(usize, 14400), tall.height);
- // Kitty's 96 dpi, as any page has it, not 1200 rows' worth.
- const kitty = try document.measureRenderAt(0, .{ .dpi = 96, .max_dimension = 1200, .display_width = 944 });
- try std.testing.expectEqual(@as(usize, 800), kitty.width);
- try std.testing.expectEqual(@as(usize, 12000), kitty.height);
- // The dpi never takes it past what is shown: that would be bands of
- // pixels nobody sees.
- const small = try document.measureRenderAt(0, .{ .dpi = 192, .max_dimension = 4096, .display_width = 300 });
- try std.testing.expectEqual(@as(usize, 300), small.width);
- // Shown whole (fit height), the height cap holds: the page is 600 px
- // tall on screen and 4096 rows is already more.
- const whole = try document.measureRenderAt(0, .{ .dpi = 192, .minimum_width = 960, .minimum_height = 600, .max_dimension = 4096, .display_height = 600 });
- try std.testing.expectEqual(@as(usize, 4096), whole.height);
- // Without a display size, the old budget.
- const blind = try document.measureRenderAt(0, .{ .dpi = 192, .minimum_width = 960, .max_dimension = 4096 });
- try std.testing.expectEqual(@as(usize, 4096), blind.height);
- // A row is never longer than max_dimension, whatever is shown.
- const wide = try document.measureRenderAt(0, .{ .dpi = 192, .minimum_width = 10_000, .max_dimension = 4096, .display_width = 10_000 });
- try std.testing.expectEqual(@as(usize, 4096), wide.width);
- // One buffer is bounded even when the page is not: a whole render of a
- // page past it is refused, a band of it is not.
- const poster: RenderRequest = .{ .dpi = 72, .minimum_width = 4096, .max_dimension = 4096, .display_width = 4096 };
- const huge = try document.measureRenderAt(0, poster);
- try std.testing.expect(huge.len > max_owned_raster_bytes);
- try std.testing.expectError(error.PixmapTooLarge, document.render(std.testing.allocator, 0, poster, &.{}));
- const band = huge.band(huge.height - 100, 100);
- const rows = try std.testing.allocator.alloc(u8, band.len);
- defer std.testing.allocator.free(rows);
- try document.renderIntoAtWithPaper(0, poster, huge, band, &.{}, rows, false);
- try expectOpaque(rows);
-}
-
-test "PDF links own URIs across page eviction and preserve internal coordinates" {
- const gpa = std.testing.allocator;
- start(gpa);
- defer stop();
- var document = try openTestFile("test/pdf-fixtures/links.pdf");
- defer document.deinit();
- var external = (try document.linkAt(gpa, 0, .{ .x = 0.3, .y = 0.18 })) orelse return error.NoLink;
- defer external.deinit(gpa);
- try std.testing.expectEqualStrings("https://example.com/embedded", external.uri);
- try std.testing.expectEqualStrings(external.uri, external.destination.external);
- try std.testing.expectApproxEqAbs(@as(f32, 0.1), external.quad.ul.x, 0.0001);
- try std.testing.expectApproxEqAbs(@as(f32, 40.0 / 300.0), external.quad.ul.y, 0.0001);
- try std.testing.expectApproxEqAbs(@as(f32, 0.6), external.quad.lr.x, 0.0001);
- const label = try document.copyRectangle(gpa, 0, external.quad);
- defer gpa.free(label);
- try std.testing.expectEqualStrings("target.txt", std.mem.trim(u8, label, "\r\n "));
- var internal = (try document.linkAt(gpa, 0, .{ .x = 0.3, .y = 0.38 })) orelse return error.NoLink;
- defer internal.deinit(gpa);
- try std.testing.expectEqual(@as(usize, 1), internal.destination.internal.page);
- try std.testing.expectApproxEqAbs(@as(f32, 12), internal.destination.internal.x.?, 0.001);
- try std.testing.expectApproxEqAbs(@as(f32, 266), internal.destination.internal.y.?, 0.001);
- const blank = try document.copyRectangle(gpa, 0, internal.quad);
- defer gpa.free(blank);
- try std.testing.expectEqualStrings("", blank);
- try std.testing.expect(try document.linkAt(gpa, 1, .{ .x = 0.3, .y = 0.18 }) == null);
- try std.testing.expectEqualStrings("https://example.com/embedded", external.uri);
- var again = (try document.linkAt(gpa, 0, .{ .x = 0.3, .y = 0.18 })) orelse return error.NoLink;
- defer again.deinit(gpa);
- try std.testing.expectEqualStrings(external.uri, again.uri);
- var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 });
- try std.testing.expectError(error.OutOfMemory, document.linkAt(failing.allocator(), 0, .{ .x = 0.3, .y = 0.18 }));
- try std.testing.expectError(error.PageOutOfRange, document.linkAt(gpa, 2, .{ .x = 0.3, .y = 0.18 }));
- for ([_]Point{ .{ .x = -0.1, .y = 0.18 }, .{ .x = 0.3, .y = 1.1 }, .{ .x = std.math.nan(f32), .y = 0.18 } }) |point|
- try std.testing.expect(try document.linkAt(gpa, 0, point) == null);
- try std.testing.expect(try document.linkAt(gpa, 0, .{ .x = 0.99, .y = 0.99 }) == null);
-}
-
-test "PDF links normalize cropped rotated annotations and ignore unsupported actions" {
- const gpa = std.testing.allocator;
- start(gpa);
- defer stop();
- // The page's link's action: a URI, an empty URI, JavaScript, a
- // destination that is not there.
- const fixtures = [_][]const u8{ "rotated-link.pdf", "rotated-link-empty-uri.pdf", "rotated-link-javascript.pdf", "rotated-link-missing-dest.pdf" };
- for (fixtures, 0..) |name, index| {
- var path: [64]u8 = undefined;
- var document = try openTestFile(try std.fmt.bufPrint(&path, "test/pdf-fixtures/{s}", .{name}));
- defer document.deinit();
- var found = try document.linkAt(gpa, 0, .{ .x = 0.1, .y = 0.1 });
- defer if (found) |*item| item.deinit(gpa);
- if (index != 0) {
- try std.testing.expect(found == null);
- continue;
- }
- const link = found orelse return error.NoRotatedLink;
- try std.testing.expectApproxEqAbs(@as(f32, 0), link.quad.ul.x, 0.0001);
- try std.testing.expectApproxEqAbs(@as(f32, 0), link.quad.ul.y, 0.0001);
- try std.testing.expectApproxEqAbs(@as(f32, 50.0 / 150.0), link.quad.lr.x, 0.0001);
- try std.testing.expectApproxEqAbs(@as(f32, 40.0 / 160.0), link.quad.lr.y, 0.0001);
- try std.testing.expect(try document.linkAt(gpa, 0, .{ .x = 0.7, .y = 0.7 }) == null);
- }
-}
-
-fn emitTooDeepOutlinePdf(bytes: *std.Io.Writer, offsets: []usize, levels: usize) !void {
- const first_outline_item = 5;
- try bytes.writeAll("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
- try beginPdfObject(bytes, offsets, 1);
- try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>\nendobj\n");
- try beginPdfObject(bytes, offsets, 2);
- try bytes.writeAll("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
- try beginPdfObject(bytes, offsets, 3);
- try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> >>\nendobj\n");
- try beginPdfObject(bytes, offsets, 4);
- try bytes.print("<< /Type /Outlines /First 5 0 R /Last 5 0 R /Count {d} >>\nendobj\n", .{levels});
-
- for (0..levels) |level| {
- const number = first_outline_item + level;
- try beginPdfObject(bytes, offsets, number);
- try bytes.print("<< /Title (Level {d}) /Parent {d} 0 R", .{
- level,
- if (level == 0) 4 else number - 1,
- });
- if (level + 1 < levels) {
- try bytes.print(" /First {d} 0 R /Last {d} 0 R /Count {d}", .{
- number + 1,
- number + 1,
- levels - level - 1,
- });
- }
- try bytes.writeAll(" >>\nendobj\n");
- }
- try finishGeneratedPdf(bytes, offsets);
-}
-
-fn makeTooDeepOutlinePdf(gpa: std.mem.Allocator) ![]u8 {
- const levels: usize = c.PARDES_PDF_MAX_OUTLINE_DEPTH + 1;
- const object_count = 5 + levels;
- const offsets = try gpa.alloc(usize, object_count);
- defer gpa.free(offsets);
- return allocateGeneratedPdf(gpa, offsets, levels, emitTooDeepOutlinePdf);
-}
-
-fn emitWideOutlinePdf(bytes: *std.Io.Writer, offsets: []usize, items: usize) !void {
- const first_outline_item = 5;
- try bytes.writeAll("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
- try beginPdfObject(bytes, offsets, 1);
- try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>\nendobj\n");
- try beginPdfObject(bytes, offsets, 2);
- try bytes.writeAll("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
- try beginPdfObject(bytes, offsets, 3);
- try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> >>\nendobj\n");
- try beginPdfObject(bytes, offsets, 4);
- try bytes.print("<< /Type /Outlines /First 5 0 R /Last {d} 0 R /Count {d} >>\nendobj\n", .{
- first_outline_item + items - 1,
- items,
- });
-
- for (0..items) |ordinal| {
- const number = first_outline_item + ordinal;
- try beginPdfObject(bytes, offsets, number);
- try bytes.print("<< /Title (Section {d}) /Parent 4 0 R /Dest [3 0 R /Fit]", .{ordinal});
- if (ordinal != 0)
- try bytes.print(" /Prev {d} 0 R", .{number - 1});
- if (ordinal + 1 < items)
- try bytes.print(" /Next {d} 0 R", .{number + 1});
- try bytes.writeAll(" >>\nendobj\n");
- }
- try finishGeneratedPdf(bytes, offsets);
-}
-
-fn makeWideOutlinePdf(gpa: std.mem.Allocator, items: usize) ![]u8 {
- if (items == 0) return error.EmptyOutlineFixture;
- const object_count = try std.math.add(usize, 5, items);
- const offsets = try gpa.alloc(usize, object_count);
- defer gpa.free(offsets);
- return allocateGeneratedPdf(gpa, offsets, items, emitWideOutlinePdf);
-}
-
-test "PDF outline is a stable owned DFS view with native destinations" {
- var document = try openTestFile("test/pdf-fixtures/outline.pdf");
- defer document.deinit();
- try std.testing.expectEqual(@as(usize, 3), document.pages);
- for (0..2) |fail_index| {
- var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{
- .fail_index = fail_index,
- });
- try std.testing.expectError(
- error.OutOfMemory,
- document.outline(failing.allocator()),
- );
- }
- for (0..2) |_| {
- var outline = try document.outline(std.testing.allocator);
- defer outline.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, 4), outline.entries.len);
- try std.testing.expectEqualSlices(u8, &.{ 0, 1, 0, 0 }, &.{
- outline.entries[0].depth,
- outline.entries[1].depth,
- outline.entries[2].depth,
- outline.entries[3].depth,
- });
-
- try std.testing.expect(outline.entries[0].title == null);
- try std.testing.expect(outline.entries[0].destination == .none);
- try std.testing.expectEqualStrings("Café 子", outline.entries[1].title.?);
- const child = outline.entries[1].destination.internal;
- try std.testing.expectEqual(@as(usize, 1), child.page);
- try std.testing.expect(child.x != null and child.y != null);
- try std.testing.expectApproxEqAbs(@as(f32, 12), child.x.?, 0.01);
-
- try std.testing.expectEqualStrings("", outline.entries[2].title.?);
- const fitted = outline.entries[2].destination.internal;
- try std.testing.expectEqual(@as(usize, 2), fitted.page);
- try std.testing.expect(fitted.x == null);
- try std.testing.expect(fitted.y != null);
-
- try std.testing.expectEqualStrings("External", outline.entries[3].title.?);
- try std.testing.expectEqualStrings(
- "https://example.com/manual",
- outline.entries[3].destination.external,
- );
- }
-}
-
-test "PDF outline accepts manual-sized trees and rejects item overflow atomically" {
- const manual_items = 4105;
- try std.testing.expect(max_outline_items >= manual_items);
-
- const manual_fixture = try makeWideOutlinePdf(std.testing.allocator, manual_items);
- defer std.testing.allocator.free(manual_fixture);
- var manual_document = try Document.openBytes(manual_fixture);
- defer manual_document.deinit();
- var outline = try manual_document.outline(std.testing.allocator);
- defer outline.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, manual_items), outline.entries.len);
- try std.testing.expectEqualStrings("Section 0", outline.entries[0].title.?);
- try std.testing.expectEqualStrings("Section 4104", outline.entries[manual_items - 1].title.?);
- try std.testing.expectEqual(@as(usize, 0), outline.entries[manual_items - 1].destination.internal.page);
-
- const overflow_fixture = try makeWideOutlinePdf(std.testing.allocator, max_outline_items + 1);
- defer std.testing.allocator.free(overflow_fixture);
- var overflow_document = try Document.openBytes(overflow_fixture);
- defer overflow_document.deinit();
- var raw: c.pardes_pdf_outline_result = undefined;
- @memset(std.mem.asBytes(&raw), 0xa5);
- try std.testing.expectEqual(
- c.PARDES_PDF_LIMIT_EXCEEDED,
- c.pardes_pdf_load_outline(overflow_document.handle, &raw),
- );
- try std.testing.expect(raw.handle == null);
- try std.testing.expect(raw.items == null);
- try std.testing.expectEqual(@as(usize, 0), raw.item_count);
- try std.testing.expect(raw.bytes == null);
- try std.testing.expectEqual(@as(usize, 0), raw.bytes_len);
-}
-
-test "PDF outline absence and hostile depth are atomic and repeatable" {
- var plain_document = try openTestFile("test/pdf-fixtures/offset-rotated.pdf");
- defer plain_document.deinit();
- var absent = try plain_document.outline(std.testing.allocator);
- defer absent.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, 0), absent.entries.len);
- try std.testing.expectEqual(@as(usize, 0), absent.bytes.len);
-
- const deep_fixture = try makeTooDeepOutlinePdf(std.testing.allocator);
- defer std.testing.allocator.free(deep_fixture);
- var deep_document = try Document.openBytes(deep_fixture);
- defer deep_document.deinit();
- var raw: c.pardes_pdf_outline_result = undefined;
- @memset(std.mem.asBytes(&raw), 0xa5);
- try std.testing.expectEqual(
- c.PARDES_PDF_LIMIT_EXCEEDED,
- c.pardes_pdf_load_outline(deep_document.handle, &raw),
- );
- try std.testing.expect(raw.handle == null);
- try std.testing.expect(raw.items == null);
- try std.testing.expectEqual(@as(usize, 0), raw.item_count);
- try std.testing.expect(raw.bytes == null);
- try std.testing.expectEqual(@as(usize, 0), raw.bytes_len);
- for (0..2) |_|
- try std.testing.expectError(
- error.OutlineLimitExceeded,
- deep_document.outline(std.testing.allocator),
- );
- const size = try deep_document.pageSize(0);
- try std.testing.expectEqual(@as(f32, 100), size.width);
- try std.testing.expectEqual(@as(f32, 100), size.height);
-}
-
-test "caller-owned RGBA layout is packed and overflow checked" {
- const layout = try checkedRasterLayout(.{
- .width = 2,
- .height = 3,
- .stride = 8,
- .samples_len = 24,
- });
- try std.testing.expectEqual(@as(usize, 2), layout.width);
- try std.testing.expectEqual(@as(usize, 3), layout.height);
- try std.testing.expectEqual(@as(usize, 8), layout.stride);
- try std.testing.expectEqual(@as(usize, 24), layout.len);
- try std.testing.expectError(error.BadPixmap, checkedRasterLayout(.{
- .width = 2,
- .height = 3,
- .stride = 7,
- .samples_len = 21,
- }));
-}
-
-test "RGBA allocation and buffer-validation failures leave the document renderable" {
- var document = try openTestFile("docs/design.pdf");
- defer document.deinit();
-
- var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{
- .fail_index = 0,
- });
- try std.testing.expectError(
- error.OutOfMemory,
- document.render(failing.allocator(), 0, .{}, &.{}),
- );
-
- const request = try document.boundedRequest(0, .{});
- var raw_layout: c.pardes_pdf_raster_layout = std.mem.zeroes(c.pardes_pdf_raster_layout);
- try std.testing.expectEqual(c.PARDES_PDF_OK, c.pardes_pdf_measure_render(document.handle, 0, &request, &raw_layout));
- const layout = try checkedRasterLayout(raw_layout);
- {
- const scratch = try std.testing.allocator.alloc(u8, layout.len);
- defer std.testing.allocator.free(scratch);
- @memset(scratch, 0xa5);
- try std.testing.expectEqual(c.PARDES_PDF_ERROR, c.pardes_pdf_render_into(
- document.handle,
- 0,
- &request,
- null,
- 0,
- scratch.ptr,
- scratch.len - 1,
- raw_layout.width,
- raw_layout.height,
- raw_layout.stride,
- 0,
- raw_layout.height,
- 0,
- ));
- for (scratch) |byte|
- try std.testing.expectEqual(@as(u8, 0xa5), byte);
- }
-
- const after = try document.render(std.testing.allocator, 0, .{}, &.{});
- defer std.testing.allocator.free(after.rgba);
- const repeated = try document.render(std.testing.allocator, 0, .{}, &.{});
- defer std.testing.allocator.free(repeated.rgba);
- try std.testing.expectEqualSlices(u8, after.rgba, repeated.rgba);
- try expectOpaque(after.rgba);
- try expectOpaque(repeated.rgba);
-}
-
-test "a band's rows are the full page's rows, and highlights land in them" {
- // THE claim the fast-scroll path rests on: rendering rows [y, y+h) of a
- // page is the same rendering, clipped — not a different one. If MuPDF ever
- // let the pixmap's bbox change antialiasing, hinting or subpixel placement,
- // a fling would show pixels a reader could tell apart from a rested view,
- // and this test is what refuses to let that happen quietly.
- var document = try openTestFile("docs/design.pdf");
- defer document.deinit();
-
- const request: RenderRequest = .{ .dpi = 96, .max_dimension = 1200 };
- const raster = try document.measureRenderAt(0, request);
- const whole = try std.testing.allocator.alloc(u8, raster.len);
- defer std.testing.allocator.free(whole);
- try document.renderIntoAtWithPaper(0, request, raster, raster.wholePage(), &.{}, whole, false);
-
- // Odd offsets and an odd height on purpose: a band that starts on a row
- // MuPDF would never choose itself is exactly where an off-by-one in the
- // bbox arithmetic would show up.
- const cases = [_]struct { y: usize, h: usize }{
- .{ .y = 0, .h = 1 },
- .{ .y = 1, .h = 37 },
- .{ .y = raster.height / 3, .h = 101 },
- .{ .y = raster.height / 2, .h = raster.height / 2 },
- .{ .y = raster.height - 1, .h = 1 },
- };
- for (cases) |case| {
- const band = raster.band(case.y, case.h);
- const rows = try std.testing.allocator.alloc(u8, band.len);
- defer std.testing.allocator.free(rows);
- try document.renderIntoAtWithPaper(0, request, raster, band, &.{}, rows, false);
- const from = band.y * raster.stride;
- try std.testing.expectEqualSlices(u8, whole[from..][0..band.len], rows);
- try expectOpaque(rows);
- }
-
- // A baked highlight is drawn under the same CTM, so it has to land on the
- // same rows through a band as it does through a whole page.
- const highlights = [_]Highlight{.{
- .quad = .{
- .ul = .{ .x = 0.1, .y = 0.4 },
- .ur = .{ .x = 0.9, .y = 0.4 },
- .ll = .{ .x = 0.1, .y = 0.6 },
- .lr = .{ .x = 0.9, .y = 0.6 },
- },
- .kind = .search,
- .rgba = .{ 0x30, 0x80, 0xf0, 0x80 },
- }};
- const marked_whole = try std.testing.allocator.alloc(u8, raster.len);
- defer std.testing.allocator.free(marked_whole);
- try document.renderIntoAtWithPaper(0, request, raster, raster.wholePage(), &highlights, marked_whole, false);
- const marked_band = raster.band(raster.height / 3, raster.height / 3);
- const marked_rows = try std.testing.allocator.alloc(u8, marked_band.len);
- defer std.testing.allocator.free(marked_rows);
- try document.renderIntoAtWithPaper(0, request, raster, marked_band, &highlights, marked_rows, false);
- const marked_from = marked_band.y * raster.stride;
- try std.testing.expectEqualSlices(
- u8,
- marked_whole[marked_from..][0..marked_band.len],
- marked_rows,
- );
- // ...and the highlight really is in the band that was compared, or the
- // comparison above would be two identical plain renders agreeing.
- try std.testing.expect(!std.mem.eql(
- u8,
- whole[marked_from..][0..marked_band.len],
- marked_rows,
- ));
-
- // A band request that misses the page is a viewport that has left it, not
- // a malformed call: it clamps instead of failing.
- const past_end = raster.band(raster.height + 500, 64);
- try std.testing.expect(past_end.y < raster.height);
- try std.testing.expectEqual(@as(usize, 1), past_end.height);
-}
-
-test "MuPDF search returns normalized oriented quads and word selection text" {
- var document = try openTestFile("docs/design.pdf");
- defer document.deinit();
-
- const projected = try document.pageText(std.testing.allocator, 0);
- defer std.testing.allocator.free(projected);
- try std.testing.expect(std.ascii.findIgnoreCase(projected, "Pardes") != null);
- // Exercise transactional cache replacement before searching page zero
- // again; a failed ownership handoff here tends to surface as a double drop.
- if (document.pages > 1) {
- const other_page = try document.pageText(std.testing.allocator, 1);
- std.testing.allocator.free(other_page);
- }
-
- var found = try document.search(std.testing.allocator, 0, "Pardes");
- defer found.deinit(std.testing.allocator);
- try std.testing.expect(found.hit_count > 0);
- try std.testing.expect(found.quads.len > 0);
- for (found.quads) |item| {
- try std.testing.expect(item.hit < found.hit_count);
- try std.testing.expect(validQuad(item.quad));
- }
-
- const first = found.quads[0].quad;
- var selected = try document.select(std.testing.allocator, 0, first.ul, first.lr);
- defer selected.deinit(std.testing.allocator);
- try std.testing.expect(selected.quads.len > 0);
- try std.testing.expect(validPoint(selected.start));
- try std.testing.expect(validPoint(selected.end));
-
- const text = try document.copySelection(std.testing.allocator, 0, selected.start, selected.end);
- defer std.testing.allocator.free(text);
- try std.testing.expect(std.ascii.findIgnoreCase(text, "Pardes") != null);
-}
-
-test "highlighted render changes pixels while plain render stays stable" {
- var document = try openTestFile("docs/design.pdf");
- defer document.deinit();
-
- const plain_before = try document.render(std.testing.allocator, 0, .{}, &.{});
- defer std.testing.allocator.free(plain_before.rgba);
- const whole_page = Quad{
- .ul = .{ .x = 0, .y = 0 },
- .ur = .{ .x = 1, .y = 0 },
- .ll = .{ .x = 0, .y = 1 },
- .lr = .{ .x = 1, .y = 1 },
- };
- const highlights = [_]Highlight{
- Highlight.init(whole_page, .{ 255, 0, 0, 128 }, .custom),
- };
- const marked = try document.render(std.testing.allocator, 0, .{}, &highlights);
- defer std.testing.allocator.free(marked.rgba);
- const plain_after = try document.render(std.testing.allocator, 0, .{}, &.{});
- defer std.testing.allocator.free(plain_after.rgba);
-
- try expectOpaque(plain_before.rgba);
- try expectOpaque(marked.rgba);
- try expectOpaque(plain_after.rgba);
- try std.testing.expectEqual(plain_before.width, marked.width);
- try std.testing.expectEqual(plain_before.height, marked.height);
- try std.testing.expect(!std.mem.eql(u8, plain_before.rgba, marked.rgba));
- try std.testing.expectEqualSlices(u8, plain_before.rgba, plain_after.rgba);
-}
-
-test "offset crop and rotation keep normalized highlights pixel-aligned" {
- var document = try openTestFile("test/pdf-fixtures/offset-rotated.pdf");
- defer document.deinit();
- const plain = try document.render(std.testing.allocator, 0, .{}, &.{});
- defer std.testing.allocator.free(plain.rgba);
- // CropBox is 160x150 points and /Rotate 90 swaps its displayed axes.
- try std.testing.expectEqual(@as(usize, 300), plain.width);
- try std.testing.expectEqual(@as(usize, 320), plain.height);
-
- // The SIZE comes off the page object rather than a loaded page (see
- // pardes_pdf_get_page_size), and this is the fixture that would catch it
- // being a different answer: an offset CropBox plus /Rotate 90, where a
- // MediaBox reading, an untransformed cropbox or a missed rotation all give
- // plausible-looking wrong numbers. The rendered raster above is what
- // fz_bound_page produces, so the strip's layout has to agree with it.
- const size = try document.pageSize(0);
- try std.testing.expectEqual(@as(f32, 150), size.width);
- try std.testing.expectEqual(@as(f32, 160), size.height);
- try std.testing.expectApproxEqAbs(
- @as(f32, @floatFromInt(plain.width)) / @as(f32, @floatFromInt(plain.height)),
- size.width / size.height,
- 0.001,
- );
-
- const kitty = try document.render(std.testing.allocator, 0, .{
- .dpi = 96,
- .max_dimension = 1200,
- }, &.{});
- defer std.testing.allocator.free(kitty.rgba);
- try std.testing.expect(kitty.width < plain.width);
- try std.testing.expect(kitty.height < plain.height);
-
- const sdl = try document.render(std.testing.allocator, 0, .{
- .dpi = 192,
- .minimum_width = 640,
- .minimum_height = 480,
- .max_dimension = 4096,
- }, &.{});
- defer std.testing.allocator.free(sdl.rgba);
- try std.testing.expect(sdl.width >= 640);
- try std.testing.expect(sdl.height >= 480);
- try std.testing.expect(sdl.width * sdl.height >= kitty.width * kitty.height * 4);
-
- const capped = try document.render(std.testing.allocator, 0, .{
- .dpi = 192,
- .minimum_width = 4096,
- .minimum_height = 4096,
- .max_dimension = 512,
- }, &.{});
- defer std.testing.allocator.free(capped.rgba);
- try std.testing.expectEqual(@as(usize, 512), @max(capped.width, capped.height));
-
- const left_half = Quad{
- .ul = .{ .x = 0, .y = 0 },
- .ur = .{ .x = 0.5, .y = 0 },
- .ll = .{ .x = 0, .y = 1 },
- .lr = .{ .x = 0.5, .y = 1 },
- };
- const highlights = [_]Highlight{
- Highlight.init(left_half, .{ 0, 0, 255, 255 }, .custom),
- };
- const marked = try document.render(std.testing.allocator, 0, .{}, &highlights);
- defer std.testing.allocator.free(marked.rgba);
- try std.testing.expectEqual(plain.width, marked.width);
- try std.testing.expectEqual(plain.height, marked.height);
-
- const left = (plain.height / 2 * plain.width + plain.width / 4) * 4;
- const right = (plain.height / 2 * plain.width + plain.width * 3 / 4) * 4;
- try std.testing.expect(plain.rgba[left] > 240 and
- plain.rgba[left + 1] < 10 and plain.rgba[left + 2] < 10);
- try std.testing.expect(marked.rgba[left] < 10 and
- marked.rgba[left + 1] < 10 and marked.rgba[left + 2] > 240);
- try std.testing.expectEqualSlices(u8, plain.rgba[right .. right + 4], marked.rgba[right .. right + 4]);
-}
-
-test "transparent PDF paper preserves ink and band coverage" {
- var document = try openTestFile("docs/9p.pdf");
- defer document.deinit();
- const request: RenderRequest = .{ .dpi = 96, .max_dimension = 1200 };
- const raster = try document.measureRenderAt(0, request);
- const flattened = try std.testing.allocator.alloc(u8, raster.len);
- defer std.testing.allocator.free(flattened);
- const content = try std.testing.allocator.alloc(u8, raster.len);
- defer std.testing.allocator.free(content);
- try document.renderIntoAtWithPaper(0, request, raster, raster.wholePage(), &.{}, flattened, false);
- try document.renderIntoAtWithPaper(0, request, raster, raster.wholePage(), &.{}, content, true);
- var paper: usize = 0;
- var ink: usize = 0;
- var edges: usize = 0;
- for (std.mem.bytesAsSlice([4]u8, content), std.mem.bytesAsSlice([4]u8, flattened)) |pixel, reference| {
- const a: u32 = pixel[3];
- paper += @intFromBool(a == 0);
- ink += @intFromBool(a == 255);
- edges += @intFromBool(a > 0 and a < 255);
- for (0..3) |channel| {
- const over_white = (a * pixel[channel] + (255 - a) * 255 + 127) / 255;
- try std.testing.expect(@abs(@as(i32, @intCast(over_white)) - @as(i32, reference[channel])) <= 2);
- }
- }
- try std.testing.expect(paper > 100 and ink > 100 and edges > 100);
- const band = raster.band(raster.height / 3, raster.height / 4);
- const rows = try std.testing.allocator.alloc(u8, band.len);
- defer std.testing.allocator.free(rows);
- try document.renderIntoAtWithPaper(0, request, raster, band, &.{}, rows, true);
- try std.testing.expectEqualSlices(u8, content[band.y * raster.stride ..][0..band.len], rows);
-}
diff --git a/src/pdf_view.zig b/src/pdf_view.zig
deleted file mode 100644
index 93390b57..00000000
--- a/src/pdf_view.zig
+++ /dev/null
@@ -1,3721 +0,0 @@
-//! A PDF pane: the MuPDF document it views, page rasters and their placement,
-//! scrolling, search, pointer selection, and the sections outline.
-const panes = @import("panes.zig");
-const std = @import("std");
-const pardes = @import("pardes.zig");
-const exec = @import("exec.zig");
-const layout = @import("layout.zig");
-const config = @import("config.zig");
-const modal = @import("modal.zig");
-const filesystem = @import("fs.zig");
-const tracy = @import("tracy.zig");
-const surface = @import("surface.zig");
-const look = @import("look.zig");
-const tagline = @import("tagline.zig");
-const File = panes.File;
-const Output = panes.Output;
-
-pub const enabled = @import("pardes_config").mupdf;
-pub const pdf = if (enabled) @import("mupdf") else struct {
- pub const PageSize = struct { width: f32, height: f32 };
- pub const Raster = struct {
- width: usize = 0,
- height: usize = 0,
- stride: usize = 0,
- len: usize = 0,
- pub const Band = struct { y: usize = 0, height: usize = 0, len: usize = 0 };
- pub fn wholePage(_: @This()) Band {
- return .{};
- }
- pub fn band(_: @This(), _: usize, _: usize) Band {
- return .{};
- }
- };
-};
-pub const Point = if (enabled) pdf.Point else void;
-pub const Quad = if (enabled) pdf.Quad else void;
-pub const Document = if (enabled) pdf.Document else opaque {};
-pub const OutlineInternalDestination = if (enabled) pdf.OutlineInternalDestination else void;
-const raster_max = 256;
-const raster_spare = 4;
-pub const page_gap_px: u32 = 8;
-const band_grain: usize = 64;
-/// The tallest raster one buffer carries: within every GPU's texture size
-/// and Kitty's 10000-pixel image limit (kitty and ghostty both). A page
-/// taller than this, or than `pdf.max_owned_raster_bytes` allows, is BANDED:
-/// it is held as the rows around what is on screen and rendered in chunks.
-const max_band_rows: usize = 8192;
-/// A banded page is rendered in chunks of this many rows, each from its own
-/// render of the chunk and `chunk_overlap` rows of the page beyond both of
-/// its edges, which are thrown away. A row of the page therefore always comes
-/// from the same render, however the reader scrolled to it, and never from
-/// the edge of one: MuPDF's rows at the edge of a clip can differ from the
-/// same rows rendered whole (see `pardes_pdf_render_into`), which, butted
-/// against the next chunk, would be a seam.
-const chunk_rows: usize = 512;
-const chunk_overlap: usize = 32;
-
-pub const FitMode = if (enabled) enum { width, height } else void;
-pub const TintMode = if (enabled) pdf.TintMode else void;
-pub const TintColors = if (enabled) pdf.TintColors else void;
-pub const RenderRequest = if (enabled) pdf.RenderRequest else void;
-
-pub const RasterPolicy = struct {
- dpi: u16,
- max_dimension: u16,
- match_viewport: bool,
-};
-
-pub const TintKey = if (enabled) struct {
- mode: TintMode,
- colors: pdf.TintColors,
-
- pub fn eql(a: @This(), b: @This()) bool {
- return a.mode == b.mode and
- (a.mode == .disabled or std.meta.eql(a.colors, b.colors));
- }
-} else void;
-
-pub const Highlight = if (enabled) pdf.Highlight else void;
-pub const Highlights = if (enabled) struct {
- const Page = struct { page: usize, items: []const Highlight };
- pub const replica = .{ .len = .{.{ "pages", "len" }} };
- pages: [3]Page = undefined,
- len: usize = 0,
- /// Repaint whenever the set changes, not only when a page's raster was
- /// invalidated (`HighlightInput.live`).
- live: bool = false,
-
- pub fn forPage(highlights: @This(), page: usize) []const Highlight {
- for (highlights.pages[0..highlights.len]) |group|
- if (group.page == page) return group.items;
- return &.{};
- }
-} else void;
-
-pub const HighlightInput = if (enabled) struct {
- hover_quads: []const Quad = &.{},
- hover_page: ?usize = null,
- hover_color: [3]u8,
- selection_color: [3]u8,
- live: bool = false,
-} else void;
-
-pub fn buildHighlights(
- state: *const State,
- arena: std.mem.Allocator,
- input: HighlightInput,
-) !Highlights {
- if (comptime !enabled) return;
- const search_len = if (state.search_results) |results| results.quads.len else 0;
- const selection_len = if (state.selection) |selection| selection.quads.len else 0;
- const items = try arena.alloc(Highlight, input.hover_quads.len + search_len + selection_len);
- var result: Highlights = .{ .live = input.live };
- var n: usize = 0;
- // Hover, search and selection can belong to three different pages.
- // Group them once so raster rendering can borrow a contiguous slice.
- for ([_]?usize{ input.hover_page, state.page, state.selection_page }) |candidate| {
- const page = candidate orelse continue;
- var seen = false;
- for (result.pages[0..result.len]) |group| {
- if (group.page == page) seen = true;
- }
- if (seen) continue;
- const start = n;
- if (input.hover_page == page) for (input.hover_quads) |quad| {
- items[n] = pdf.Highlight.init(quad, .{
- input.hover_color[0], input.hover_color[1], input.hover_color[2], 0x2c,
- }, .custom);
- n += 1;
- };
- if (state.page == page) if (state.search_results) |results| {
- for (results.quads) |item| {
- items[n] = pdf.Highlight.init(item.quad, .{ 0xff, 0xd5, 0x4f, 0x70 }, .search);
- n += 1;
- }
- };
- if (state.selection_page == page) if (state.selection) |selection| {
- for (selection.quads) |quad| {
- items[n] = pdf.Highlight.init(quad, .{
- input.selection_color[0], input.selection_color[1], input.selection_color[2], 0x78,
- }, .selection);
- n += 1;
- }
- };
- result.pages[result.len] = .{ .page = page, .items = items[start..n] };
- result.len += 1;
- }
- return result;
-}
-
-test "PDF selections retain their owning page across page focus" {
- if (comptime !enabled) return;
- const gpa = std.testing.allocator;
- var state = try State.open(gpa, "docs/design.pdf", 1);
- defer state.deinit(gpa);
- try std.testing.expect(state.page_count > 1);
- var found = try state.document.search(gpa, 0, "Pardes");
- defer found.deinit(gpa);
- const quad = found.quads[0].quad;
- const point: Point = .{
- .x = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4,
- .y = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4,
- };
- try std.testing.expectEqual(.changed, state.setSelection(gpa, point, point, true));
- const selected = try gpa.dupe(u8, state.selection_text);
- defer gpa.free(selected);
- try std.testing.expect(selected.len > 0);
- try std.testing.expect(state.focusLocation(gpa, 2, 0));
- try std.testing.expectEqual(@as(?usize, 0), state.selection_page);
- try std.testing.expectEqualStrings(selected, state.selection_text);
- var arena = std.heap.ArenaAllocator.init(gpa);
- defer arena.deinit();
- const highlights = try buildHighlights(&state, arena.allocator(), .{
- .hover_quads = &.{quad},
- .hover_page = 1,
- .hover_color = .{ 1, 2, 3 },
- .selection_color = .{ 4, 5, 6 },
- });
- try std.testing.expectEqual(state.selection.?.quads.len, highlights.forPage(0).len);
- try std.testing.expectEqual(@as(usize, 1), highlights.forPage(1).len);
- try std.testing.expectEqual(@as(usize, 0), highlights.forPage(2).len);
- try std.testing.expect(state.focusLocation(gpa, 1, 0));
- try std.testing.expectEqualStrings(selected, state.selection_text);
- try std.testing.expectEqual(.unchanged, state.setSelection(gpa, point, point, true));
- try std.testing.expect(state.focusLocation(gpa, 2, 0));
- state.rasters[0] = .{ .valid = true, .page = 0, .tried = true, .decorated = true };
- state.rasters_len = 1;
- try std.testing.expectEqual(.changed, state.setSelection(gpa, point, point, false));
- try std.testing.expectEqual(@as(?usize, 1), state.selection_page);
- try std.testing.expect(!state.rasters[0].tried);
- state.clearSelection(gpa);
- try std.testing.expect(state.selection_page == null);
- try std.testing.expectEqual(@as(usize, 0), state.selection_text.len);
-}
-
-test "off the loop: pages land from lanes, a stale request's raster never lands, and a job nobody waits for is aborted" {
- if (comptime !enabled) return;
- const gpa = std.testing.allocator;
- workers = std.testing.io;
- defer workers = null;
- defer dropKept();
- var state = try State.open(gpa, "docs/design.pdf", 1);
- defer state.deinit(gpa);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- const key: TintKey = .{ .mode = .disabled, .colors = undefined };
- const none: HighlightInput = .{ .hover_color = .{ 0, 0, 0 }, .selection_color = .{ 0, 0, 0 } };
- const policy = pardes.pdf_raster_policy;
- const Run = struct {
- /// Frames until every lane is idle; no slot ever holds a raster of
- /// the `stale` request.
- fn settle(st: *State, a: *std.heap.ArenaAllocator, v: Viewport, k: TintKey, h: HighlightInput, stale: ?RenderRequest) !void {
- var frames: usize = 0;
- while (true) : (frames += 1) {
- _ = renderFrame(st, std.testing.allocator, a.allocator(), v, pardes.pdf_raster_policy, k, h, 0, false);
- if (stale) |old| for (st.rasters[0..st.rasters_len]) |r| if (r.rgba.len > 0 and r.request_valid)
- try std.testing.expect(!r.request.eql(old));
- if (!rendering(st)) break;
- try std.testing.expect(frames < 100_000);
- std.Thread.yield() catch {};
- }
- }
- };
- const small: Viewport = .{ .pixel_w = 400, .pixel_h = 300 };
- ensureLayout(&state, small);
- // The first frame asks; nothing has landed, so the loop drew nothing.
- _ = renderFrame(&state, gpa, arena.allocator(), small, policy, key, none, 0, false);
- try std.testing.expect(rendering(&state));
- try std.testing.expect(!pageReady(&state, small, 0));
- try Run.settle(&state, &arena, small, key, none, null);
- try std.testing.expect(pageReady(&state, small, 0));
- // The page past the view was rendered ahead.
- const shown = visiblePages(&state, small);
- try std.testing.expect(rasterForPage(&state, shown.first + shown.len) != null);
- // A new request while the old one's jobs are out, many times over:
- // only the newest request's rasters are ever in a slot.
- var round: u32 = 0;
- while (round < 8) : (round += 1) {
- const v: Viewport = .{ .pixel_w = 300 + 37 * round, .pixel_h = 300 };
- ensureLayout(&state, v);
- _ = renderFrame(&state, gpa, arena.allocator(), v, policy, key, none, 0, false);
- const next: Viewport = .{ .pixel_w = 301 + 37 * round, .pixel_h = 300 };
- ensureLayout(&state, next);
- try Run.settle(&state, &arena, next, key, none, renderRequest(v, policy, state.fit));
- try std.testing.expect(pageReady(&state, next, state.page));
- try std.testing.expect(rasterForPage(&state, state.page).?.request.eql(renderRequest(next, policy, state.fit)));
- }
- // A job whose page left the strip is aborted through its cookie, and an
- // aborted job is not a failure: the page is asked again when it returns.
- state.invalidateAllRasters();
- const last: Viewport = .{ .pixel_w = 301 + 37 * 7, .pixel_h = 300 };
- _ = renderFrame(&state, gpa, arena.allocator(), last, policy, key, none, 0, false);
- state.document_scroll_y = @floatFromInt(state.page_starts[state.page_count - 1]);
- _ = renderFrame(&state, gpa, arena.allocator(), last, policy, key, none, 0, false);
- for (state.lanes) |lane| if (lane.job) |job| if (job.page < state.page_count - 2)
- try std.testing.expectEqual(@as(c_int, 1), @atomicLoad(c_int, &job.cookie.abort, .acquire));
- try Run.settle(&state, &arena, last, key, none, null);
- for (state.rasters[0..state.rasters_len]) |r| try std.testing.expect(!r.failed);
-}
-
-test "page sizes off the loop: the strip opens on the first page's size, and when a lane's sizes land it keeps its page and offset" {
- if (comptime !enabled) return;
- const gpa = std.testing.allocator;
- var exact = try State.open(gpa, "docs/design.pdf", 1);
- defer exact.deinit(gpa);
- workers = std.testing.io;
- defer workers = null;
- defer dropKept();
- var state = try State.open(gpa, "docs/design.pdf", 1);
- defer state.deinit(gpa);
- try std.testing.expect(state.sizes_pending);
- for (state.page_sizes) |size| try std.testing.expectEqual(exact.page_sizes[0], size);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- const view: Viewport = .{ .pixel_w = 400, .pixel_h = 300 };
- // Assumed wrong (half as tall) so that the landing lays out again.
- for (state.page_sizes) |*size| size.height /= 2;
- ensureLayout(&state, view);
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[2])) + 0.25 * @as(f64, @floatFromInt(state.page_heights[2]));
- state.drawn_y = state.document_scroll_y;
- const none: HighlightInput = .{ .hover_color = .{ 0, 0, 0 }, .selection_color = .{ 0, 0, 0 } };
- const key: TintKey = .{ .mode = .disabled, .colors = undefined };
- var frames: usize = 0;
- while (state.sizes_pending) : (frames += 1) {
- _ = renderFrame(&state, gpa, arena.allocator(), view, pardes.pdf_raster_policy, key, none, 0, false);
- try std.testing.expect(frames < 100_000);
- std.Thread.yield() catch {};
- }
- applySizes(&state, gpa);
- ensureLayout(&state, view);
- try std.testing.expect(std.mem.eql(u8, std.mem.sliceAsBytes(exact.page_sizes), std.mem.sliceAsBytes(state.page_sizes)));
- try std.testing.expectEqual(@as(usize, 2), pageAtOffset(&state, state.document_scroll_y));
- const offset = (state.document_scroll_y - @as(f64, @floatFromInt(state.page_starts[2]))) / @as(f64, @floatFromInt(state.page_heights[2]));
- try std.testing.expectApproxEqAbs(@as(f64, 0.25), offset, 1e-9);
- // The strip moved with its place: no kick, the motion carries on.
- try std.testing.expectEqual(state.document_scroll_y, state.drawn_y);
- try Wait.idle(&state, &arena, view);
-}
-
-test "kept pages: a second open shows the page it left, bounded in bytes, the oldest going first" {
- if (comptime !enabled) return;
- const gpa = std.testing.allocator;
- workers = std.testing.io;
- defer workers = null;
- defer dropKept();
- const key: TintKey = .{ .mode = .disabled, .colors = undefined };
- const request: RenderRequest = .{};
- // Five pages of 20 MiB kept: only what fits in the bound stays, newest.
- {
- var state = try State.open(gpa, "docs/design.pdf", 1);
- defer state.deinit(gpa);
- for (0..5) |page| {
- state.rasters[page] = .{ .valid = true, .page = page, .rgba = try gpa.alloc(u8, 20 << 20), .iw = 1, .ih = 1, .band_h = 1, .request = request, .request_valid = true, .tint_key = key };
- state.rasters_len += 1;
- }
- }
- var total: usize = 0;
- var pages: [5]bool = @splat(false);
- for (kept) |k| if (k) |e| {
- total += e.rgba.len;
- pages[e.page] = true;
- };
- try std.testing.expect(total <= kept_limit);
- try std.testing.expect(pages[4] and !pages[0]);
- // Opened again: page 4 is there before any render.
- var again = try State.open(gpa, "docs/design.pdf", 1);
- defer again.deinit(gpa);
- again.rasters[0] = .{ .valid = true, .page = 4 };
- again.rasters_len = 1;
- try std.testing.expect(unkeep(&again, &again.rasters[0], request, key));
- try std.testing.expectEqual(@as(usize, 20 << 20), again.rasters[0].rgba.len);
- for (kept) |k| if (k) |e| try std.testing.expect(e.page != 4);
-}
-
-/// TEST-ONLY: frames until every lane is idle.
-const Wait = struct {
- fn idle(st: *State, a: *std.heap.ArenaAllocator, v: Viewport) !void {
- const none: HighlightInput = .{ .hover_color = .{ 0, 0, 0 }, .selection_color = .{ 0, 0, 0 } };
- const key: TintKey = .{ .mode = .disabled, .colors = undefined };
- var frames: usize = 0;
- while (rendering(st)) : (frames += 1) {
- _ = renderFrame(st, std.testing.allocator, a.allocator(), v, pardes.pdf_raster_policy, key, none, 0, false);
- try std.testing.expect(frames < 100_000);
- std.Thread.yield() catch {};
- }
- }
-};
-
-pub const Raster = if (enabled) struct {
- valid: bool = false,
- page: usize = 0,
- rgba: []u8 = &.{},
- /// Full page shape; rgba contains only the band below.
- iw: usize = 0,
- ih: usize = 0,
- band_y: usize = 0,
- band_h: usize = 0,
- request: pdf.RenderRequest = .{},
- request_valid: bool = false,
- tried: bool = false,
- decorated: bool = false,
- tint_key: ?TintKey = null,
- revision: u32 = 0,
- /// `rgba` before its highlights and tint, kept once the page has been
- /// highlighted: a highlight change repaints rows from it instead of
- /// rendering the page again.
- clean: []u8 = &.{},
- /// The highlights baked into `rgba` (gpa-owned), so a change repaints
- /// only the rows of the quads that differ.
- baked: []Highlight = &.{},
- /// `baked` is a true record (false after a render could not copy it).
- baked_valid: bool = false,
- /// Page rows changed since revision `patch_from`, the one last handed
- /// to a shell; 0 when the pixels were replaced wholesale since.
- patch_from: u32 = 0,
- patch_rows: pdf.Document.Rows = .{ .start = 0, .end = 0 },
- /// The render job this slot waits for (its generation; 0: none). Only
- /// that job's raster lands here: an older one, or one for a slot since
- /// retired, is dropped when it comes (`land`).
- pending: u32 = 0,
- /// The last job for `request` failed (not aborted): not asked again
- /// until the raster is invalidated or the request changes.
- failed: bool = false,
- /// A lane found the page too tall for one buffer: it is rendered on the
- /// loop, in chunks, as before.
- banded: bool = false,
-} else void;
-
-/// Where page renders run off the loop: set by a shell that has threads
-/// (gui, tty) to its Io. Null (tests, benches, hosts without threads): the
-/// loop renders as it always did.
-pub var workers: ?std.Io = null;
-
-/// Two lanes: the page in view and the next one, or the two a strip shows
-/// at once; a page asked for while both are out waits a frame.
-/// ponytail: two lanes, fixed; more only if a profile shows pages queuing
-/// behind a slow one (a third costs another parse of the document).
-const lane_count = 2;
-
-/// One page render, run on a lane's thread: what the loop asked for, and
-/// what the lane leaves for `land` (rgba and clean are gpa-owned, handed
-/// over). The lane's thread touches only this and the lane's document.
-const Job = if (enabled) struct {
- /// A page's raster, or every page's size (`submitSizes`).
- kind: enum { render, sizes } = .render,
- /// The sizes pass's answer, gpa-owned.
- sizes: []pdf.PageSize = &.{},
- gen: u32,
- page: usize,
- request: RenderRequest,
- /// Measured by the lane.
- shape: pdf.Raster = .{ .width = 0, .height = 0, .stride = 0, .len = 0 },
- /// Too tall for one buffer: the loop renders it in bands (`slot.banded`).
- banded: bool = false,
- tint_key: TintKey,
- /// The highlights baked in (gpa-owned): the slot's `baked` once it lands.
- highlights: []Highlight,
- keep_clean: bool,
- /// A spare of the page's size, or empty: the lane allocates it.
- rgba: []u8,
- clean: []u8 = &.{},
- ok: bool = false,
- /// Set from the loop when nothing waits for this page any more.
- cookie: pdf.Cookie = std.mem.zeroes(pdf.Cookie),
- done: std.atomic.Value(bool) = .init(false),
-} else void;
-
-/// Pages kept past their pane: a second open of the same file, a Restore
-/// (the old core's panes close, the new one's open), shows them on its
-/// first frame instead of waiting for a lane. Only with workers (a test's
-/// State leaves nothing behind). Bound: `kept_limit` bytes and
-/// `kept.len` pages, the least recently kept evicted first.
-/// ponytail: the file is known by its path, length and a hash of its first
-/// and last 64 KiB (a PDF's trailer and xref are at its end); a change
-/// that keeps all three shows the old page until it is next rendered.
-const Kept = if (enabled) struct {
- file: u64,
- page: usize,
- request: RenderRequest,
- tint_key: TintKey,
- rgba: []u8,
- iw: usize,
- ih: usize,
- gpa: std.mem.Allocator,
- age: u64,
-} else void;
-const kept_limit: usize = 64 << 20;
-var kept: [16]?Kept = @splat(null);
-var kept_age: u64 = 0;
-
-fn fileKey(path: []const u8, bytes: []const u8) u64 {
- var h: std.hash.Wyhash = .init(bytes.len);
- h.update(path);
- h.update(bytes[0..@min(bytes.len, 64 << 10)]);
- h.update(bytes[bytes.len -| (64 << 10)..]);
- return h.final();
-}
-
-/// A slot's page as it stands (whole, unhighlighted) into the kept pages,
-/// its buffer handed over; the oldest go until it fits.
-fn keepPage(state: *State, gpa: std.mem.Allocator, slot: *Raster) void {
- if (workers == null or slot.rgba.len == 0 or slot.baked.len != 0 or !slot.request_valid or
- slot.tint_key == null or slot.band_y != 0 or slot.band_h != slot.ih or slot.rgba.len > kept_limit) return;
- kept_age += 1;
- for (&kept) |*k| if (k.*) |e| if (e.file == state.file and e.page == slot.page) {
- e.gpa.free(e.rgba);
- k.* = null;
- };
- while (true) {
- var total: usize = slot.rgba.len;
- var oldest: ?*?Kept = null;
- var free: ?*?Kept = null;
- for (&kept) |*k| if (k.*) |e| {
- total += e.rgba.len;
- if (oldest == null or e.age < oldest.?.*.?.age) oldest = k;
- } else if (free == null) {
- free = k;
- };
- if (total <= kept_limit) if (free) |f| {
- f.* = .{ .file = state.file, .page = slot.page, .request = slot.request, .tint_key = slot.tint_key.?, .rgba = slot.rgba, .iw = slot.iw, .ih = slot.ih, .gpa = gpa, .age = kept_age };
- slot.rgba = &.{};
- return;
- };
- const o = oldest.?;
- o.*.?.gpa.free(o.*.?.rgba);
- o.* = null;
- }
-}
-
-/// The kept page for this file, page, request and tint, into `slot`.
-fn unkeep(state: *State, slot: *Raster, request: RenderRequest, tint_key: TintKey) bool {
- for (&kept) |*k| if (k.*) |e| if (e.file == state.file and e.page == slot.page and e.request.eql(request) and e.tint_key.eql(tint_key)) {
- k.* = null;
- slot.rgba = e.rgba;
- slot.iw = e.iw;
- slot.ih = e.ih;
- slot.band_y = 0;
- slot.band_h = e.ih;
- slot.request = request;
- slot.request_valid = true;
- slot.tint_key = tint_key;
- slot.tried = true;
- slot.baked_valid = true;
- state.next_raster_revision +%= 1;
- if (state.next_raster_revision == 0) state.next_raster_revision = 1;
- slot.revision = state.next_raster_revision;
- state.landed +|= 1;
- return true;
- };
- return false;
-}
-
-/// Every kept page freed: a shell's end, before its allocators' leak check.
-pub fn dropKept() void {
- if (comptime !enabled) return;
- for (&kept) |*k| if (k.*) |e| {
- e.gpa.free(e.rgba);
- k.* = null;
- };
-}
-
-const Lane = if (enabled) struct {
- /// The lane's cloned context and its own document (`Document.laneClone`):
- /// made on the loop at its first job, opened by its first job, used by
- /// one job at a time, closed with the State.
- doc: ?Document = null,
- job: ?*Job = null,
- future: ?std.Io.Future(void) = null,
- io: std.Io = undefined,
- /// Its document is open and its fonts loaded by a job (`collect`).
- warm: bool = false,
-} else void;
-
-pub const SectionsOutput = if (enabled) struct {
- pane: usize,
- serial: u32,
- revision: u32,
-} else void;
-
-pub const SelectionUpdate = enum { failed, stationary, unchanged, changed };
-
-pub const State = if (enabled) struct {
- /// What the replay digest leaves out (src/walk.zig): the pages' pixels,
- /// rendered from the document, and the lanes rendering them.
- pub const replica = .{ .derived = .{ "rasters", "rasters_len" }, .local = .{"lanes"} };
- path: []u8,
- document: Document,
- page: usize = 0,
- page_count: usize,
- page_sizes: []pdf.PageSize,
- page_starts: []u64,
- page_heights: []u32,
- document_height: u64 = 0,
- layout_viewport_w: u32 = 0,
- layout_viewport_h: u32 = 0,
- layout_fit: FitMode = .width,
- layout_valid: bool = false,
- document_scroll_y: f64 = 0,
- /// Where the core stood at the last frame (`drawn_y`), and what moved
- /// it since by the pixel (`direct_y`: a touchpad, a relayout).
- drawn_y: f64 = 0,
- direct_y: f64 = 0,
- /// The last kick was a jump past a body (renderFrame's `far`).
- far: bool = false,
- scroll_to_page_pending: bool = true,
- rasters: [raster_max]Raster = undefined,
- rasters_len: usize = 0,
- /// Rasters installed since the last draw (the probe's `landed`).
- landed: u16 = 0,
- lanes: [lane_count]Lane = @splat(.{}),
- render_gen: u32 = 0,
- /// The paper a page shows until its raster lands, tinted (`draw`).
- blank: [4]u8 = .{ 255, 255, 255, 255 },
- /// Which way the strip last went: the page past it is rendered ahead.
- ahead: i2 = 1,
- /// `page_sizes` past the first are assumed (the first's) until a
- /// lane's pass lands, generation `sizes_gen` (0: not asked yet).
- sizes_pending: bool = false,
- sizes_gen: u32 = 0,
- /// The pass's sizes, landed, for the next draw (gpa-owned).
- sizes_ready: []pdf.PageSize = &.{},
- /// The next relayout keeps the strip's motion (a retarget, not a
- /// reset): the sizes landed under it, nothing the user did.
- relayout_keeps_motion: bool = false,
- /// Which file this is, for the kept pages (`fileKey`).
- file: u64 = 0,
- spare: [raster_spare][]u8 = @splat(&.{}),
- spare_len: usize = 0,
- layout_anchor_pending: bool = false,
- layout_anchor_page: usize = 0,
- layout_anchor_fraction: f64 = 0,
- next_raster_revision: u32 = 0,
- scroll_travel: f64 = 0,
- fit: FitMode = .width,
- tint: TintMode = .filtered,
- pan_x: u16 = 0,
- pan_y: u16 = 0,
- highlights_dirty: bool = false,
- search_reveal_pending: bool = false,
- search_results: ?pdf.SearchResults = null,
- selection: ?pdf.Selection = null,
- selection_page: ?usize = null,
- selection_text: []u8 = &.{},
- selection_anchor: ?Point = null,
- selection_head: ?Point = null,
- drag_anchor: ?Point = null,
- drag_head: ?Point = null,
- text: []u8 = &.{},
- text_tried: bool = false,
- text_scroll: usize = 0,
- text_scroll_clamp_pending: bool = false,
- search_query: []u8 = &.{},
- search_hit: usize = 0,
- reveal_viewport_w: u32 = 0,
- reveal_viewport_h: u32 = 0,
- reveal_fit: FitMode = .width,
- reveal_viewport_valid: bool = false,
- outline: ?pdf.Outline = null,
- outline_tried: bool = false,
- sections_output: ?SectionsOutput = null,
- outline_reveal_pending: ?pdf.OutlineInternalDestination = null,
-
- /// Read whole and opened from memory (the bridge copies), never from
- /// the file itself: MuPDF reads a file lazily at every page, and the
- /// path may be a mount this editor serves, which only a read that
- /// gives the turn up can come back from (`filesystem.readFile`).
- pub fn open(gpa: std.mem.Allocator, path: []const u8, page_one_based: usize) !@This() {
- const local = filesystem.localPath(path) orelse return error.NonLocalPath;
- const bytes = try filesystem.readFile(gpa, local);
- defer gpa.free(bytes);
- return openBytes(gpa, path, bytes, page_one_based);
- }
-
- pub fn openBytes(gpa: std.mem.Allocator, path: []const u8, bytes: []const u8, page_one_based: usize) !@This() {
- var state = try initDocument(gpa, path, try Document.openBytes(bytes), page_one_based);
- state.file = fileKey(path, bytes);
- return state;
- }
-
- fn initDocument(gpa: std.mem.Allocator, path: []const u8, opened: Document, page_one_based: usize) !@This() {
- var document = opened;
- errdefer document.deinit();
- const page_sizes = try gpa.alloc(pdf.PageSize, document.pages);
- errdefer gpa.free(page_sizes);
- // With lanes, only the first page is measured here and the strip
- // is laid out as if every page had its size, until a lane's pass
- // over the rest lands (`submitSizes`): 5363 pages of the SDM took
- // the open 700 ms in Debug, 26 in ReleaseSafe, on the loop.
- const assumed = workers != null and document.pages > 1;
- if (assumed) {
- @memset(page_sizes, try document.pageSize(0));
- } else for (page_sizes, 0..) |*size, page| size.* = try document.pageSize(page);
- const page_starts = try gpa.alloc(u64, document.pages);
- errdefer gpa.free(page_starts);
- const page_heights = try gpa.alloc(u32, document.pages);
- errdefer gpa.free(page_heights);
- const owned_path = try gpa.dupe(u8, path);
- errdefer gpa.free(owned_path);
- return .{
- .path = owned_path,
- .document = document,
- .sizes_pending = assumed,
- .page = if (page_one_based > 0)
- @min(page_one_based - 1, document.pages - 1)
- else
- 0,
- .page_count = document.pages,
- .page_sizes = page_sizes,
- .page_starts = page_starts,
- .page_heights = page_heights,
- };
- }
-
- pub fn reload(state: *@This(), gpa: std.mem.Allocator) !void {
- const preserve_anchor = !state.scroll_to_page_pending and
- (state.layout_anchor_pending or
- (state.layout_valid and state.page_count > 0 and state.document_height > 0));
- var anchor_page: usize = state.layout_anchor_page;
- var anchor_fraction: f64 = state.layout_anchor_fraction;
- if (preserve_anchor and !state.layout_anchor_pending) {
- anchor_page = pageAtOffset(state, state.document_scroll_y);
- const start: f64 = @floatFromInt(state.page_starts[anchor_page]);
- const height: f64 = @floatFromInt(@max(@as(u32, 1), state.page_heights[anchor_page]));
- anchor_fraction = std.math.clamp(
- (state.document_scroll_y - start) / height,
- 0,
- 1,
- );
- }
-
- var fresh = try @This().open(gpa, state.path, state.page + 1);
- errdefer fresh.deinit(gpa);
- if (state.search_query.len > 0)
- fresh.search_query = try gpa.dupe(u8, state.search_query);
-
- fresh.fit = state.fit;
- fresh.tint = state.tint;
- fresh.pan_x = state.pan_x;
- fresh.pan_y = state.pan_y;
- fresh.text_scroll = state.text_scroll;
- fresh.text_scroll_clamp_pending = true;
- fresh.search_hit = state.search_hit;
- fresh.highlights_dirty = fresh.search_query.len > 0;
- fresh.search_reveal_pending = state.search_reveal_pending;
- fresh.reveal_viewport_w = state.reveal_viewport_w;
- fresh.reveal_viewport_h = state.reveal_viewport_h;
- fresh.reveal_fit = state.reveal_fit;
- fresh.reveal_viewport_valid = state.reveal_viewport_valid;
- // Revisions are part of the backend texture key. Resetting this counter
- // while the pane serial stays live can alias a cached pre-reload page.
- fresh.next_raster_revision = state.next_raster_revision;
- fresh.sections_output = state.sections_output;
- if (preserve_anchor) {
- fresh.scroll_to_page_pending = false;
- fresh.layout_anchor_pending = true;
- fresh.layout_anchor_page = anchor_page;
- fresh.layout_anchor_fraction = anchor_fraction;
- }
-
- var old = state.*;
- state.* = fresh;
- old.deinit(gpa);
- }
-
- pub fn invalidateRaster(state: *@This(), page: usize) void {
- if (rasterForPage(state, page)) |raster| raster.tried = false;
- }
-
- pub fn invalidateAllRasters(state: *@This()) void {
- for (state.rasters[0..state.rasters_len]) |*raster| {
- if (raster.valid) raster.tried = false;
- }
- }
-
- fn retireRgba(state: *@This(), gpa: std.mem.Allocator, rgba: []u8) void {
- if (rgba.len == 0) return;
- if (state.spare_len == state.spare.len) return gpa.free(rgba);
- state.spare[state.spare_len] = rgba;
- state.spare_len += 1;
- }
-
- fn retireRaster(state: *@This(), gpa: std.mem.Allocator, raster: *Raster) void {
- if (raster.clean.len > 0) gpa.free(raster.clean);
- gpa.free(raster.baked);
- state.retireRgba(gpa, raster.rgba);
- raster.* = .{};
- }
-
- fn claimRgba(state: *@This(), gpa: std.mem.Allocator, bytes: usize) ?[]u8 {
- for (state.spare[0..state.spare_len], 0..) |candidate, index| {
- if (candidate.len != bytes) continue;
- state.spare_len -= 1;
- state.spare[index] = state.spare[state.spare_len];
- return candidate;
- }
- return gpa.alloc(u8, bytes) catch null;
- }
-
- fn trimSpares(state: *@This(), gpa: std.mem.Allocator) void {
- while (state.spare_len > 1) {
- state.spare_len -= 1;
- gpa.free(state.spare[state.spare_len]);
- }
- }
-
- fn dropSearchResults(state: *@This(), gpa: std.mem.Allocator) void {
- if (state.search_results) |*results| results.deinit(gpa);
- state.search_results = null;
- }
-
- fn dropSelection(state: *@This(), gpa: std.mem.Allocator) void {
- if (state.selection) |*selection| selection.deinit(gpa);
- state.selection = null;
- state.selection_page = null;
- if (state.selection_text.len > 0) gpa.free(state.selection_text);
- state.selection_text = &.{};
- state.selection_anchor = null;
- state.selection_head = null;
- }
-
- pub fn setSelection(
- state: *@This(),
- gpa: std.mem.Allocator,
- start: Point,
- end: Point,
- invalidate_raster: bool,
- ) SelectionUpdate {
- if (state.selection != null and state.selection_page == state.page and
- state.selection_anchor != null and state.selection_head != null and
- state.selection_anchor.?.x == start.x and state.selection_anchor.?.y == start.y and
- state.selection_head.?.x == end.x and state.selection_head.?.y == end.y) return .unchanged;
- var selection = state.document.select(gpa, state.page, start, end) catch return .failed;
- const text = state.document.copySelection(
- gpa,
- state.page,
- selection.start,
- selection.end,
- ) catch {
- selection.deinit(gpa);
- return .failed;
- };
-
- const old_page = state.selection_page;
- state.dropSelection(gpa);
- state.selection = selection;
- state.selection_page = state.page;
- state.selection_text = text;
- state.selection_anchor = start;
- state.selection_head = end;
- if (old_page) |page| if (page != state.page) state.invalidateRaster(page);
- if (invalidate_raster) state.invalidateRaster(state.page);
- return .changed;
- }
-
- pub fn clearDrag(state: *@This()) void {
- state.drag_anchor = null;
- state.drag_head = null;
- }
-
- pub fn clearSelection(state: *@This(), gpa: std.mem.Allocator) void {
- const page = state.selection_page;
- state.dropSelection(gpa);
- if (page) |selected_page| state.invalidateRaster(selected_page);
- }
-
- /// Drops the selection and the search; true when there was one.
- pub fn cancelChrome(state: *@This(), gpa: std.mem.Allocator) bool {
- const had = state.selection != null or state.search_query.len > 0;
- state.clearDrag();
- state.clearSelection(gpa);
- if (state.search_query.len == 0) return had;
- state.dropSearchQuery(gpa);
- state.invalidateRaster(state.page);
- return had;
- }
-
- fn invalidatePage(state: *@This(), gpa: std.mem.Allocator) void {
- state.dropSearchResults(gpa);
- state.clearDrag();
- if (state.text.len > 0) gpa.free(state.text);
- state.text = &.{};
- state.text_tried = false;
- state.text_scroll = 0;
- state.text_scroll_clamp_pending = false;
- state.highlights_dirty = state.search_query.len > 0;
- state.search_reveal_pending = state.search_query.len > 0;
- state.search_hit = 0;
- }
-
- fn dropSearchQuery(state: *@This(), gpa: std.mem.Allocator) void {
- if (state.search_query.len > 0) gpa.free(state.search_query);
- state.search_query = &.{};
- state.search_hit = 0;
- state.dropSearchResults(gpa);
- state.highlights_dirty = false;
- state.search_reveal_pending = false;
- }
-
- pub fn setSearchQuery(state: *@This(), gpa: std.mem.Allocator, query: []const u8) !void {
- if (std.mem.eql(u8, state.search_query, query)) return;
- const owned = try gpa.dupe(u8, query);
- state.dropSearchQuery(gpa);
- state.search_query = owned;
- state.highlights_dirty = query.len > 0;
- state.search_reveal_pending = query.len > 0;
- state.invalidateRaster(state.page);
- }
-
- pub fn ensureText(state: *@This(), gpa: std.mem.Allocator) []const u8 {
- if (!state.text_tried) {
- state.text_tried = true;
- state.text = state.document.pageText(gpa, state.page) catch &.{};
- }
- if (state.text_scroll_clamp_pending) {
- const lines = std.mem.count(u8, state.text, "\n") + 1;
- state.text_scroll = @min(state.text_scroll, lines - 1);
- state.text_scroll_clamp_pending = false;
- }
- return state.text;
- }
-
- pub fn resolveSearch(state: *@This(), gpa: std.mem.Allocator) void {
- if (!state.highlights_dirty) return;
- state.highlights_dirty = false;
- state.dropSearchResults(gpa);
- if (state.search_query.len == 0) return;
- const results = state.document.search(gpa, state.page, state.search_query) catch return;
- state.search_hit = if (results.hit_count == 0)
- 0
- else
- @min(state.search_hit, results.hit_count - 1);
- state.search_results = results;
- }
-
- /// Whether page `page` (one-based) holds search hit `hit` (one-based) of
- /// the pane's search: none asked, no hit is there.
- pub fn hitExists(state: *@This(), gpa: std.mem.Allocator, page: usize, hit: usize) bool {
- if (hit == 0) return true;
- if (state.search_query.len == 0 or page == 0 or page > state.page_count) return false;
- var results = state.document.search(gpa, page - 1, state.search_query) catch return false;
- defer results.deinit(gpa);
- return hit <= results.hit_count;
- }
-
- pub fn ensureOutline(state: *@This(), gpa: std.mem.Allocator) ?*const pdf.Outline {
- if (!state.outline_tried) {
- state.outline_tried = true;
- state.outline = state.document.outline(gpa) catch null;
- }
- return if (state.outline) |*outline| outline else null;
- }
-
- pub fn renderSections(
- state: *@This(),
- pdf_gpa: std.mem.Allocator,
- output_gpa: std.mem.Allocator,
- ) ![]u8 {
- const entries: []const pdf.OutlineEntry = if (state.ensureOutline(pdf_gpa)) |outline|
- outline.entries
- else
- &.{};
- return SectionRows.render(output_gpa, state.path, entries);
- }
-
- pub fn sectionDestination(
- state: *@This(),
- gpa: std.mem.Allocator,
- ordinal: usize,
- ) ?pdf.OutlineDestination {
- const outline = state.ensureOutline(gpa) orelse return null;
- return SectionRows.resolve(outline.entries, ordinal);
- }
-
- /// Apply the one-based page/hit location encoded in a PDF search row.
- /// Returns whether host pane cursor chrome must be reset.
- pub fn focusLocation(
- state: *@This(),
- gpa: std.mem.Allocator,
- line: usize,
- column: usize,
- ) bool {
- const changed = line > 0 and state.activatePage(gpa, line - 1, true);
- if (column > 0 and state.search_query.len > 0) {
- state.search_hit = column - 1;
- state.search_reveal_pending = true;
- }
- return changed;
- }
-
- /// Change the document page while leaving pane cursor/selection chrome to
- /// the UI adapter. Returns whether that pane-local chrome must be reset.
- pub fn activatePage(
- state: *@This(),
- gpa: std.mem.Allocator,
- page: usize,
- reveal: bool,
- ) bool {
- state.outline_reveal_pending = null;
- const next = @min(page, state.page_count -| 1);
- const changed = next != state.page;
- if (changed) {
- state.invalidatePage(gpa);
- state.page = next;
- }
- if (reveal) {
- state.scroll_to_page_pending = true;
- if (state.layout_valid) {
- state.document_scroll_y = @floatFromInt(state.page_starts[next]);
- state.scroll_to_page_pending = false;
- }
- } else {
- state.search_reveal_pending = false;
- }
- return changed;
- }
-
- pub fn toggleFit(state: *@This()) void {
- state.fit = if (state.fit == .width) .height else .width;
- state.pan_x = 0;
- state.pan_y = 0;
- state.layout_valid = false;
- state.scroll_to_page_pending = true;
- state.search_reveal_pending = state.search_query.len > 0;
- }
-
- pub fn toggleTint(state: *@This()) void {
- state.tint = state.tint.next();
- state.invalidateAllRasters();
- }
-
- pub fn queueOutlineReveal(
- state: *@This(),
- destination: pdf.OutlineInternalDestination,
- ) void {
- state.scroll_to_page_pending = false;
- state.layout_anchor_pending = false;
- state.outline_reveal_pending = destination;
- }
-
- pub fn deinit(state: *@This(), gpa: std.mem.Allocator) void {
- // Every lane stopped and joined, its job dropped, its document
- // closed, before the document its context was cloned from.
- for (&state.lanes) |*lane| {
- if (lane.job) |job| {
- @atomicStore(c_int, &job.cookie.abort, 1, .release);
- pardes.turn.yield();
- lane.future.?.await(lane.io);
- pardes.turn.back();
- job.gen = 0;
- land(state, gpa, job);
- }
- if (lane.doc) |*doc| doc.deinit();
- lane.* = .{};
- }
- gpa.free(state.path);
- for (state.rasters[0..state.rasters_len]) |*raster| keepPage(state, gpa, raster);
- for (state.rasters[0..state.rasters_len]) |raster| {
- if (raster.rgba.len > 0) gpa.free(raster.rgba);
- if (raster.clean.len > 0) gpa.free(raster.clean);
- gpa.free(raster.baked);
- }
- for (state.spare[0..state.spare_len]) |rgba| gpa.free(rgba);
- if (state.sizes_ready.len > 0) gpa.free(state.sizes_ready);
- gpa.free(state.page_sizes);
- gpa.free(state.page_starts);
- gpa.free(state.page_heights);
- if (state.text.len > 0) gpa.free(state.text);
- if (state.search_query.len > 0) gpa.free(state.search_query);
- if (state.search_results) |*results| results.deinit(gpa);
- if (state.selection) |*selection| selection.deinit(gpa);
- if (state.selection_text.len > 0) gpa.free(state.selection_text);
- if (state.outline) |*outline| outline.deinit(gpa);
- state.document.deinit();
- state.* = undefined;
- }
-} else void;
-
-pub const SearchOutput = struct {
- bytes: usize = 0,
- rows: usize = 0,
- anchor: ?usize = null,
-};
-
-pub fn textLines(
- state: *State,
- gpa: std.mem.Allocator,
- arena: std.mem.Allocator,
-) ![]const []const u8 {
- if (comptime !enabled) return &.{};
- const page_text = state.ensureText(gpa);
- const lines = try arena.alloc([]const u8, std.mem.count(u8, page_text, "\n") + 1);
- var it = std.mem.splitScalar(u8, page_text, '\n');
- var n: usize = 0;
- while (it.next()) |line| : (n += 1) lines[n] = line;
- return lines;
-}
-
-pub fn visibleText(
- state: *State,
- gpa: std.mem.Allocator,
- arena: std.mem.Allocator,
- max_rows: usize,
-) ![]const u8 {
- if (comptime !enabled) return "";
- const page_text = state.ensureText(gpa);
- var start: usize = 0;
- for (0..state.text_scroll) |_| {
- const newline = std.mem.indexOfScalarPos(u8, page_text, start, '\n') orelse
- return arena.dupe(u8, "");
- start = newline + 1;
- }
- if (max_rows == 0) return arena.dupe(u8, "");
-
- var end = start;
- var row: usize = 0;
- while (row < max_rows) : (row += 1) {
- const newline = std.mem.indexOfScalarPos(u8, page_text, end, '\n') orelse {
- end = page_text.len;
- break;
- };
- if (row + 1 == max_rows) {
- end = newline;
- break;
- }
- end = newline + 1;
- }
- return arena.dupe(u8, page_text[start..end]);
-}
-
-/// Materialize exact MuPDF logical hits as `path:PAGE:HIT query` rows. The
-/// same hit numbering drives persistent highlights and later reveal actions.
-pub fn searchRows(
- state: *State,
- gpa: std.mem.Allocator,
- pattern: []const u8,
- from_cursor: bool,
- out: []u8,
-) !SearchOutput {
- if (comptime !enabled) return .{};
- try state.setSearchQuery(gpa, pattern);
- const shown = std.fs.path.basename(state.path);
- var result: SearchOutput = .{};
- const max_hits = 512;
- var snippet_len = @min(pattern.len, 200);
- while (snippet_len > 0 and snippet_len < pattern.len and pattern[snippet_len] & 0xc0 == 0x80)
- snippet_len -= 1;
- const snippet = pattern[0..snippet_len];
- for (0..state.page_count) |page| {
- if (result.rows >= max_hits) break;
- var found = try state.document.search(gpa, page, pattern);
- defer found.deinit(gpa);
-
- const cursor_hit: ?usize = if (from_cursor and page == state.page and state.selection_page == page) cursor: {
- const selection = state.selection orelse break :cursor null;
- for (found.quads) |item| {
- const q = item.quad;
- const center: Point = .{
- .x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4,
- .y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4,
- };
- if (selection.contains(center)) break :cursor item.hit;
- }
- break :cursor null;
- } else null;
-
- for (0..found.hit_count) |hit_index| {
- if (result.rows >= max_hits) break;
- // A row that does not fit ends the list.
- const line = std.fmt.bufPrint(out[result.bytes..], "{s}:{d}:{d} {s}\n", .{
- shown, page + 1, hit_index + 1, snippet,
- }) catch return result;
- if (from_cursor and
- (page < state.page or
- (page == state.page and cursor_hit != null and hit_index <= cursor_hit.?)))
- result.anchor = result.rows;
- result.bytes += line.len;
- result.rows += 1;
- }
- }
- return result;
-}
-
-pub const Viewport = struct { pixel_w: u32, pixel_h: u32 };
-pub const VisiblePages = struct { first: usize = 0, len: usize = 0 };
-pub const PanAxis = enum { horizontal, vertical };
-pub const PanResult = enum { moved, edge, unavailable };
-pub const ScrollResult = struct { active_page: usize };
-pub const CellPixels = struct { w: u16, h: u16 };
-
-/// How a native pixel attachment is placed in its pane body. `contain` is the
-/// historical image-pane policy: shrink only when necessary and keep the
-/// image at the top left. The axis-specific modes may enlarge, letterbox the
-/// unconstrained axis, or crop it when it overflows.
-pub const NativeFit = if (enabled) enum { contain, width, height } else enum { contain };
-
-fn panOffset(overflow: u32, pan: u16) u32 {
- if (overflow == 0 or pan == 0) return 0;
- if (pan == std.math.maxInt(u16)) return overflow;
- // Round, rather than truncate, so the midpoint is the visual midpoint.
- return @intCast((@as(u64, overflow) * pan + std.math.maxInt(u16) / 2) / std.math.maxInt(u16));
-}
-
-fn fitWidth(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_y: u16) ?surface.NativeGeometry {
- const scaled_h = @as(u64, src_h) * body_w;
- if (scaled_h <= @as(u64, body_h) * src_w) {
- const full_h: u32 = @intCast(@max(1, scaled_h / src_w));
- return .{
- .src = .{ .w = src_w, .h = src_h },
- .dst = .{ .y = (body_h - full_h) / 2, .w = body_w, .h = full_h },
- };
- }
-
- // Retain the largest whole source-pixel crop which cannot extend beyond
- // the body at this scale. The sub-pixel remainder becomes at most a small
- // centered letterbox instead of leaking into an adjacent cell in Kitty.
- const crop_h_wide = @as(u64, body_h) * src_w / body_w;
- if (crop_h_wide == 0) return null;
- const crop_h: u32 = @min(src_h, @as(u32, @intCast(crop_h_wide)));
- const dst_h: u32 = @min(body_h, @max(1, @as(u32, @intCast(@as(u64, crop_h) * body_w / src_w))));
- return .{
- .src = .{
- .y = panOffset(src_h - crop_h, pan_y),
- .w = src_w,
- .h = crop_h,
- },
- .dst = .{ .y = (body_h - dst_h) / 2, .w = body_w, .h = dst_h },
- };
-}
-
-fn fitHeight(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_x: u16) ?surface.NativeGeometry {
- const scaled_w = @as(u64, src_w) * body_h;
- if (scaled_w <= @as(u64, body_w) * src_h) {
- const full_w: u32 = @intCast(@max(1, scaled_w / src_h));
- return .{
- .src = .{ .w = src_w, .h = src_h },
- .dst = .{ .x = (body_w - full_w) / 2, .w = full_w, .h = body_h },
- };
- }
-
- const crop_w_wide = @as(u64, body_w) * src_h / body_h;
- if (crop_w_wide == 0) return null;
- const crop_w: u32 = @min(src_w, @as(u32, @intCast(crop_w_wide)));
- const dst_w: u32 = @min(body_w, @max(1, @as(u32, @intCast(@as(u64, crop_w) * body_h / src_h))));
- return .{
- .src = .{
- .x = panOffset(src_w - crop_w, pan_x),
- .w = crop_w,
- .h = src_h,
- },
- .dst = .{ .x = (body_w - dst_w) / 2, .w = dst_w, .h = body_h },
- };
-}
-
-/// Compute native image placement without floating point. Source dimensions
-/// are limited to u32 because SDL's texture API and Kitty's crop parameters
-/// cannot describe anything larger. Kitty applies the stricter u16 check at
-/// its protocol boundary.
-pub fn nativeGeometry(
- iw: usize,
- ih: usize,
- body_pixel_w: u32,
- body_pixel_h: u32,
- fit: NativeFit,
- pan_x: u16,
- pan_y: u16,
-) ?surface.NativeGeometry {
- if (comptime !enabled) {
- return surface.containGeometry(iw, ih, body_pixel_w, body_pixel_h);
- }
- if (iw == 0 or ih == 0 or body_pixel_w == 0 or body_pixel_h == 0 or
- iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null;
-
- const src_w: u32 = @intCast(iw);
- const src_h: u32 = @intCast(ih);
- return switch (fit) {
- .width => fitWidth(src_w, src_h, body_pixel_w, body_pixel_h, pan_y),
- .height => fitHeight(src_w, src_h, body_pixel_w, body_pixel_h, pan_x),
- // Pan is not contain's: it keeps the top-left placement.
- .contain => surface.containGeometry(iw, ih, body_pixel_w, body_pixel_h),
- };
-}
-
-test "native fit width handles portrait crop, pan extrema, and landscape letterbox" {
- if (comptime !enabled) return;
- const top = nativeGeometry(600, 1000, 800, 600, .width, 0, 0).?;
- try std.testing.expectEqual(surface.RectPx{ .w = 600, .h = 450 }, top.src);
- try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, top.dst);
-
- const middle = nativeGeometry(600, 1000, 800, 600, .width, 0, 32768).?;
- try std.testing.expectEqual(@as(u32, 275), middle.src.y);
- const bottom = nativeGeometry(600, 1000, 800, 600, .width, 65535, 65535).?;
- try std.testing.expectEqual(@as(u32, 550), bottom.src.y);
-
- const landscape = nativeGeometry(1000, 600, 800, 600, .width, 0, 65535).?;
- try std.testing.expectEqual(surface.RectPx{ .w = 1000, .h = 600 }, landscape.src);
- try std.testing.expectEqual(surface.RectPx{ .y = 60, .w = 800, .h = 480 }, landscape.dst);
-}
-
-test "native fit height handles portrait letterbox and landscape crop" {
- if (comptime !enabled) return;
- const portrait = nativeGeometry(600, 1000, 800, 600, .height, 65535, 0).?;
- try std.testing.expectEqual(surface.RectPx{ .w = 600, .h = 1000 }, portrait.src);
- try std.testing.expectEqual(surface.RectPx{ .x = 220, .w = 360, .h = 600 }, portrait.dst);
-
- const left = nativeGeometry(1000, 600, 800, 600, .height, 0, 0).?;
- try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, left.src);
- try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, left.dst);
- const right = nativeGeometry(1000, 600, 800, 600, .height, 65535, 0).?;
- try std.testing.expectEqual(@as(u32, 200), right.src.x);
-}
-
-test "native fit odd ratios round inward and map points through letterboxes and crops" {
- if (comptime !enabled) return;
- const width = nativeGeometry(403, 211, 101, 47, .width, 0, 32768).?;
- try std.testing.expectEqual(surface.RectPx{ .y = 12, .w = 403, .h = 187 }, width.src);
- try std.testing.expectEqual(surface.RectPx{ .w = 101, .h = 46 }, width.dst);
- const mapped = width.sourcePoint(100, 45).?;
- try std.testing.expect(mapped.x < width.src.x + width.src.w);
- try std.testing.expect(mapped.y < width.src.y + width.src.h);
- try std.testing.expect(width.sourcePoint(101, 46) == null);
-
- const height = nativeGeometry(403, 211, 101, 47, .height, 32768, 0).?;
- try std.testing.expectEqual(surface.RectPx{ .w = 403, .h = 211 }, height.src);
- try std.testing.expectEqual(surface.RectPx{ .x = 6, .w = 89, .h = 47 }, height.dst);
- try std.testing.expect(height.sourcePoint(5, 20) == null);
- try std.testing.expect(height.sourcePoint(6, 20) != null);
-}
-
-test "native fit modes reject what the backend contract cannot represent and are total at extreme aspect ratios" {
- if (comptime !enabled) return;
- try std.testing.expect(nativeGeometry(10, 10, 0, 20, .width, 0, 0) == null);
- if (@bitSizeOf(usize) > 32)
- try std.testing.expect(nativeGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20, .height, 0, 0) == null);
-
- const largest = std.math.maxInt(u32);
- try std.testing.expect(nativeGeometry(1, largest, largest, 1, .width, 0, 65535) == null);
- try std.testing.expect(nativeGeometry(largest, 1, 1, largest, .height, 65535, 0) == null);
-
- const wide = nativeGeometry(largest, 1, largest, 1, .width, 0, 0).?;
- try std.testing.expectEqual(surface.RectPx{ .w = largest, .h = 1 }, wide.dst);
- const tall = nativeGeometry(1, largest, 1, largest, .height, 0, 0).?;
- try std.testing.expectEqual(surface.RectPx{ .w = 1, .h = largest }, tall.dst);
-}
-
-const PlacedGeometry = struct {
- geometry: surface.NativeGeometry,
- pixel_offset_y: f32,
-};
-
-pub const PlacedRaster = if (enabled) struct {
- page: usize,
- revision: u32,
- fit: FitMode,
- pan_x: u16,
- geometry: surface.NativeGeometry,
- pixel_offset_y: f32,
- rgba: []const u8,
- width: usize,
- band_height: usize,
-} else void;
-
-const VisibleRows = struct {
- base: surface.NativeGeometry,
- y0: u32,
- y1: u32,
- dst_y: u32,
- dst_h: u32,
- pixel_offset_y: f32,
-};
-
-/// The raster a pane asks for. The page is shown `viewport.pixel_w` wide
-/// (fit width) or `pixel_h` tall (fit height), and the raster is never
-/// smaller than that, however tall the page: see `pdf.RenderRequest`.
-pub fn renderRequest(viewport: Viewport, policy: RasterPolicy, fit: FitMode) RenderRequest {
- if (comptime !enabled) return;
- return .{
- .dpi = policy.dpi,
- .minimum_width = if (policy.match_viewport) viewport.pixel_w else 0,
- .minimum_height = if (policy.match_viewport) viewport.pixel_h else 0,
- .max_dimension = policy.max_dimension,
- .display_width = if (fit == .width) viewport.pixel_w else 0,
- .display_height = if (fit == .height) viewport.pixel_h else 0,
- };
-}
-
-fn pageHeight(size: pdf.PageSize, viewport: Viewport, fit: FitMode) u32 {
- if (comptime !enabled) return 0;
- if (fit == .height) return viewport.pixel_h;
- const scaled = @as(f64, @floatFromInt(viewport.pixel_w)) *
- @as(f64, size.height) / @as(f64, size.width);
- return @max(1, @as(u32, @intFromFloat(@min(
- @as(f64, @floatFromInt(std.math.maxInt(u32))),
- @round(scaled),
- ))));
-}
-
-fn pageAtOffset(state: *const State, offset: f64) usize {
- if (comptime !enabled) return 0;
- const y: u64 = @intFromFloat(std.math.clamp(
- @floor(offset),
- 0,
- @as(f64, @floatFromInt(state.document_height -| 1)),
- ));
- var lo: usize = 0;
- var hi: usize = state.page_count;
- while (lo + 1 < hi) {
- const mid = lo + (hi - lo) / 2;
- if (state.page_starts[mid] <= y) lo = mid else hi = mid;
- }
- const end = state.page_starts[lo] + state.page_heights[lo];
- return if (y >= end and lo + 1 < state.page_count) lo + 1 else lo;
-}
-
-fn pageVisible(state: *const State, page: usize, y: f64, h: f64) bool {
- if (comptime !enabled) return false;
- const top = @as(f64, @floatFromInt(state.page_starts[page])) - y;
- const bottom = top + @as(f64, @floatFromInt(state.page_heights[page]));
- return bottom > 0 and top < h;
-}
-
-pub fn visiblePages(state: *const State, viewport: Viewport) VisiblePages {
- return pagesOver(state, state.document_scroll_y, @floatFromInt(viewport.pixel_h));
-}
-
-/// The pages over the strip from `y`, `h` pixels down.
-fn pagesOver(state: *const State, y: f64, h: f64) VisiblePages {
- if (comptime !enabled) return .{};
- var out: VisiblePages = .{};
- var page = pageAtOffset(state, y);
- if (page > 0 and pageVisible(state, page - 1, y, h)) page -= 1;
- out.first = page;
- while (page < state.page_count) : (page += 1) {
- const top = @as(f64, @floatFromInt(state.page_starts[page])) - y;
- if (top >= h) break;
- if (pageVisible(state, page, y, h)) out.len += 1;
- }
- return out;
-}
-
-fn visibleContains(visible: VisiblePages, page: usize) bool {
- return page >= visible.first and page - visible.first < visible.len;
-}
-
-pub fn rasterForPage(state: *State, page: usize) ?*Raster {
- if (comptime !enabled) return null;
- for (state.rasters[0..state.rasters_len]) |*raster|
- if (raster.valid and raster.page == page) return raster;
- return null;
-}
-
-fn rasterForPageConst(state: *const State, page: usize) ?*const Raster {
- if (comptime !enabled) return null;
- for (state.rasters[0..state.rasters_len]) |*raster|
- if (raster.valid and raster.page == page) return raster;
- return null;
-}
-
-fn visibleRows(
- state: *const State,
- viewport: Viewport,
- page: usize,
- iw: usize,
- ih: usize,
-) ?VisibleRows {
- if (comptime !enabled) return null;
- const page_h = state.page_heights[page];
- const base = nativeGeometry(
- iw,
- ih,
- viewport.pixel_w,
- page_h,
- switch (state.fit) {
- .width => .width,
- .height => .height,
- },
- state.pan_x,
- 0,
- ) orelse return null;
- if (base.dst.h == 0 or base.src.h == 0) return null;
-
- const scroll_floor = @floor(state.document_scroll_y);
- const fractional: f32 = @floatCast(state.document_scroll_y - scroll_floor);
- const scroll_i: i64 = @intFromFloat(@min(
- scroll_floor,
- @as(f64, @floatFromInt(std.math.maxInt(i64))),
- ));
- const start_i: i64 = @intCast(@min(
- state.page_starts[page],
- @as(u64, std.math.maxInt(i64)),
- ));
- const full_y = start_i - scroll_i + @as(i64, base.dst.y);
- const full_bottom = full_y + @as(i64, base.dst.h);
- const visible_y = @max(@as(i64, 0), full_y);
- const visible_bottom = @min(@as(i64, viewport.pixel_h), full_bottom);
- if (visible_bottom <= visible_y) return null;
-
- const rel_y0: u64 = @intCast(visible_y - full_y);
- const rel_y1: u64 = @intCast(visible_bottom - full_y);
- const src_y0: u32 = base.src.y + @as(u32, @intCast(
- rel_y0 * base.src.h / base.dst.h,
- ));
- const src_y1: u32 = base.src.y + @as(u32, @intCast(@min(
- @as(u64, base.src.h),
- (rel_y1 * base.src.h + base.dst.h - 1) / base.dst.h,
- )));
- if (src_y1 <= src_y0) return null;
- return .{
- .base = base,
- .y0 = src_y0,
- .y1 = src_y1,
- .dst_y = @intCast(visible_y),
- .dst_h = @intCast(visible_bottom - visible_y),
- .pixel_offset_y = -fractional,
- };
-}
-
-fn placedGeometry(
- state: *const State,
- raster: *const Raster,
- viewport: Viewport,
- page: usize,
-) ?PlacedGeometry {
- if (comptime !enabled) return null;
- const rows = visibleRows(state, viewport, page, raster.iw, raster.ih) orelse return null;
- const band_y: u32 = @intCast(raster.band_y);
- const band_end: u32 = @intCast(raster.band_y + raster.band_h);
- if (rows.y0 < band_y or rows.y1 > band_end) return null;
- return .{
- .geometry = .{
- .src = .{
- .x = rows.base.src.x,
- .y = rows.y0 - band_y,
- .w = rows.base.src.w,
- .h = rows.y1 - rows.y0,
- },
- .dst = .{
- .x = rows.base.dst.x,
- .y = rows.dst_y,
- .w = rows.base.dst.w,
- .h = rows.dst_h,
- },
- },
- .pixel_offset_y = rows.pixel_offset_y,
- };
-}
-
-pub fn placedRaster(state: *const State, viewport: Viewport, page: usize) ?PlacedRaster {
- if (comptime !enabled) return null;
- const raster = rasterForPageConst(state, page) orelse return null;
- if (raster.rgba.len == 0) return null;
- const placed = placedGeometry(state, raster, viewport, page) orelse return null;
- return .{
- .page = page,
- .revision = raster.revision,
- .fit = state.fit,
- .pan_x = state.pan_x,
- .geometry = placed.geometry,
- .pixel_offset_y = placed.pixel_offset_y,
- .rgba = raster.rgba,
- .width = raster.iw,
- .band_height = raster.band_h,
- };
-}
-
-pub fn activeGeometry(state: *const State, viewport: Viewport) ?surface.NativeGeometry {
- if (comptime !enabled) return null;
- const raster = rasterForPageConst(state, state.page) orelse return null;
- const placed = placedGeometry(state, raster, viewport, state.page) orelse return null;
- return placed.geometry;
-}
-
-pub fn pageReady(state: *const State, viewport: Viewport, page: usize) bool {
- if (comptime !enabled) return false;
- return placedRaster(state, viewport, page) != null;
-}
-
-fn slotShape(slot: *const Raster) pdf.Raster {
- const stride = slot.iw * 4;
- return .{ .width = slot.iw, .height = slot.ih, .stride = stride, .len = stride * slot.ih };
-}
-
-fn flinging(state: *const State, viewport: Viewport) bool {
- if (comptime !enabled) return false;
- return state.scroll_travel >= @as(f64, @floatFromInt(viewport.pixel_h));
-}
-
-/// The most rows one buffer of this page holds.
-fn bandCap(shape: pdf.Raster) usize {
- return @min(max_band_rows, pdf.max_owned_raster_bytes / @max(shape.stride, 1));
-}
-
-/// A page too tall for one buffer: see `max_band_rows`.
-pub fn isBanded(shape: pdf.Raster) bool {
- if (comptime !enabled) return false;
- return shape.height > bandCap(shape);
-}
-
-/// What a banded page's buffer is asked to hold. `target` is what a render
-/// covers: the rows on screen and a screenful either side, so scrolling finds
-/// the next rows ready (none while flinging, which only wants this frame's).
-/// `keep` is what the buffer must still cover to be kept: half a screenful
-/// either side, so a render happens once per half screenful scrolled, not on
-/// every frame.
-const Reach = enum { target, keep };
-
-fn wantedBand(
- state: *const State,
- viewport: Viewport,
- page: usize,
- shape: pdf.Raster,
- is_flinging: bool,
- reach: Reach,
-) pdf.Raster.Band {
- if (isBanded(shape)) return chunkBand(state, viewport, page, shape, is_flinging, reach);
- if (!is_flinging) return shape.wholePage();
- const rows = visibleRows(state, viewport, page, shape.width, shape.height) orelse
- return shape.wholePage();
- const first = (@as(usize, rows.y0) / band_grain) * band_grain;
- const last = std.math.divCeil(usize, @as(usize, rows.y1), band_grain) catch
- return shape.wholePage();
- return shape.band(first, last * band_grain - first);
-}
-
-fn chunkBand(
- state: *const State,
- viewport: Viewport,
- page: usize,
- shape: pdf.Raster,
- is_flinging: bool,
- reach: Reach,
-) pdf.Raster.Band {
- const rows = visibleRows(state, viewport, page, shape.width, shape.height) orelse
- return shape.band(0, chunk_rows);
- const seen: usize = rows.y1 - rows.y0;
- const margin: usize = if (is_flinging) 0 else switch (reach) {
- .target => seen,
- .keep => seen / 2,
- };
- const top = @as(usize, rows.y0) -| margin;
- const bottom = @min(shape.height, @as(usize, rows.y1) + margin);
- if (reach == .keep) return shape.band(top, bottom - top);
- var first = top / chunk_rows * chunk_rows;
- var last = @min(shape.height, (bottom + chunk_rows - 1) / chunk_rows * chunk_rows);
- const cap = bandCap(shape) / chunk_rows * chunk_rows;
- if (last - first > cap) {
- // The margins give way: what is on screen always fits.
- first = @as(usize, rows.y0) / chunk_rows * chunk_rows;
- last = @min(shape.height, first + cap);
- }
- return shape.band(first, last - first);
-}
-
-/// Fill `fresh` with the rows `want` of a banded page. Chunks the slot
-/// already holds, under this request and tint and with these highlights
-/// (`reuse`), are copied; the rest are rendered (`renderChunk`), then
-/// highlighted and tinted as `reconcile` does a whole page. `slot.clean`
-/// becomes the new rows' clean copy when `keep_clean`.
-fn fillBanded(
- state: *State,
- gpa: std.mem.Allocator,
- slot: *const Raster,
- request: RenderRequest,
- shape: pdf.Raster,
- want: pdf.Raster.Band,
- highlights: []const Highlight,
- tint_key: TintKey,
- fresh: []u8,
- keep_clean: bool,
- reuse: bool,
- clean_out: *[]u8,
-) bool {
- const tz = tracy.zone(@src(), "pdf.fill_banded");
- defer tz.end();
- const stride = shape.stride;
- const clean: []u8 = if (keep_clean) gpa.alloc(u8, fresh.len) catch return false else &.{};
- var filled = false;
- defer if (!filled and clean.len > 0) gpa.free(clean);
- const held = reuse and slot.rgba.len == slot.band_h * stride and
- (!keep_clean or slot.clean.len == slot.rgba.len);
- var scratch: []u8 = &.{};
- defer if (scratch.len > 0) gpa.free(scratch);
- const end = want.y + want.height;
- var y = want.y;
- while (y < end) {
- const rows = @min(chunk_rows - y % chunk_rows, end - y);
- const at = (y - want.y) * stride;
- const out = fresh[at..][0 .. rows * stride];
- if (held and slot.band_y <= y and y + rows <= slot.band_y + slot.band_h) {
- const from = (y - slot.band_y) * stride;
- @memcpy(out, slot.rgba[from..][0..out.len]);
- if (keep_clean) @memcpy(clean[at..][0..out.len], slot.clean[from..][0..out.len]);
- } else {
- if (scratch.len == 0)
- scratch = gpa.alloc(u8, (chunk_rows + 2 * chunk_overlap) * stride) catch return false;
- const target = if (keep_clean) clean[at..][0..out.len] else out;
- renderChunk(state, request, shape, slot.page, y, if (keep_clean) &.{} else highlights, target, scratch) catch
- return false;
- if (keep_clean) {
- @memcpy(out, target);
- state.document.paintHighlightsAt(slot.page, request, shape, shape.band(y, rows), highlights, out) catch
- return false;
- }
- pdf.tintRgba(out, tint_key.mode, tint_key.colors) catch return false;
- }
- y += rows;
- }
- filled = true;
- clean_out.* = clean;
- return true;
-}
-
-/// The `out.len / stride` rows of a banded page from row `y` (a chunk or
-/// its end), cut from a render reaching `chunk_overlap` rows past both.
-fn renderChunk(
- state: *State,
- request: RenderRequest,
- shape: pdf.Raster,
- page: usize,
- y: usize,
- highlights: []const Highlight,
- out: []u8,
- scratch: []u8,
-) !void {
- const tz = tracy.zone(@src(), "pdf.render_chunk");
- defer tz.end();
- const rows = out.len / shape.stride;
- const top = y -| chunk_overlap;
- const bottom = @min(shape.height, y + rows + chunk_overlap);
- const band = shape.band(top, bottom - top);
- const buf = scratch[0..band.len];
- try state.document.renderIntoAtWithPaper(page, request, shape, band, highlights, buf, pardes.platform == .macos);
- @memcpy(out, buf[(y - top) * shape.stride ..][0..out.len]);
-}
-
-fn reconcile(
- state: *State,
- gpa: std.mem.Allocator,
- request: RenderRequest,
- tint_key: TintKey,
- highlights: Highlights,
- visible: VisiblePages,
- viewport: Viewport,
-) void {
- if (comptime !enabled) return;
- const tz = tracy.zone(@src(), "pdf.reconcile");
- defer tz.end();
- collect(state, gpa);
- defer if (workers != null) sweep(state);
- if (state.sizes_pending and state.sizes_gen == 0) if (workers) |io| submitSizes(state, gpa, io);
-
- // Remove first so arriving pages can claim departing page buffers. Only
- // the final visible set can be seen, so a fling skips crossed-over pages.
- var index: usize = 0;
- while (index < state.rasters_len) {
- if (visibleContains(visible, state.rasters[index].page)) {
- index += 1;
- continue;
- }
- state.retireRaster(gpa, &state.rasters[index]);
- state.rasters_len -= 1;
- if (index != state.rasters_len)
- state.rasters[index] = state.rasters[state.rasters_len];
- }
-
- const is_flinging = flinging(state, viewport);
- var page = visible.first;
- const end = visible.first + visible.len;
- while (page < end) : (page += 1) {
- var raster = rasterForPage(state, page);
- if (raster == null) {
- if (state.rasters_len == state.rasters.len) continue;
- state.rasters[state.rasters_len] = .{ .valid = true, .page = page };
- state.rasters_len += 1;
- raster = &state.rasters[state.rasters_len - 1];
- if (workers != null) _ = unkeep(state, raster.?, request, tint_key);
- }
- const slot = raster.?;
- const page_highlights = highlights.forPage(page);
- const decorated = page_highlights.len > 0;
- const base_stale = !slot.request_valid or !slot.request.eql(request) or
- slot.tint_key == null or !slot.tint_key.?.eql(tint_key) or
- slot.rgba.len == 0 or slot.band_h == 0;
- const uncovered = !base_stale and uncovered: {
- const want = wantedBand(state, viewport, page, slotShape(slot), is_flinging, .keep);
- break :uncovered slot.band_y > want.y or
- slot.band_y + slot.band_h < want.y + want.height;
- };
- // A banded page moving on keeps the rows it has, if they are exactly
- // what a render would make now.
- const reuse = !base_stale and slot.baked_valid and sameHighlights(slot.baked, page_highlights);
- if (!base_stale and !uncovered) {
- if (slot.tried and slot.decorated == decorated and
- !(highlights.live and !sameHighlights(slot.baked, page_highlights))) continue;
- // Invalidated, but it already shows exactly these highlights
- // (a preview withdrawn that was never drawn, on every pointer
- // move over a page): nothing to render.
- if (slot.baked_valid and sameHighlights(slot.baked, page_highlights)) {
- slot.tried = true;
- continue;
- }
- // Only the highlights moved: repaint their rows in place.
- if (repaintHighlights(state, gpa, slot, request, tint_key, page_highlights)) continue;
- }
-
- // Off the loop: a lane renders the page whole and it lands on a
- // later frame (`collect`); until then the slot shows what it has.
- // A page too tall for one buffer is banded and stays on the loop.
- if (workers) |io| {
- if (pendingJob(state, slot)) |job| {
- if (job.request.eql(request) and job.tint_key.eql(tint_key)) continue;
- @atomicStore(c_int, &job.cookie.abort, 1, .release);
- slot.pending = 0;
- }
- if (slot.failed and slot.tried and slot.request_valid and slot.request.eql(request)) continue;
- const keep = pardes.platform != .macos and (decorated or slot.clean.len > 0);
- switch (submit(state, gpa, io, slot, request, tint_key, page_highlights, keep)) {
- .sent, .busy => continue,
- .loop => {},
- }
- }
-
- slot.tried = true;
- slot.request = request;
- slot.request_valid = true;
- const shape_or_null = shape: {
- const tz_measure = tracy.zone(@src(), "pdf.measure");
- defer tz_measure.end();
- break :shape state.document.measureRenderAt(page, request) catch null;
- };
- const shape = shape_or_null orelse continue;
- const want = wantedBand(state, viewport, page, shape, is_flinging, .target);
- const fresh = state.claimRgba(gpa, want.len) orelse continue;
- // A highlighted page keeps its clean rows for repaints.
- const keep_clean = pardes.platform != .macos and (decorated or slot.clean.len > 0);
- const filled = if (isBanded(shape)) banded: {
- var clean: []u8 = &.{};
- if (!fillBanded(state, gpa, slot, request, shape, want, page_highlights, tint_key, fresh, keep_clean, reuse, &clean))
- break :banded false;
- if (slot.clean.len > 0) gpa.free(slot.clean);
- slot.clean = clean;
- break :banded true;
- } else filled: {
- {
- const tz_render = tracy.zone(@src(), "pdf.render_into");
- defer tz_render.end();
- state.document.renderIntoAtWithPaper(
- page,
- request,
- shape,
- want,
- if (keep_clean) &.{} else page_highlights,
- fresh,
- pardes.platform == .macos,
- ) catch break :filled false;
- if (slot.clean.len != 0 and (!keep_clean or slot.clean.len != fresh.len)) {
- gpa.free(slot.clean);
- slot.clean = &.{};
- }
- if (keep_clean) {
- if (slot.clean.len == 0) slot.clean = gpa.alloc(u8, fresh.len) catch &.{};
- if (slot.clean.len == fresh.len) @memcpy(slot.clean, fresh);
- state.document.paintHighlightsAt(page, request, shape, want, page_highlights, fresh) catch
- break :filled false;
- }
- }
- const tz_tint = tracy.zone(@src(), "pdf.tint");
- defer tz_tint.end();
- pdf.tintRgba(fresh, tint_key.mode, tint_key.colors) catch
- break :filled false;
- break :filled true;
- };
- if (!filled) {
- state.retireRgba(gpa, fresh);
- // `clean` may already hold the band that failed.
- if (slot.clean.len > 0) gpa.free(slot.clean);
- slot.clean = &.{};
- continue;
- }
-
- state.retireRgba(gpa, slot.rgba);
- slot.rgba = fresh;
- slot.iw = shape.width;
- slot.ih = shape.height;
- slot.band_y = want.y;
- slot.band_h = want.height;
- slot.decorated = decorated;
- slot.tint_key = tint_key;
- if (gpa.dupe(Highlight, page_highlights)) |copy| {
- gpa.free(slot.baked);
- slot.baked = copy;
- slot.baked_valid = true;
- } else |_| {
- // Unrecorded highlights cannot be compared or diffed.
- slot.baked_valid = false;
- if (slot.clean.len > 0) gpa.free(slot.clean);
- slot.clean = &.{};
- }
- slot.patch_from = 0;
- slot.patch_rows = .{ .start = 0, .end = 0 };
- state.next_raster_revision +%= 1;
- if (state.next_raster_revision == 0) state.next_raster_revision = 1;
- slot.revision = state.next_raster_revision;
- state.landed +|= 1;
- }
- state.trimSpares(gpa);
-}
-
-fn pendingJob(state: *State, slot: *const Raster) ?*Job {
- if (slot.pending == 0) return null;
- for (state.lanes) |lane| if (lane.job) |job| if (job.gen == slot.pending) return job;
- return null;
-}
-
-/// Hands `slot`'s page to a free lane: `busy` when both are out (asked
-/// again next frame), `loop` when the page is banded or no lane can be had
-/// (the loop renders it as before).
-fn submit(
- state: *State,
- gpa: std.mem.Allocator,
- io: std.Io,
- slot: *Raster,
- request: RenderRequest,
- tint_key: TintKey,
- page_highlights: []const Highlight,
- keep_clean: bool,
-) enum { sent, busy, loop } {
- if (slot.banded) return .loop;
- // A lane's first job parses the document again and loads its fonts:
- // a second cold lane beside the first only slowed both (the SDM's
- // first page 1.7 -> 2.5 s in Debug), so a lane starts once the one
- // before it is warm.
- const lane = for (&state.lanes, 0..) |*l, i| {
- if (l.job == null and (l.doc != null or i == 0 or state.lanes[i - 1].warm)) break l;
- } else return .busy;
- if (lane.doc == null) lane.doc = state.document.laneClone() catch return .loop;
- const highlights = gpa.dupe(Highlight, page_highlights) catch return .loop;
- const job = gpa.create(Job) catch {
- gpa.free(highlights);
- return .loop;
- };
- state.render_gen +%= 1;
- if (state.render_gen == 0) state.render_gen = 1;
- // A spare is handed over: the lane keeps it if it is the page's size
- // (most pages of a document are), else frees it and allocates.
- const spare: []u8 = if (state.spare_len > 0) spare: {
- state.spare_len -= 1;
- break :spare state.spare[state.spare_len];
- } else &.{};
- job.* = .{
- .gen = state.render_gen,
- .page = slot.page,
- .request = request,
- .tint_key = tint_key,
- .highlights = highlights,
- .keep_clean = keep_clean,
- .rgba = spare,
- };
- lane.future = io.concurrent(renderJob, .{ lane.doc.?, job, gpa }) catch {
- state.retireRgba(gpa, spare);
- gpa.free(highlights);
- gpa.destroy(job);
- return .loop;
- };
- lane.job = job;
- lane.io = io;
- slot.pending = job.gen;
- return .sent;
-}
-
-/// The sizes landed: laid out again where the view is, by page and offset
-/// in it (a Look made meanwhile landed on the assumed layout and stays on
-/// its page), and the strip's glide carries on through it (`ensureLayout`).
-/// A document whose pages are all one size never gets here.
-pub fn applySizes(state: *State, gpa: std.mem.Allocator) void {
- if (comptime !enabled) return;
- if (state.sizes_ready.len == 0) return;
- if (state.layout_valid and !state.scroll_to_page_pending and !state.layout_anchor_pending) captureLayoutAnchor(state);
- @memcpy(state.page_sizes, state.sizes_ready);
- gpa.free(state.sizes_ready);
- state.sizes_ready = &.{};
- state.layout_valid = false;
- state.relayout_keeps_motion = true;
-}
-
-/// The sizes of every page, measured on the last lane (its first job, so
-/// its document's page tree is loaded when it starts rendering).
-fn submitSizes(state: *State, gpa: std.mem.Allocator, io: std.Io) void {
- const lane = &state.lanes[lane_count - 1];
- if (lane.job != null) return;
- if (lane.doc == null) lane.doc = state.document.laneClone() catch return;
- const job = gpa.create(Job) catch return;
- state.render_gen +%= 1;
- if (state.render_gen == 0) state.render_gen = 1;
- job.* = .{ .kind = .sizes, .gen = state.render_gen, .page = 0, .request = .{}, .tint_key = .{ .mode = .disabled, .colors = undefined }, .highlights = &.{}, .keep_clean = false, .rgba = &.{} };
- lane.future = io.concurrent(renderJob, .{ lane.doc.?, job, gpa }) catch {
- gpa.destroy(job);
- // No lane: measured here after all.
- for (state.page_sizes, 0..) |*size, page| size.* = state.document.pageSize(page) catch size.*;
- state.sizes_pending = false;
- state.layout_valid = false;
- return;
- };
- lane.job = job;
- lane.io = io;
- state.sizes_gen = job.gen;
-}
-
-/// A lane's thread: the page rendered whole into the job's buffer, its
-/// clean copy kept, highlighted and tinted, all as `reconcile` does on the
-/// loop, under the job's cookie. It touches the job and the lane's own
-/// document (`doc` is a copy of its handle), nothing of the State.
-fn renderJob(lane_doc: Document, job: *Job, gpa: std.mem.Allocator) void {
- const tz = tracy.zone(@src(), "pdf.lane_render");
- defer tz.end();
- var doc = lane_doc;
- defer job.done.store(true, .release);
- doc.laneOpen() catch return;
- if (job.kind == .sizes) {
- job.sizes = gpa.alloc(pdf.PageSize, doc.pages) catch return;
- for (job.sizes, 0..) |*size, page| {
- if (page % 64 == 0 and @atomicLoad(c_int, &job.cookie.abort, .acquire) != 0) return;
- size.* = doc.pageSize(page) catch return;
- }
- job.ok = true;
- return;
- }
- doc.setCookie(&job.cookie);
- defer doc.setCookie(null);
- // Measured here, on the lane's own document: loading a page (its links
- // and annotations) cost the loop 6-7 ms a page of the SDM in Debug.
- job.shape = doc.measureRenderAt(job.page, job.request) catch return;
- if (isBanded(job.shape)) {
- job.banded = true;
- return;
- }
- if (job.rgba.len != job.shape.len) {
- if (job.rgba.len > 0) gpa.free(job.rgba);
- job.rgba = &.{};
- job.rgba = pardes.memory.unfilled(gpa, job.shape.len) catch return;
- }
- const band = job.shape.wholePage();
- doc.renderIntoAtWithPaper(job.page, job.request, job.shape, band, if (job.keep_clean) &.{} else job.highlights, job.rgba, pardes.platform == .macos) catch return;
- if (job.keep_clean) {
- job.clean = pardes.memory.dupeUnfilled(gpa, job.rgba) catch return;
- doc.paintHighlightsAt(job.page, job.request, job.shape, band, job.highlights, job.rgba) catch return;
- }
- pdf.tintRgba(job.rgba, job.tint_key.mode, job.tint_key.colors) catch return;
- job.ok = true;
-}
-
-/// The jobs that are done, joined (a return away) and landed.
-fn collect(state: *State, gpa: std.mem.Allocator) void {
- for (&state.lanes) |*lane| {
- const job = lane.job orelse continue;
- if (!job.done.load(.acquire)) continue;
- lane.future.?.await(lane.io);
- lane.future = null;
- lane.job = null;
- lane.warm = true;
- land(state, gpa, job);
- }
-}
-
-/// A job's raster into the slot waiting for its generation, swapped in
-/// whole (no pixel is copied on the loop); a stale, failed or aborted one
-/// is dropped. Frees the job.
-fn land(state: *State, gpa: std.mem.Allocator, job: *Job) void {
- const tz = tracy.zone(@src(), "pdf.land");
- defer tz.end();
- defer gpa.destroy(job);
- if (job.kind == .sizes) {
- defer if (job.sizes.len > 0) gpa.free(job.sizes);
- if (job.gen == 0 or job.gen != state.sizes_gen) return;
- state.sizes_pending = false;
- if (!job.ok or job.sizes.len != state.page_count) return; // ponytail: the assumed sizes stay
- if (std.mem.eql(u8, std.mem.sliceAsBytes(job.sizes), std.mem.sliceAsBytes(state.page_sizes))) return;
- // Applied by the next draw, before it lays out (`applySizes`): here
- // the strip may stand where it is drawn, not where the core is.
- if (state.sizes_ready.len > 0) gpa.free(state.sizes_ready);
- state.sizes_ready = job.sizes;
- job.sizes = &.{};
- return;
- }
- const slot: ?*Raster = if (job.gen == 0) null else for (state.rasters[0..state.rasters_len]) |*r| {
- if (r.valid and r.pending == job.gen) break r;
- } else null;
- if (slot == null or !job.ok) {
- if (slot) |s| {
- s.pending = 0;
- s.banded = job.banded;
- if (@atomicLoad(c_int, &job.cookie.abort, .acquire) == 0 and !job.banded) {
- s.failed = true;
- s.tried = true;
- s.request = job.request;
- s.request_valid = true;
- }
- }
- state.retireRgba(gpa, job.rgba);
- if (job.clean.len > 0) gpa.free(job.clean);
- gpa.free(job.highlights);
- return;
- }
- const s = slot.?;
- s.pending = 0;
- s.failed = false;
- s.tried = true;
- state.retireRgba(gpa, s.rgba);
- s.rgba = job.rgba;
- if (s.clean.len > 0) gpa.free(s.clean);
- s.clean = job.clean;
- s.iw = job.shape.width;
- s.ih = job.shape.height;
- s.band_y = 0;
- s.band_h = job.shape.height;
- s.request = job.request;
- s.request_valid = true;
- s.tint_key = job.tint_key;
- s.decorated = job.highlights.len > 0;
- gpa.free(s.baked);
- s.baked = job.highlights;
- s.baked_valid = true;
- s.patch_from = 0;
- s.patch_rows = .{ .start = 0, .end = 0 };
- state.next_raster_revision +%= 1;
- if (state.next_raster_revision == 0) state.next_raster_revision = 1;
- s.revision = state.next_raster_revision;
- state.landed +|= 1;
-}
-
-/// A job no slot waits for any more (its page left the strip, its request
-/// changed) is told to stop: MuPDF sees the cookie at its next operator.
-fn sweep(state: *State) void {
- for (state.lanes) |lane| if (lane.job) |job| if (job.kind == .render) {
- const wanted = for (state.rasters[0..state.rasters_len]) |r| {
- if (r.valid and r.pending == job.gen) break true;
- } else false;
- if (!wanted) @atomicStore(c_int, &job.cookie.abort, 1, .release);
- };
-}
-
-/// Some page of this State is being rendered on a lane (the frames after
-/// look for it, as a picture's decode is looked for).
-pub fn rendering(state: *const State) bool {
- if (comptime !enabled) return false;
- for (state.lanes) |lane| if (lane.job != null) return true;
- return false;
-}
-
-/// Repaint only the rows where the old and new highlights differ: the
-/// clean rows kept from the page's last render, MuPDF's highlight pass
-/// (the whole new set) over them, the per-pixel tint — the operations a
-/// full render performs, in its order, on fewer rows and without running
-/// the page again. False leaves the slot for the full path.
-fn repaintHighlights(
- state: *State,
- gpa: std.mem.Allocator,
- slot: *Raster,
- request: RenderRequest,
- tint_key: TintKey,
- page_highlights: []const Highlight,
-) bool {
- const tz = tracy.zone(@src(), "pdf.repaint_highlights");
- defer tz.end();
- if (slot.clean.len != slot.rgba.len or !slot.baked_valid) return false;
- if (sameHighlights(slot.baked, page_highlights)) {
- slot.tried = true;
- return true;
- }
- const baked = gpa.dupe(Highlight, page_highlights) catch return false;
- const changed = changedHighlights(gpa, slot.baked, page_highlights) catch {
- gpa.free(baked);
- return false;
- };
- defer gpa.free(changed);
- var dirty = state.document.highlightRows(slot.page, request, changed) catch {
- gpa.free(baked);
- return false;
- };
- slot.tried = true;
- dirty.start = @max(dirty.start, slot.band_y);
- dirty.end = @min(dirty.end, slot.band_y + slot.band_h);
- if (dirty.start < dirty.end) {
- const shape = slotShape(slot);
- const band = shape.band(dirty.start, dirty.end - dirty.start);
- const offset = (dirty.start - slot.band_y) * shape.stride;
- const out = slot.rgba[offset..][0..band.len];
- @memcpy(out, slot.clean[offset..][0..band.len]);
- // On failure the rows are half-made: let the full path redo them.
- state.document.paintHighlightsAt(slot.page, request, shape, band, page_highlights, out) catch {
- gpa.free(baked);
- slot.tried = false;
- return false;
- };
- pdf.tintRgba(out, tint_key.mode, tint_key.colors) catch {
- gpa.free(baked);
- slot.tried = false;
- return false;
- };
- slot.patch_rows = unionRows(slot.patch_rows, dirty);
- state.next_raster_revision +%= 1;
- if (state.next_raster_revision == 0) state.next_raster_revision = 1;
- slot.revision = state.next_raster_revision;
- }
- gpa.free(slot.baked);
- slot.baked = baked;
- slot.decorated = page_highlights.len > 0;
- return true;
-}
-
-fn sameHighlights(a: []const Highlight, b: []const Highlight) bool {
- return std.mem.eql(u8, std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b));
-}
-
-/// The highlights in one set and not the other, as multisets (a quad
-/// painted twice blends twice). When only the order changed, blending
-/// order did, so everything counts.
-// ponytail: quadratic match; past 64k comparisons every quad counts.
-fn changedHighlights(gpa: std.mem.Allocator, old: []const Highlight, new: []const Highlight) ![]Highlight {
- const out = try gpa.alloc(Highlight, old.len + new.len);
- errdefer gpa.free(out);
- var n: usize = 0;
- if (old.len * new.len <= 1 << 16) {
- const matched = try gpa.alloc(bool, new.len);
- defer gpa.free(matched);
- @memset(matched, false);
- for (old) |h| {
- for (new, matched) |candidate, *used| {
- if (!used.* and std.mem.eql(u8, std.mem.asBytes(&h), std.mem.asBytes(&candidate))) {
- used.* = true;
- break;
- }
- } else {
- out[n] = h;
- n += 1;
- }
- }
- for (new, matched) |h, used| if (!used) {
- out[n] = h;
- n += 1;
- };
- }
- if (n == 0) {
- @memcpy(out[0..old.len], old);
- @memcpy(out[old.len..], new);
- return out;
- }
- // Freed by length: hand back exactly what the caller will free.
- return gpa.realloc(out, n);
-}
-
-fn unionRows(a: pdf.Document.Rows, b: pdf.Document.Rows) pdf.Document.Rows {
- if (a.start >= a.end) return b;
- if (b.start >= b.end) return a;
- return .{ .start = @min(a.start, b.start), .end = @max(a.end, b.end) };
-}
-
-pub fn renderFrame(
- state: *State,
- gpa: std.mem.Allocator,
- arena: std.mem.Allocator,
- viewport: Viewport,
- policy: RasterPolicy,
- tint_key: TintKey,
- highlight_input: HighlightInput,
- path: f64,
- far: bool,
-) VisiblePages {
- if (comptime !enabled) return .{};
- ensureLayout(state, viewport);
- state.resolveSearch(gpa);
- const highlights = buildHighlights(state, arena, highlight_input) catch Highlights{};
- const request = renderRequest(viewport, policy, state.fit);
- // ponytail: every page the glide crosses to its mark (`path` pixels
- // on) renders now, in the input's frame, so no frame of the glide
- // waits on MuPDF (it renders on the loop). A far jump's slide (`far`)
- // comes in over what is there, none of the page above its mark, which
- // would cost the input's frame a page; a render thread would draw it.
- const span = struct {
- fn f(st: *const State, view: Viewport, along: f64, from_rest: bool) VisiblePages {
- const h: f64 = @floatFromInt(view.pixel_h);
- return if (from_rest) pagesOver(st, st.document_scroll_y + along, h) else pagesOver(st, st.document_scroll_y + @min(0, along), h + @abs(along));
- }
- }.f;
- // Off the loop, the page past the strip the way it last went is asked
- // for too, after the ones in view: rendered ahead, as paint-ahead does.
- const ahead = struct {
- fn f(st: *const State, v: VisiblePages) VisiblePages {
- if (workers == null or v.len == 0) return v;
- if (st.ahead > 0 and v.first + v.len < st.page_count) return .{ .first = v.first, .len = v.len + 1 };
- if (st.ahead < 0 and v.first > 0) return .{ .first = v.first - 1, .len = v.len + 1 };
- return v;
- }
- }.f;
- var visible = span(state, viewport, path, far);
- reconcile(state, gpa, request, tint_key, highlights, ahead(state, visible), viewport);
-
- rearmSearchReveal(state, viewport);
- revealSearch(state, viewport, activeGeometry(state, viewport));
- visible = span(state, viewport, path, far);
- reconcile(state, gpa, request, tint_key, highlights, ahead(state, visible), viewport);
- return visible;
-}
-
-pub fn normalizedPixel(value: f32, dimension: usize) u32 {
- const scaled = std.math.clamp(value, 0, 1) * @as(f32, @floatFromInt(dimension));
- return @intCast(@min(dimension - 1, @as(usize, @intFromFloat(scaled))));
-}
-
-pub fn scaledStep(base: u32, count: u32) u32 {
- return @intCast(@min(
- @as(u64, std.math.maxInt(u32)),
- @as(u64, base) * @max(@as(u64, 1), count),
- ));
-}
-
-pub fn scrollDocument(state: *State, viewport: Viewport, delta_pixels: f64) ?ScrollResult {
- if (comptime !enabled) return null;
- if (!std.math.isFinite(delta_pixels) or delta_pixels == 0) return null;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- const next = std.math.clamp(state.document_scroll_y + delta_pixels, 0, max_scroll);
- if (next == state.document_scroll_y) return null;
- state.scroll_travel += @abs(next - state.document_scroll_y);
- state.document_scroll_y = next;
- return .{ .active_page = pageAtOffset(state, next) };
-}
-
-pub fn panPixels(
- state: *State,
- geometry: surface.NativeGeometry,
- axis: PanAxis,
- direction: i8,
- display_pixels: u32,
-) PanResult {
- if (comptime !enabled) return .unavailable;
- const raster = rasterForPage(state, state.page) orelse return .unavailable;
- const source_full: u32 = @intCast(switch (axis) {
- .horizontal => raster.iw,
- .vertical => raster.ih,
- });
- const crop = switch (axis) {
- .horizontal => geometry.src.w,
- .vertical => geometry.src.h,
- };
- const source_at = switch (axis) {
- .horizontal => geometry.src.x,
- .vertical => geometry.src.y,
- };
- const displayed = @max(@as(u32, 1), switch (axis) {
- .horizontal => geometry.dst.w,
- .vertical => geometry.dst.h,
- });
- const overflow = source_full -| crop;
- if (overflow == 0 or
- (direction < 0 and source_at == 0) or
- (direction > 0 and source_at >= overflow)) return .edge;
-
- const source_step = @max(
- @as(u64, 1),
- (@as(u64, display_pixels) * @as(u64, crop) + displayed - 1) / displayed,
- );
- const normalized_step: u32 = @intCast(@min(
- @as(u64, std.math.maxInt(u16)),
- @max(
- @as(u64, 1),
- (source_step * std.math.maxInt(u16) + overflow - 1) / overflow,
- ),
- ));
- const position = switch (axis) {
- .horizontal => &state.pan_x,
- .vertical => &state.pan_y,
- };
- if (direction > 0) {
- position.* = @intCast(@min(
- @as(u32, std.math.maxInt(u16)),
- @as(u32, position.*) + normalized_step,
- ));
- } else {
- position.* -|= @intCast(normalized_step);
- }
- return .moved;
-}
-
-fn setHorizontalEdge(state: *State, geometry: surface.NativeGeometry, end: bool) void {
- if (comptime !enabled) return;
- const raster = rasterForPage(state, state.page) orelse return;
- if (raster.iw <= geometry.src.w) return;
- state.pan_x = if (end) std.math.maxInt(u16) else 0;
-}
-
-fn rearmSearchReveal(state: *State, viewport: Viewport) void {
- if (comptime !enabled) return;
- if (state.search_query.len == 0) return;
- if (!state.reveal_viewport_valid or
- state.reveal_viewport_w != viewport.pixel_w or
- state.reveal_viewport_h != viewport.pixel_h or
- state.reveal_fit != state.fit)
- state.search_reveal_pending = true;
-}
-
-pub fn revealSearch(
- state: *State,
- viewport: Viewport,
- geometry: ?surface.NativeGeometry,
-) void {
- if (comptime !enabled) return;
- if (!state.search_reveal_pending) return;
- state.reveal_viewport_w = viewport.pixel_w;
- state.reveal_viewport_h = viewport.pixel_h;
- state.reveal_fit = state.fit;
- state.reveal_viewport_valid = true;
- const results = state.search_results orelse {
- state.search_reveal_pending = false;
- return;
- };
- if (results.hit_count == 0 or results.quads.len == 0) {
- state.search_reveal_pending = false;
- return;
- }
- state.search_hit = @min(state.search_hit, results.hit_count - 1);
- const q = for (results.quads) |item| {
- if (item.hit == state.search_hit) break item.quad;
- } else {
- state.search_reveal_pending = false;
- return;
- };
- state.search_reveal_pending = false;
- const center_x = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4;
- const center_y = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4;
- if (state.fit == .width) {
- ensureLayout(state, viewport);
- const page_y = @as(f64, @floatFromInt(state.page_starts[state.page])) +
- @as(f64, center_y) * @as(f64, @floatFromInt(state.page_heights[state.page]));
- const wanted = page_y - @as(f64, @floatFromInt(viewport.pixel_h)) / 2;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- state.document_scroll_y = std.math.clamp(wanted, 0, max_scroll);
- return;
- }
- const placed = geometry orelse return;
- const raster = rasterForPage(state, state.page) orelse return;
- const full: u32 = @intCast(raster.iw);
- const at = normalizedPixel(center_x, raster.iw);
- if (at >= placed.src.x and at < placed.src.x + placed.src.w) return;
- const overflow = full -| placed.src.w;
- if (overflow == 0) return;
- const wanted = @min(overflow, at -| placed.src.w / 2);
- state.pan_x = @intCast(
- (@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow,
- );
-}
-
-pub fn stepPage(state: *State, gpa: std.mem.Allocator, delta: i64) bool {
- const current: i64 = @intCast(state.page);
- const last: i64 = @intCast(state.page_count -| 1);
- return state.activatePage(
- gpa,
- @intCast(std.math.clamp(current + delta, 0, last)),
- true,
- );
-}
-
-fn scrollNormal(
- state: *State,
- gpa: std.mem.Allocator,
- viewport: ?Viewport,
- delta_pixels: f64,
-) bool {
- const view = viewport orelse return false;
- ensureLayout(state, view);
- const result = scrollDocument(state, view, delta_pixels) orelse return false;
- return result.active_page != state.page and
- state.activatePage(gpa, result.active_page, false);
-}
-
-fn moveRows(
- state: *State,
- gpa: std.mem.Allocator,
- native_images: bool,
- viewport: ?Viewport,
- cell_pixels: CellPixels,
- direction: i8,
- count: u32,
-) bool {
- if (!native_images) {
- const pages: i64 = @intCast(@max(@as(u32, 1), count));
- return stepPage(state, gpa, if (direction > 0) pages else -pages);
- }
- return scrollNormal(
- state,
- gpa,
- viewport,
- @as(f64, @floatFromInt(scaledStep(cell_pixels.h, count))) * direction,
- );
-}
-
-fn movePage(
- state: *State,
- gpa: std.mem.Allocator,
- native_images: bool,
- viewport: ?Viewport,
- cell_pixels: CellPixels,
- direction: i8,
- half: bool,
- count: u32,
-) bool {
- if (!native_images) {
- const pages: i64 = @intCast(@max(@as(u32, 1), count));
- return stepPage(state, gpa, if (direction > 0) pages else -pages);
- }
- const base: u32 = if (viewport) |view|
- (if (half) @max(@as(u32, 1), view.pixel_h / 2) else view.pixel_h)
- else
- cell_pixels.h;
- return scrollNormal(
- state,
- gpa,
- viewport,
- @as(f64, @floatFromInt(scaledStep(base, count))) * direction,
- );
-}
-
-/// A normal-mode command in a PDF pane: the page moves, or the session is
-/// asked for what a page cannot do (Last, the leader, the tag, a search).
-pub fn applyNormal(core: *pardes.Pardes, pane: *pardes.Pane, a: modal.Normal.Action) void {
- const v = core.view();
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- const gpa = core.pdf_gpa;
- const native = v.frontend.native_images;
- const cells: CellPixels = .{ .w = v.cell_pixels.w, .h = v.cell_pixels.h };
- const viewport = paneViewport(core, pane);
- const placed = if (native) paneGeometry(core, pane) else null;
- const page_changed = switch (a.role) {
- // Esc drops a selection or a search the page shows, else goes back
- // a pane (text-only, the page shows neither); typed again by a
- // macro, Esc is only the page's.
- .escape => {
- if ((!state.cancelChrome(gpa) or !native) and core.macro.replaying == 0) exec.runBuiltin(core, .Last, v.active, "", null);
- return;
- },
- .move_down, .goto_line_down => moveRows(state, gpa, native, viewport, cells, 1, a.count),
- .move_up, .goto_line_up => moveRows(state, gpa, native, viewport, cells, -1, a.count),
- .view_scroll_down => moveRows(state, gpa, native, viewport, cells, 1, 1),
- .view_scroll_up => moveRows(state, gpa, native, viewport, cells, -1, 1),
- .move_left, .move_right => {
- if (placed) |g| _ = panPixels(state, g, .horizontal, if (a.role == .move_left) -1 else 1, scaledStep(cells.w, a.count));
- return;
- },
- .goto_line_start, .goto_first_nonws, .line_start, .line_first_nonws, .goto_line_end, .line_end => {
- if (placed) |g| setHorizontalEdge(state, g, a.role == .goto_line_end or a.role == .line_end);
- return;
- },
- .goto_file_start => state.activatePage(gpa, if (a.explicit) a.count -| 1 else 0, true),
- .goto_line => a.explicit and state.activatePage(gpa, a.count -| 1, true),
- .goto_last_line => state.activatePage(gpa, state.page_count -| 1, true),
- .half_page_down, .page_down => movePage(state, gpa, native, viewport, cells, 1, a.role == .half_page_down, a.count),
- .half_page_up, .page_up => movePage(state, gpa, native, viewport, cells, -1, a.role == .half_page_up, a.count),
- .leader => {
- v.prefix = .leader;
- v.leader_n = 0;
- return;
- },
- .command_line => return tagline.enterTag(core, pane),
- .search => return panes.startPrompt(core, pane, &pane.body, .{ .search = config.search_marker }),
- .search_next, .search_prev => return look.lookWalk(core, if (a.role == .search_next) 1 else -1),
- else => false,
- };
- if (page_changed) resetPageChrome(pane);
-}
-
-pub fn captureLayoutAnchor(state: *State) void {
- if (comptime !enabled) return;
- if (!state.layout_valid or state.page_count == 0 or state.document_height == 0) return;
- const page = pageAtOffset(state, state.document_scroll_y);
- const start: f64 = @floatFromInt(state.page_starts[page]);
- const height: f64 = @floatFromInt(@max(@as(u32, 1), state.page_heights[page]));
- state.layout_anchor_page = page;
- state.layout_anchor_fraction = std.math.clamp((state.document_scroll_y - start) / height, 0, 1);
- state.layout_anchor_pending = true;
-}
-
-fn consumeOutlineReveal(state: *State, viewport: Viewport) void {
- const destination = state.outline_reveal_pending orelse return;
- state.outline_reveal_pending = null;
- const page = @min(destination.page, state.page_count -| 1);
- const size = state.page_sizes[page];
- const raw_y = destination.y orelse 0;
- const y = if (std.math.isFinite(raw_y)) std.math.clamp(raw_y, 0, size.height) else 0;
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[page])) +
- @as(f64, y) / @as(f64, size.height) * @as(f64, @floatFromInt(state.page_heights[page]));
-
- if (destination.x) |raw_x| if (state.fit == .height and std.math.isFinite(raw_x)) {
- const display_width = @as(f64, @floatFromInt(viewport.pixel_h)) *
- @as(f64, size.width) / @as(f64, size.height);
- const viewport_width: f64 = @floatFromInt(viewport.pixel_w);
- if (display_width > viewport_width) {
- const x = std.math.clamp(raw_x, 0, size.width);
- const target = @as(f64, x) / @as(f64, size.width) * display_width;
- const overflow = display_width - viewport_width;
- const wanted = std.math.clamp(target - viewport_width / 2, 0, overflow);
- state.pan_x = @intFromFloat(@round(
- wanted / overflow * @as(f64, std.math.maxInt(u16)),
- ));
- }
- };
- state.search_reveal_pending = false;
- state.reveal_viewport_w = viewport.pixel_w;
- state.reveal_viewport_h = viewport.pixel_h;
- state.reveal_fit = state.fit;
- state.reveal_viewport_valid = true;
-}
-
-pub fn ensureLayout(state: *State, viewport: Viewport) void {
- if (comptime !enabled) return;
- const tz = tracy.zone(@src(), "pdf.ensure_layout");
- defer tz.end();
- var relaid = false;
- const before = state.document_scroll_y;
- if (state.layout_valid and !state.scroll_to_page_pending and
- !state.layout_anchor_pending and
- (state.layout_viewport_w != viewport.pixel_w or
- state.layout_viewport_h != viewport.pixel_h)) captureLayoutAnchor(state);
- if (!state.layout_valid or state.layout_viewport_w != viewport.pixel_w or
- state.layout_viewport_h != viewport.pixel_h or state.layout_fit != state.fit)
- {
- var at: u64 = 0;
- for (state.page_sizes, 0..) |size, page| {
- state.page_starts[page] = at;
- const height = pageHeight(size, viewport, state.fit);
- state.page_heights[page] = height;
- at = std.math.add(u64, at, height) catch std.math.maxInt(u64);
- if (page + 1 < state.page_count)
- at = std.math.add(u64, at, page_gap_px) catch std.math.maxInt(u64);
- }
- state.document_height = at;
- state.layout_viewport_w = viewport.pixel_w;
- state.layout_viewport_h = viewport.pixel_h;
- state.layout_fit = state.fit;
- state.layout_valid = true;
- relaid = true;
- if (state.scroll_to_page_pending) {
- state.document_scroll_y = @floatFromInt(state.page_starts[state.page]);
- state.scroll_to_page_pending = false;
- state.layout_anchor_pending = false;
- } else if (state.layout_anchor_pending) {
- const page = @min(state.layout_anchor_page, state.page_count -| 1);
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[page])) +
- state.layout_anchor_fraction * @as(f64, @floatFromInt(state.page_heights[page]));
- state.layout_anchor_pending = false;
- }
- }
- consumeOutlineReveal(state, viewport);
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- state.document_scroll_y = std.math.clamp(state.document_scroll_y, 0, max_scroll);
- // A new layout is not a scroll: the picture is drawn there at once.
- // Unless the sizes landed under it: then the strip, wherever it is in
- // its glide, moves with the place it is heading for.
- if (relaid and state.relayout_keeps_motion) {
- state.drawn_y += state.document_scroll_y - before;
- state.relayout_keeps_motion = false;
- } else if (relaid) {
- state.drawn_y = state.document_scroll_y;
- state.direct_y = 0;
- }
-}
-
-pub const WordProbe = if (enabled) struct {
- page: usize,
- quads: []pdf.Quad,
- text: []u8,
- link: ?pdf.Link = null,
-
- pub fn deinit(probe: *@This(), gpa: std.mem.Allocator) void {
- if (probe.link) |*link| link.deinit(gpa);
- gpa.free(probe.quads);
- gpa.free(probe.text);
- probe.* = undefined;
- }
-} else void;
-
-pub const PointerDrag = if (enabled) struct {
- native: bool = false,
- /// Right-button Look probes this cell on release without borrowing or
- /// replacing the pane's persistent MuPDF selection.
- word_at: ?struct { col: u16, row: u16 } = null,
- /// Drag updates keep selection geometry/text live, but their expensive
- /// baked raster highlight is committed once on release.
- selection_changed: bool = false,
-} else struct {};
-
-pub const PointerAction = enum { look, exec };
-
-pub const PointerRelease = if (enabled) struct {
- action: ?PointerAction = null,
- text: []const u8 = &.{},
- probe: ?WordProbe = null,
-
- pub fn deinit(release: *@This(), gpa: std.mem.Allocator) void {
- if (release.probe) |*probe| probe.deinit(gpa);
- release.* = undefined;
- }
-} else struct {
- pub fn deinit(_: *@This(), _: std.mem.Allocator) void {}
-};
-
-pub fn probeWord(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- point: if (enabled) pdf.Point else void,
-) !?WordProbe {
- if (comptime !enabled) return null;
- var selection = try document.select(gpa, page, point, point);
- errdefer selection.deinit(gpa);
- const text = try document.copySelection(gpa, page, selection.start, selection.end);
- errdefer gpa.free(text);
- if (selection.quads.len == 0 or text.len == 0) {
- selection.deinit(gpa);
- gpa.free(text);
- return null;
- }
- // Transfer the quad allocation out of Selection. There is intentionally
- // no Selection.deinit on this success path: WordProbe is now its owner.
- return .{ .page = page, .quads = selection.quads, .text = text };
-}
-
-pub fn pointAtGeometry(
- geometry: surface.NativeGeometry,
- pixel_offset_y: f32,
- full_width: usize,
- full_height: usize,
- band_y: usize,
- pixel_x: i64,
- pixel_y: i64,
- clamp_to_page: bool,
-) ?Point {
- if (comptime !enabled) return null;
- if (full_width == 0 or full_height == 0 or
- geometry.src.w == 0 or geometry.src.h == 0 or
- geometry.dst.w == 0 or geometry.dst.h == 0) return null;
-
- const left: f64 = @floatFromInt(geometry.dst.x);
- const top: f64 = @floatFromInt(geometry.dst.y);
- const right = left + @as(f64, @floatFromInt(geometry.dst.w));
- const bottom = top + @as(f64, @floatFromInt(geometry.dst.h));
- var x: f64 = @floatFromInt(pixel_x);
- var y: f64 = @as(f64, @floatFromInt(pixel_y)) - @as(f64, pixel_offset_y);
- if (clamp_to_page) {
- // Half-open rectangles: keep a clamped point infinitesimally inside
- // the last presented pixel instead of letting it become `right`.
- const epsilon = 1.0 / 1024.0;
- x = std.math.clamp(x, left, @max(left, right - epsilon));
- y = std.math.clamp(y, top, @max(top, bottom - epsilon));
- } else if (x < left or x >= right or y < top or y >= bottom) {
- return null;
- }
-
- const source_x_f = @as(f64, @floatFromInt(geometry.src.x)) +
- (x - left) * @as(f64, @floatFromInt(geometry.src.w)) /
- @as(f64, @floatFromInt(geometry.dst.w));
- const source_y_f = @as(f64, @floatFromInt(geometry.src.y)) +
- (y - top) * @as(f64, @floatFromInt(geometry.src.h)) /
- @as(f64, @floatFromInt(geometry.dst.h));
- const source_x: usize = @min(full_width - 1, @as(usize, @intFromFloat(@floor(source_x_f))));
- const band_source_y: usize = @intFromFloat(@floor(source_y_f));
- const source_y = @min(full_height - 1, band_y + band_source_y);
- return .{
- .x = (@as(f32, @floatFromInt(source_x)) + 0.5) /
- @as(f32, @floatFromInt(full_width)),
- .y = (@as(f32, @floatFromInt(source_y)) + 0.5) /
- @as(f32, @floatFromInt(full_height)),
- };
-}
-
-pub fn openPane(
- core: *pardes.Pardes,
- id: usize,
- path: []const u8,
- page_one_based: usize,
- /// A page past the last: the last page (a restore, a start-up), or
- /// refused with error.NoSuchPage (a look, which names a place).
- past_end: enum { last, refuse },
-) !*pardes.Pane {
- if (comptime !enabled) return error.PdfDisabled;
- // The slot stays ours across the read: another request may make a
- // pane meanwhile.
- core.reserved_slots[id] = true;
- defer core.reserved_slots[id] = false;
- const state = try core.pdf_gpa.create(State);
- errdefer core.pdf_gpa.destroy(state);
- state.* = if (filesystem.localPath(path) != null)
- try State.open(core.pdf_gpa, path, page_one_based)
- else virtual: {
- const bytes = try filesystem.read(core, path);
- defer core.gpa.free(bytes);
- break :virtual try State.openBytes(core.pdf_gpa, path, bytes, page_one_based);
- };
- errdefer state.deinit(core.pdf_gpa);
- if (past_end == .refuse and page_one_based > state.page_count) return error.NoSuchPage;
- const pane = try core.newDocPane(id);
- pane.pdf = state;
- pane.body.cur_pinned = true;
- if (filesystem.localPath(path) != null) core.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } });
- return pane;
-}
-
-/// The file on disk is still the one the pane read (`fileKey`): a watch
-/// armed over it has nothing to reload.
-pub fn sameBytes(core: *pardes.Pardes, pane: *const pardes.Pane) bool {
- if (comptime !enabled) return false;
- const state = if (pane.pdf) |pv| pv else return false;
- if (state.file == 0) return false;
- const bytes = filesystem.read(core, state.path) catch return false;
- defer core.gpa.free(bytes);
- return fileKey(state.path, bytes) == state.file;
-}
-
-/// Release a PDF payload while its pane slot is still installed, so the host
-/// can retire the corresponding directory watch before that id is reused.
-pub fn deinitPane(core: *pardes.Pardes, pane: *pardes.Pane, state: *State) void {
- if (comptime !enabled) return;
- if (panes.paneIdOf(core, pane)) |id| core.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } });
- state.deinit(core.pdf_gpa);
- core.pdf_gpa.destroy(state);
- pane.pdf = null;
-}
-
-/// A PDF pane loaded from a dump given its document again (MuPDF's, so
-/// never in the dump) from its file; one changed since is laid out anew.
-pub fn reopen(core: *pardes.Pardes, pane: *pardes.Pane) !void {
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- const local = filesystem.localPath(state.path) orelse return error.NonLocalPath;
- const bytes = try filesystem.readFile(core.pdf_gpa, local);
- defer core.pdf_gpa.free(bytes);
- state.document = try Document.openBytes(bytes);
- if (state.document.pages != state.page_count or fileKey(state.path, bytes) != state.file) {
- try state.reload(core.pdf_gpa);
- }
-}
-
-pub fn isSectionsOutput(pane: *const pardes.Pane) bool {
- if (comptime !enabled) return false;
- const file = pane.file orelse return false;
- const output = file.output orelse return false;
- return switch (output.from) {
- .cmd => |builtin| builtin == .PdfSections,
- else => false,
- };
-}
-
-fn refreshCleanSections(core: *pardes.Pardes, state: *State) void {
- if (comptime !enabled) return;
- const remembered = state.sections_output orelse return;
- if (remembered.pane >= core.panes.len) return;
- const result = core.panes[remembered.pane] orelse return;
- if (result.serial != remembered.serial or !isSectionsOutput(result)) return;
- const file = &result.file.?;
- if (file.revision != remembered.revision) return;
-
- const content = state.renderSections(core.pdf_gpa, core.gpa) catch {
- state.sections_output = null;
- return;
- };
- if (std.mem.eql(u8, file.content, content)) {
- core.gpa.free(content);
- return;
- }
- look.invalidateLookHover(core, remembered.pane);
- File.setContent(core, file, content);
- const rows = File.lineCount(file.content);
- file.scroll = @min(file.scroll, rows - 1);
- const row = @min(@as(usize, @intCast(@max(0, result.body.cur_row))), rows - 1);
- result.body.cur_row = @intCast(row);
- result.body.cur_col = @intCast(@min(
- @as(usize, @intCast(@max(0, result.body.cur_col))),
- modal.lineSlice(file.content, row).len,
- ));
- result.body.vsel.active = false;
- result.body.nsel = 0;
- state.sections_output.?.revision = file.revision;
-}
-
-/// One successful watched-path transaction, including every piece of derived
-/// PDF output. The caller owns generic update bookkeeping and status text.
-pub fn reloadWatched(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
-) !void {
- if (comptime !enabled) return error.PdfDisabled;
- const state = pane.pdf orelse return error.MissingPdfState;
- try state.reload(core.pdf_gpa);
- resetPageChrome(pane);
- refreshCleanSections(core, state);
-}
-
-fn rearmCleanSections(
- core: *pardes.Pardes,
- id: usize,
- pane: *pardes.Pane,
- state: *State,
-) bool {
- const remembered = state.sections_output orelse return false;
- if (remembered.pane >= core.panes.len) return false;
- const result = core.panes[remembered.pane] orelse return false;
- if (result.serial != remembered.serial or !isSectionsOutput(result)) return false;
- const file = &result.file.?;
- if (file.revision != remembered.revision) return false;
-
- file.scroll = 0;
- result.body.cur_row = 0;
- result.body.cur_col = 0;
- result.body.vsel.active = false;
- result.body.nsel = 0;
- pane.search_pane = remembered.pane;
- pane.search_row = null;
- look.armLookWalk(core, remembered.pane);
- core.view().active = id;
- return true;
-}
-
-/// Lazily materialise this pane's cached outline as a location list. All
-/// PDF-specific ownership stays here; Pardes contributes only placement.
-pub fn openSections(core: *pardes.Pardes, id: usize) void {
- if (comptime !enabled) return;
- const pane = core.panes[id] orelse return;
- const state = pane.pdf orelse return;
- if (rearmCleanSections(core, id, pane, state)) return;
- const content = state.renderSections(core.pdf_gpa, core.gpa) catch |err| return core.reportError(id, "PdfSections", err);
- // No outline: said, not an empty pane to puzzle over.
- if (content.len == 0) {
- core.gpa.free(content);
- return core.reportFailure(id, "PdfSections: this PDF has no outline");
- }
-
- const free = core.freeSlot() orelse {
- core.gpa.free(content);
- return core.reportError(id, "PdfSections", error.NoPaneSlots);
- };
- const dir = std.fs.path.dirname(state.path) orelse "/";
- const result = Output.open(
- core,
- free,
- dir,
- .{ .cmd = .PdfSections },
- "",
- content,
- ) catch {
- core.gpa.free(content);
- return;
- };
- state.sections_output = .{
- .pane = free,
- .serial = result.serial,
- .revision = result.file.?.revision,
- };
- exec.placeNew(core, id, id, free, .doc);
- layout.compute(core);
- core.view().active = id;
- pane.search_pane = free;
- pane.search_row = null;
- look.armLookWalk(core, free);
-}
-
-const SectionsOwner = struct {
- id: usize,
- pane: *pardes.Pane,
- state: *State,
-};
-
-fn sectionsOwner(core: *pardes.Pardes, output_id: usize) ?SectionsOwner {
- const output = core.panes[output_id] orelse return null;
- if (!isSectionsOutput(output)) return null;
- const file = output.file.?;
- for (core.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- const state = if (pane.pdf) |pdf_state| pdf_state else continue;
- const token = state.sections_output orelse continue;
- if (token.pane == output_id and token.serial == output.serial and
- token.revision == file.revision)
- return .{ .id = id, .pane = pane, .state = state };
- }
- return null;
-}
-
-pub fn lookSection(
- core: *pardes.Pardes,
- output_id: usize,
- path: []const u8,
- at: look.Spot,
-) bool {
- if (comptime !enabled) return false;
- const output = core.panes[output_id] orelse return false;
- if (!isSectionsOutput(output)) return false;
- if (at.line == 0 or at.col == 0 or at.end_line != 0 or
- !look.isPdfPath(path)) return false;
- const owner = sectionsOwner(core, output_id) orelse return true;
-
- var joined_path: [4096]u8 = undefined;
- const output_dir = std.fs.path.dirname(output.file.?.path) orelse "/";
- const separator = if (std.mem.endsWith(u8, output_dir, "/")) "" else "/";
- const target_path = if (std.fs.path.isAbsolute(path))
- path
- else
- std.fmt.bufPrint(&joined_path, "{s}{s}{s}", .{ output_dir, separator, path }) catch return true;
- if (!std.mem.eql(u8, owner.state.path, target_path)) return true;
-
- // A row is `file:PAGE:SECTION`, its first number the page as in every
- // other location: a section there is none, or one on another page, is
- // a miss said, never a silent jump.
- var said: [160]u8 = undefined;
- const destination = owner.state.sectionDestination(core.pdf_gpa, at.col - 1) orelse
- return failSection(core, output_id, std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ std.fs.path.basename(owner.state.path), at.col }) catch "PdfSections: no such section");
- if (destination == .internal and destination.internal.page + 1 != at.line)
- return failSection(core, output_id, std.fmt.bufPrint(&said, "PdfSections: section {d} of {s} is on page {d}, not {d}", .{ at.col, std.fs.path.basename(owner.state.path), destination.internal.page + 1, at.line }) catch "PdfSections: that section is on another page");
- switch (destination) {
- .internal => |internal| {
- look.clearNavigationSelection(core, owner.pane);
- revealOutlineDestination(core, owner.pane, internal);
- },
- .external => |uri| if (uri.len <= 256) core.emit(.{ .open_link = .from(uri) }),
- .none => unreachable,
- }
- core.view().active = owner.id;
- return true;
-}
-
-fn failSection(core: *pardes.Pardes, id: usize, text: []const u8) bool {
- core.look_missed = true;
- core.reportFailure(id, text);
- return true;
-}
-
-pub fn resetPageChrome(pane: *pardes.Pane) void {
- pane.body.cur_row = 0;
- pane.body.cur_col = 0;
- pane.body.vsel.active = false;
- pane.body.nsel = 0;
-}
-
-pub fn activatePage(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- page: usize,
- reveal: bool,
-) void {
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- if (state.activatePage(core.pdf_gpa, page, reveal)) resetPageChrome(pane);
-}
-
-pub fn revealOutlineDestination(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- destination: OutlineInternalDestination,
-) void {
- if (comptime !enabled) return;
- activatePage(core, pane, destination.page, false);
- const state = pane.pdf.?;
- state.queueOutlineReveal(destination);
- // Consume immediately when geometry already exists; otherwise the PDF
- // draw pass consumes the same value after the next layout transaction.
- _ = ensurePaneLayout(core, pane);
-}
-
-/// A PDF's place, as the jumplist keeps it: the page at the strip's top and
-/// how far down that page it stands, a fraction in 2^-32 of the page. A
-/// fraction, not pixels: a zoom, a fit change or a resize scales every page,
-/// and a fraction of one lands on the same line of print after it.
-pub const Place = struct { page: usize, at: u32 };
-const place_scale: f64 = std.math.maxInt(u32);
-
-pub fn place(pane: *const pardes.Pane) ?Place {
- if (comptime !enabled) return null;
- const state = if (pane.pdf) |pv| pv else return null;
- if (!state.layout_valid or state.document_height == 0) return .{ .page = state.page, .at = 0 };
- const page = pageAtOffset(state, state.document_scroll_y);
- const start: f64 = @floatFromInt(state.page_starts[page]);
- const height: f64 = @floatFromInt(@max(1, state.page_heights[page]));
- const fraction = std.math.clamp((state.document_scroll_y - start) / height, 0, 1);
- return .{ .page = page, .at = @intFromFloat(@round(fraction * place_scale)) };
-}
-
-/// Where `at` stands on the strip as laid out now, in document pixels.
-pub fn placeY(pane: *const pardes.Pane, at: Place) ?f64 {
- if (comptime !enabled) return null;
- const state = if (pane.pdf) |pv| pv else return null;
- if (!state.layout_valid) return null;
- const page = @min(at.page, state.page_count -| 1);
- return @as(f64, @floatFromInt(state.page_starts[page])) +
- @as(f64, @floatFromInt(at.at)) / place_scale * @as(f64, @floatFromInt(state.page_heights[page]));
-}
-
-/// A jump to `at` (Back, Forward): the strip is there at once. Not laid
-/// out yet (a pane just reopened), it is anchored there for the first
-/// layout.
-pub fn landAt(core: *pardes.Pardes, pane: *pardes.Pane, at: Place) void {
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- const page = @min(at.page, state.page_count -| 1);
- activatePage(core, pane, page, false);
- state.scroll_to_page_pending = false;
- if (placeY(pane, .{ .page = page, .at = at.at })) |y| {
- state.layout_anchor_pending = false;
- // Where it stands already (half a pixel is the place's rounding):
- // not moved, not kicked.
- if (@abs(y - state.document_scroll_y) >= 0.5) state.document_scroll_y = y;
- } else {
- state.layout_anchor_pending = true;
- state.layout_anchor_page = page;
- state.layout_anchor_fraction = @as(f64, @floatFromInt(at.at)) / place_scale;
- }
-}
-
-pub fn toggleFit(pane: *pardes.Pane) void {
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- state.toggleFit();
-}
-
-pub fn toggleTint(pane: *pardes.Pane) void {
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- state.toggleTint();
-}
-
-pub fn paneViewport(core: *const pardes.Pardes, pane: *const pardes.Pane) ?Viewport {
- const v = core.view();
- if (comptime !enabled) return null;
- const rect = v.rects[panes.paneIdOf(core, pane) orelse return null];
- const cols = rect.w -| config.GUTTER;
- const rows = rect.h -| pane.tag_rows;
- if (cols == 0 or rows == 0) return null;
- return .{
- .pixel_w = @as(u32, cols) * @as(u32, v.cell_pixels.w),
- .pixel_h = @as(u32, rows) * @as(u32, v.cell_pixels.h),
- };
-}
-
-pub fn ensurePaneLayout(core: *pardes.Pardes, pane: *pardes.Pane) ?Viewport {
- if (comptime !enabled) return null;
- const state = pane.pdf orelse return null;
- const view = paneViewport(core, pane) orelse return null;
- ensureLayout(state, view);
- return view;
-}
-
-pub fn tintColors(core: *const pardes.Pardes) TintColors {
- if (comptime !enabled) return;
- const theme = core.theme();
- return .{
- .background = theme.bg orelse theme.tag_bg,
- .foreground = theme.fg orelse theme.tag_fg,
- };
-}
-
-pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?surface.NativeGeometry {
- if (comptime !enabled) return null;
- const state = if (pane.pdf) |view| view else return null;
- const view = paneViewport(core, pane) orelse return null;
- return activeGeometry(state, view);
-}
-
-/// The page under grid row `row`, from the middle of its cell.
-pub fn pageAtGridRow(core: *const pardes.Pardes, pane: *const pardes.Pane, row: u16) ?usize {
- const v = core.view();
- if (comptime !enabled) return null;
- const state = pane.pdf orelse return null;
- const rect = v.rects[panes.paneIdOf(core, pane) orelse return null];
- const body_y = core.bodyTop(pane, rect);
- if (!state.layout_valid or row < body_y or row >= body_y + (rect.h -| pane.tag_rows)) return null;
- const document_y = state.document_scroll_y + @as(f64, @floatFromInt(
- @as(u32, row - body_y) * v.cell_pixels.h + v.cell_pixels.h / 2,
- ));
- const page = pageAtOffset(state, document_y);
- const start: f64 = @floatFromInt(state.page_starts[page]);
- if (document_y < start or
- document_y >= start + @as(f64, @floatFromInt(state.page_heights[page]))) return null;
- return page;
-}
-
-/// Some page of the pane is placed where it is drawn.
-pub fn paneNativeReady(core: *const pardes.Pardes, pane: *const pardes.Pane) bool {
- if (comptime !enabled) return false;
- if (!core.view().frontend.native_images) return false;
- const state = if (pane.pdf) |view| view else return false;
- const view = paneViewport(core, pane) orelse return false;
- for (state.rasters[0..state.rasters_len]) |*raster| {
- if (raster.valid and raster.rgba.len > 0 and
- placedGeometry(state, raster, view, raster.page) != null) return true;
- }
- return false;
-}
-
-pub fn nativePageAtGridRow(
- core: *const pardes.Pardes,
- pane: *const pardes.Pane,
- row: u16,
-) ?usize {
- if (comptime !enabled) return null;
- if (!core.view().frontend.native_images) return null;
- const state = if (pane.pdf) |view| view else return null;
- const page = pageAtGridRow(core, pane, row) orelse return null;
- const view = paneViewport(core, pane) orelse return null;
- if (!pageReady(state, view, page)) return null;
- return page;
-}
-
-/// The point of `page` under the middle of grid cell `col`,`row`, where
-/// that page is placed; `clamp_to_page` holds a point past it on its edge.
-pub fn panePointAtPage(
- core: *const pardes.Pardes,
- pane: *const pardes.Pane,
- page: usize,
- col: u16,
- row: u16,
- clamp_to_page: bool,
-) ?Point {
- if (comptime !enabled) return null;
- const state = if (pane.pdf) |view| view else return null;
- const view = paneViewport(core, pane) orelse return null;
- const raster = rasterForPageConst(state, page) orelse return null;
- if (raster.rgba.len == 0) return null;
- const placed = placedGeometry(state, raster, view, page) orelse return null;
- const rect = core.view().rects[panes.paneIdOf(core, pane) orelse return null];
- const body_x = @as(i64, rect.x + config.GUTTER);
- const body_y = @as(i64, core.bodyTop(pane, rect));
- const px = (@as(i64, col) - body_x) * core.view().cell_pixels.w + core.view().cell_pixels.w / 2;
- const py = (@as(i64, row) - body_y) * core.view().cell_pixels.h + core.view().cell_pixels.h / 2;
- return pointAtGeometry(placed.geometry, placed.pixel_offset_y, raster.iw, raster.ih, raster.band_y, px, py, clamp_to_page);
-}
-
-pub fn probeAt(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- col: u16,
- row: u16,
-) ?WordProbe {
- if (comptime !enabled) return null;
- const page = nativePageAtGridRow(core, pane, row) orelse return null;
- const point = panePointAtPage(core, pane, page, col, row, false) orelse return null;
- const state = pane.pdf orelse return null;
- if (state.document.linkAt(core.pdf_gpa, page, point) catch null) |found| {
- var link = found;
- if (look.pdfLinkLocation(core, pane, link) != null) {
- const quads = core.pdf_gpa.alloc(pdf.Quad, 1) catch {
- link.deinit(core.pdf_gpa);
- return null;
- };
- const text = state.document.copyRectangle(core.pdf_gpa, page, link.quad) catch {
- core.pdf_gpa.free(quads);
- link.deinit(core.pdf_gpa);
- return null;
- };
- quads[0] = link.quad;
- return .{ .page = page, .quads = quads, .text = text, .link = link };
- }
- link.deinit(core.pdf_gpa);
- }
- return probeWord(&state.document, core.pdf_gpa, page, point) catch null;
-}
-
-pub fn beginDrag(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- col: u16,
- row: u16,
- snap_word: bool,
-) bool {
- if (comptime !enabled) return false;
- const hit_page = pageAtGridRow(core, pane, row) orelse return false;
- if (hit_page != pane.pdf.?.page) activatePage(core, pane, hit_page, false);
- const state = pane.pdf.?;
- state.clearDrag();
- const point = panePointAtPage(core, pane, state.page, col, row, false) orelse return false;
- state.drag_anchor = point;
- state.drag_head = point;
- if (!snap_word) return true;
- if (state.selection_page == state.page) if (state.selection) |selection| if (selection.contains(point)) return true;
- if (state.setSelection(core.pdf_gpa, point, point, true) == .failed) {
- // Preserve the old selection transactionally, but never let an
- // outside click execute its stale text.
- state.clearDrag();
- return false;
- }
- return true;
-}
-
-pub fn updateSelection(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- col: u16,
- row: u16,
- invalidate_raster: bool,
-) SelectionUpdate {
- if (comptime !enabled) return .failed;
- const state = pane.pdf orelse return .failed;
- const anchor = state.drag_anchor orelse return .failed;
- const point = panePointAtPage(core, pane, state.page, col, row, true) orelse return .failed;
- if (state.drag_head) |head| if (head.x == point.x and head.y == point.y) return .stationary;
- const result = state.setSelection(core.pdf_gpa, anchor, point, invalidate_raster);
- if (result != .failed) state.drag_head = point;
- return result;
-}
-
-pub fn pointerStart(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- button: pardes.Mouse.Button,
- col: u16,
- row: u16,
- on_tag: bool,
-) PointerDrag {
- if (comptime !enabled) return .{};
- if (on_tag or !paneNativeReady(core, pane)) return .{};
- var drag: PointerDrag = .{ .native = true };
- if (button == config.look_button) {
- drag.word_at = .{ .col = col, .row = row };
- } else if (button == config.select_button) {
- _ = beginDrag(core, pane, col, row, false);
- } else if (button == config.exec_button) {
- _ = beginDrag(core, pane, col, row, true);
- }
- return drag;
-}
-
-pub fn pointerUpdate(
- drag: *PointerDrag,
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- col: u16,
- row: u16,
-) void {
- if (comptime !enabled) return;
- if (!drag.native) return;
- if (drag.word_at) |at| {
- if (col == at.col and row == at.row) return;
- if (!beginDrag(core, pane, at.col, at.row, false)) {
- drag.word_at = null;
- return;
- }
- switch (updateSelection(core, pane, col, row, false)) {
- .failed => {
- drag.word_at = null;
- pane.pdf.?.clearDrag();
- },
- // Adjacent grid cells can still address one raster pixel. Keep
- // click mode and retry farther out.
- .stationary => {},
- .unchanged => drag.word_at = null,
- .changed => {
- drag.word_at = null;
- drag.selection_changed = true;
- },
- }
- return;
- }
- switch (updateSelection(core, pane, col, row, false)) {
- .failed => pane.pdf.?.clearDrag(),
- .stationary, .unchanged => {},
- .changed => drag.selection_changed = true,
- }
-}
-
-pub fn pointerCancel(pane: *pardes.Pane, drag: PointerDrag) void {
- if (comptime !enabled) return;
- if (drag.native) if (pane.pdf) |state| {
- if (drag.selection_changed) state.invalidateRaster(state.page);
- state.clearDrag();
- };
-}
-
-pub fn pointerRelease(
- core: *pardes.Pardes,
- pane: *pardes.Pane,
- drag: PointerDrag,
- button: pardes.Mouse.Button,
- chorded: bool,
-) PointerRelease {
- if (comptime !enabled) return .{};
- const state = pane.pdf orelse return .{};
- const slot = @backingInt(button);
- const grid_selection = pane.sel[slot];
- pane.sel[slot].state = .none; // native quads, not projected text cells
-
- // Drag updates changed live geometry/text while leaving baked pixels
- // stable. Commit exactly once before any chord/Exec/Look can clear state.
- if (drag.selection_changed) state.invalidateRaster(state.page);
- if (chorded) {
- state.clearDrag();
- return .{};
- }
- if (drag.word_at) |at| {
- const maybe_probe = probeAt(core, pane, at.col, at.row);
- state.clearDrag();
- const probe = maybe_probe orelse return .{};
- // A neighboring visible page becomes current before Look dispatch.
- // WordProbe owns its text/quads independently of that state change.
- if (probe.page != state.page) activatePage(core, pane, probe.page, false);
- const text = probe.text;
- return .{ .action = .look, .text = text, .probe = probe };
- }
- if (button == config.select_button) {
- const dragged = grid_selection.c0 != grid_selection.c1 or
- grid_selection.r0 != grid_selection.r1;
- if (!dragged) state.clearSelection(core.pdf_gpa);
- pane.body.cur_pinned = true;
- pane.body.mode = .normal;
- pane.body.vsel.active = false;
- pane.body.normal.clear();
- pane.body.nsel = 0;
- state.clearDrag();
- return .{};
- }
- if (state.drag_anchor == null or state.selection_text.len == 0) {
- state.clearDrag();
- return .{};
- }
- const text = state.selection_text;
- state.clearDrag();
- return .{
- .action = if (button == config.look_button) .look else .exec,
- .text = text,
- };
-}
-
-pub fn highlightInput(
- core: *pardes.Pardes,
- pane_id: usize,
- pane: *const pardes.Pane,
-) HighlightInput {
- if (comptime !enabled) return;
- const hover_quads: []const Quad = if (core.pdf_hover_preview) |preview|
- if (preview.pane == pane_id and preview.serial == pane.serial)
- preview.probe.quads
- else
- &.{}
- else
- &.{};
- const hover_page = if (hover_quads.len > 0) core.pdf_hover_preview.?.probe.page else null;
- const link_hover = hover_quads.len > 0 and core.pdf_hover_preview.?.probe.link != null;
- const selection_color = core.theme().sel_bg;
- return .{
- .hover_quads = hover_quads,
- .hover_page = hover_page,
- .hover_color = if (link_hover) core.theme().box else selection_color,
- .selection_color = selection_color,
- .live = core.view().frontend.native_image_patches,
- };
-}
-
-/// `glide`: a notch; else a touchpad's fraction, counted as moved by the
-/// pixel (`direct_y`).
-pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64, glide: bool) bool {
- if (comptime !enabled) return false;
- const tz = tracy.zone(@src(), "pdf.scroll_notch");
- defer tz.end();
- const state = pane.pdf orelse return false;
- const view = ensurePaneLayout(core, pane) orelse return false;
- const from = state.document_scroll_y;
- const result = scrollDocument(state, view, delta_pixels) orelse return false;
- if (!glide) state.direct_y += state.document_scroll_y - from;
- if (result.active_page != state.page) activatePage(core, pane, result.active_page, false);
- return true;
-}
-
-/// Where the strip is drawn this frame: where the core stands, a scroll
-/// landing at once; which way it went, for the page rendered ahead.
-fn stripAt(state: *State, view: Viewport) f64 {
- const moved = state.document_scroll_y - state.drawn_y;
- if (moved != 0) state.ahead = if (moved > 0) 1 else -1;
- state.drawn_y = state.document_scroll_y;
- state.direct_y = 0;
- state.far = false;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| view.pixel_h));
- return std.math.clamp(state.drawn_y, 0, max_scroll);
-}
-
-pub fn verticalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void {
- if (comptime !enabled) return;
- if (!core.view().frontend.native_images) {
- // The text layer: a page a notch.
- const state = pane.pdf orelse return;
- if (stepPage(state, core.pdf_gpa, direction)) resetPageChrome(pane);
- return;
- }
- const rows: u32 = @intCast(@max(1, config.wheel_rows));
- const pixels = scaledStep(core.view().cell_pixels.h, rows);
- _ = scrollPane(core, pane, @as(f64, @floatFromInt(pixels)) * direction, true);
-}
-
-pub fn horizontalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void {
- if (comptime !enabled) return;
- const state = pane.pdf orelse return;
- if (!core.view().frontend.native_images or state.fit != .height) return;
- const placed = paneGeometry(core, pane) orelse return;
- const cols: u32 = @intCast(@max(1, config.wheel_cols));
- _ = panPixels(state, placed, .horizontal, direction, scaledStep(core.view().cell_pixels.w, cols));
-}
-
-pub fn draw(
- core: *pardes.Pardes,
- s: *pardes.Surface,
- pane: *pardes.Pane,
- rect: pardes.Rect,
- pane_id: usize,
- text_x: u16,
- text_width: u16,
- rail: *pardes.Region,
-) bool {
- if (comptime !enabled) return false;
- if (!core.view().frontend.native_images or rect.h <= pane.tag_rows) return false;
- const state = pane.pdf orelse return false;
- const view = paneViewport(core, pane) orelse return false;
- const key = TintKey{ .mode = state.tint, .colors = tintColors(core) };
- applySizes(state, core.pdf_gpa);
- ensureLayout(state, view);
- // Drawn where the core stands (`drawn_y`), unless a search's reveal
- // moved it as it drew, which is then drawn there.
- const shown = stripAt(state, view);
- state.document_scroll_y = shown;
- defer state.document_scroll_y = state.drawn_y;
- if (pane_id == core.view().active) core.frames.scroll = @floatCast(shown);
- defer {
- core.frames.landed +|= state.landed;
- state.landed = 0;
- }
- const visible = renderFrame(
- state,
- core.pdf_gpa,
- core.scratch.allocator(),
- view,
- pardes.pdf_raster_policy,
- key,
- highlightInput(core, pane_id, pane),
- state.drawn_y - shown,
- state.far,
- );
- if (state.document_scroll_y != shown) state.drawn_y = state.document_scroll_y;
- // Below the notice chips, like an image: a placed page is drawn after
- // the cells and would paint a chip out.
- const body: pardes.RectCell = .{
- .x = text_x,
- .y = core.bodyTop(pane, rect) + pane.notices.span(),
- .w = text_width,
- .h = (rect.h -| pane.tag_rows) -| pane.notices.span(),
- };
- if (s.region(.body, pane_id)) |region| region.scroll_px = state.document_scroll_y;
- var placed_any = false;
- var page = visible.first;
- const visible_end = visible.first + visible.len;
- state.blank = .{ 255, 255, 255, 255 };
- pdf.tintRgba(&state.blank, key.mode, key.colors) catch {};
- while (page < visible_end) : (page += 1) {
- const placed = placedRaster(state, view, page) orelse {
- // Not landed yet (a lane renders it): its paper, where it will
- // be, one pixel drawn the page's size. Never a stall.
- // ponytail: the blank's texture is keyed revision 0, so a tint
- // change shows the old paper until the page lands.
- if (workers == null or pardes.platform == .macos) continue;
- const size = state.page_sizes[page];
- const rows = visibleRows(state, view, page, @intFromFloat(@max(1, @round(size.width * 8))), @intFromFloat(@max(1, @round(size.height * 8)))) orelse continue;
- if (!core.appendPlacement(.{
- .pane = @intCast(pane_id),
- .raster = .of(&state.blank, 1, 1),
- .src = .{ .w = 1, .h = 1 },
- .dst = body,
- .at = .{ .x = rows.base.dst.x, .y = rows.dst_y, .w = rows.base.dst.w, .h = rows.dst_h },
- .key = pardes.Placement.keyOf(pane.serial, @intCast(page), 0),
- })) break;
- placed_any = true;
- continue;
- };
- const slot = rasterForPage(state, page).?;
- const dirty: ?pardes.Placement.Dirty = if (slot.patch_from != 0 and
- slot.patch_rows.start < slot.patch_rows.end)
- .{
- .from = pardes.Placement.keyOf(pane.serial, @intCast(placed.page), slot.patch_from),
- .y = @intCast(slot.patch_rows.start - slot.band_y),
- .h = @intCast(slot.patch_rows.end - slot.patch_rows.start),
- }
- else
- null;
- if (!core.appendPlacement(.{
- .pane = @intCast(pane_id),
- // The texture is the retained band, not the full page.
- .raster = .of(placed.rgba, placed.width, placed.band_height),
- .src = placed.geometry.src,
- .dst = body,
- .at = placed.geometry.dst,
- .key = pardes.Placement.keyOf(pane.serial, @intCast(placed.page), placed.revision),
- .dirty = dirty,
- })) break;
- // A shell now holds (or will fetch whole) this revision.
- slot.patch_from = slot.revision;
- slot.patch_rows = .{ .start = 0, .end = 0 };
- placed_any = true;
- }
- // Nothing placed while pages are there (a far jump's first frame: its
- // slide starts a body short of the pages it renders) is still the PDF's
- // frame: falling back to the page's text extracted it on the loop
- // (9 ms RS, 110 ms Debug on the SDM) to show it for one frame.
- if (!placed_any and visible.len == 0) return false;
-
- // This frame has spent the motion used to choose its raster band.
- state.scroll_travel = 0;
- const chrome = core.chromeTheme();
- const theme = core.theme();
- const pane_bg: pardes.Color = if (theme.bg) |color| .{ .rgb = color } else .default;
- // The rail runs past the notice bands; only the thumb tracks the text,
- // and it is measured here, in document pixels, for `place`'s region.
- const track_h: usize = rail.rect.h;
- const total = @max(@as(u64, 1), state.document_height);
- const len = @max(
- @as(usize, 1),
- @as(usize, @intCast(@min(
- @as(u64, track_h),
- @as(u64, track_h) * view.pixel_h / total,
- ))),
- );
- const offset: u64 = @intFromFloat(@floor(state.document_scroll_y));
- const pos: usize = @intCast(@min(
- @as(u64, track_h -| 1),
- @as(u64, track_h) * offset / total,
- ));
- rail.thumb_y = @intCast(pos);
- rail.thumb_h = @intCast(@min(len, track_h -| pos));
- rail.thumb_at = @floatCast(state.document_scroll_y / @as(f64, @floatFromInt(total)));
- rail.thumb_span = @as(f32, @floatFromInt(view.pixel_h)) / @as(f32, @floatFromInt(total));
- s.fill(rail.rect.x, rail.rect.y, 1, rail.rect.h, .{ .bg = .{ .rgb = chrome.scroll_track } });
- s.fill(rail.rect.x + 1, rail.rect.y, 1, rail.rect.h, .{ .bg = pane_bg });
- s.fill(rail.rect.x, rail.rect.y + rail.thumb_y, 1, rail.thumb_h, .{ .bg = .{ .rgb = chrome.scroll_thumb } });
- return true;
-}
-
-pub const SectionRows = if (enabled) struct {
- pub fn usableDestination(destination: pdf.OutlineDestination) ?pdf.OutlineDestination {
- return switch (destination) {
- .internal => destination,
- .external => |uri| if (safeHttpUri(uri)) destination else null,
- .none => null,
- };
- }
-
- fn safeHttpUri(uri: []const u8) bool {
- // Effect.open_link is inline and cannot carry a larger URL. Omitting
- // it here is preferable to rendering a row which can never act.
- if (uri.len > 256) return false;
- var has_scheme = false;
- for (config.url_schemes) |scheme| {
- if (std.mem.startsWith(u8, uri, scheme)) {
- has_scheme = true;
- break;
- }
- }
- if (!has_scheme) return false;
- for (uri) |byte| if (byte <= 0x20 or byte == 0x7f) return false;
- return true;
- }
-
- pub fn resolve(entries: []const pdf.OutlineEntry, ordinal: usize) ?pdf.OutlineDestination {
- if (ordinal >= entries.len) return null;
- const entry = entries[ordinal];
- if (entry.destination != .none) return usableDestination(entry.destination);
- var i = ordinal + 1;
- while (i < entries.len and entries[i].depth > entry.depth) : (i += 1)
- if (usableDestination(entries[i].destination)) |destination| return destination;
- return null;
- }
-
- pub fn resolveOrdinals(
- gpa: std.mem.Allocator,
- entries: []const pdf.OutlineEntry,
- ) ![]usize {
- const unresolved = std.math.maxInt(usize);
- const ordinals = try gpa.alloc(usize, entries.len);
- @memset(ordinals, unresolved);
-
- const Pending = struct { depth: u8, ordinal: usize };
- var pending: [256]Pending = undefined;
- var pending_len: usize = 0;
- for (entries, 0..) |entry, ordinal| {
- while (pending_len > 0 and pending[pending_len - 1].depth >= entry.depth)
- pending_len -= 1;
-
- if (usableDestination(entry.destination) != null) {
- ordinals[ordinal] = ordinal;
- for (pending[0..pending_len]) |ancestor|
- ordinals[ancestor.ordinal] = ordinal;
- pending_len = 0;
- } else if (entry.destination == .none) {
- pending[pending_len] = .{ .depth = entry.depth, .ordinal = ordinal };
- pending_len += 1;
- }
- }
- return ordinals;
- }
-
- /// A title on one row: blanks, controls and broken bytes as one space
- /// between words and none at its ends; `[untitled]` for none, `[empty
- /// title]` for one with nothing to print.
- fn cleanTitle(w: *std.Io.Writer, title: ?[]const u8) std.Io.Writer.Error!void {
- const raw = title orelse return w.writeAll("[untitled]");
- var i: usize = 0;
- var wrote = false;
- var pending_space = false;
- while (i < raw.len) {
- const n: usize = std.unicode.utf8ByteSequenceLength(raw[i]) catch {
- pending_space = wrote;
- i += 1;
- continue;
- };
- if (i + n > raw.len) {
- pending_space = wrote;
- break;
- }
- const cp = std.unicode.utf8Decode(raw[i .. i + n]) catch {
- pending_space = wrote;
- i += n;
- continue;
- };
- const whitespace_or_control = cp <= 0x20 or cp == 0x7f or
- (cp >= 0x80 and cp <= 0x9f) or cp == 0x2028 or cp == 0x2029;
- if (whitespace_or_control) {
- pending_space = wrote;
- } else {
- if (pending_space) try w.writeByte(' ');
- try w.writeAll(raw[i .. i + n]);
- wrote = true;
- pending_space = false;
- }
- i += n;
- }
- if (!wrote) try w.writeAll("[empty title]");
- }
-
- pub fn render(gpa: std.mem.Allocator, path: []const u8, entries: []const pdf.OutlineEntry) ![]u8 {
- const ordinals = try resolveOrdinals(gpa, entries);
- defer gpa.free(ordinals);
- var out: std.Io.Writer.Allocating = .init(gpa);
- errdefer out.deinit();
- writeRows(&out.writer, std.fs.path.basename(path), entries, ordinals) catch return error.OutOfMemory;
- return out.toOwnedSlice();
- }
-
- /// A row an entry with somewhere to go: where (`file:PAGE:ORDINAL`, or
- /// its URI), indented by depth, its title.
- fn writeRows(w: *std.Io.Writer, target: []const u8, entries: []const pdf.OutlineEntry, ordinals: []const usize) std.Io.Writer.Error!void {
- for (entries, ordinals, 0..) |entry, resolved, ordinal| {
- if (resolved == std.math.maxInt(usize)) continue;
- // unreachable: resolveOrdinals resolves only to usable destinations
- switch (usableDestination(entries[resolved].destination) orelse unreachable) {
- .internal => |internal| try w.print("{s}:{d}:{d} ", .{ target, internal.page + 1, ordinal + 1 }),
- .external => |uri| try w.print("{s} ", .{uri}),
- .none => unreachable,
- }
- try w.splatByteAll(' ', @as(usize, entry.depth) * 2);
- try cleanTitle(w, entry.title);
- try w.writeByte('\n');
- }
- }
-} else struct {};
diff --git a/src/replica.zig b/src/replica.zig
index 622537d7..25507ec5 100644
--- a/src/replica.zig
+++ b/src/replica.zig
@@ -175,7 +175,6 @@ pub const Authority = struct {
// tells an allocator from none.
var opts = options;
opts.image_allocator = opts.image_allocator orelse gpa;
- opts.pdf_allocator = opts.pdf_allocator orelse gpa;
opts.tree_sitter_allocator = opts.tree_sitter_allocator orelse gpa;
opts.frame_allocator = opts.frame_allocator orelse gpa;
const a = try gpa.create(Authority);
@@ -712,7 +711,6 @@ pub const Replica = struct {
o.frame_allocator = epoch;
o.tree_sitter_allocator = epoch;
o.image_allocator = o.image_allocator orelse std.heap.c_allocator;
- o.pdf_allocator = o.pdf_allocator orelse std.heap.c_allocator;
// The session's closed panes and Recent are the authority's.
o.state = .off;
// Its emulators off the epoch, as `terminal.create` makes a screen
diff --git a/src/rollback.zig b/src/rollback.zig
index ce4016d8..e08e6242 100644
--- a/src/rollback.zig
+++ b/src/rollback.zig
@@ -576,7 +576,7 @@ test "a copy put back is the core as it was; one let go keeps what was done" {
var e: Epoch = .{ .child = std.testing.allocator };
defer e.deinit();
const gpa = e.allocator();
- const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
p.pump(.{}) catch {};
const before = walk.digest(Pardes, p);
var c: Copy = .{};
@@ -606,7 +606,7 @@ test "a text written in place under a copy comes back byte for byte: typed into
var e: Epoch = .{ .child = std.testing.allocator };
defer e.deinit();
const gpa = e.allocator();
- const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
p.pump(.{}) catch {};
const f = for (p.panes) |slot| {
if (slot) |pane| if (pane.file) |*file| break file;
@@ -671,7 +671,7 @@ test "a view's slot, live or drawn outside a step (a replica's own, another live
var e: Epoch = .{};
defer e.deinit();
const gpa = e.allocator();
- const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
defer p.deinit();
p.pump(.{}) catch {};
_ = p.openView() orelse return error.NoView;
@@ -711,7 +711,7 @@ test "a register's texts are pinned, not copied, and come back whole" {
var e: Epoch = .{ .child = std.testing.allocator };
defer e.deinit();
const gpa = e.allocator();
- const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
p.pump(.{}) catch {};
// A terminal's whole grid yanked: megabytes, and joined once read.
const grid = try std.testing.allocator.alloc(u8, 2 << 20);
@@ -740,7 +740,7 @@ test "a file's location rows are pinned whole, with what they own, and come back
var e: Epoch = .{ .child = std.testing.allocator };
defer e.deinit();
const gpa = e.allocator();
- const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
p.pump(.{}) catch {};
const f = for (p.panes) |slot| {
if (slot) |pane| if (pane.file) |*file| break file;
@@ -774,7 +774,7 @@ test "a rollback leaves the store and Recent as a speculation left them: they li
var e: Epoch = .{ .child = std.testing.allocator };
defer e.deinit();
const gpa = e.allocator();
- const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa });
p.pump(.{}) catch {};
var line: [std.fs.max_path_bytes + 16]u8 = undefined;
p.update(.{ .command = try lookAt(&line, "build.zig.zon") });
diff --git a/src/surface.zig b/src/surface.zig
index c058e101..15147146 100644
--- a/src/surface.zig
+++ b/src/surface.zig
@@ -260,9 +260,9 @@ pub const Region = struct {
/// A grip's pane has changes it has not saved.
dirty: bool = false,
/// A rail's thumb: rows from the rail's top, and how many. Zero rows is
- /// a rail with no thumb (an image). A native PDF's thumb is measured in
- /// document pixels and filled in by Pdf.draw while it paints, so read
- /// regions once render has returned.
+ /// a rail with no thumb (an image). A kind's thumb is where its paint
+ /// said its window is (`pa_paint.at`, `span`: a PDF's strip), filled in
+ /// as it paints, so read regions once render has returned.
thumb_y: u16 = 0,
thumb_h: u16 = 0,
/// The same thumb unrounded, for a pixel shell: its top and its length
diff --git a/src/tagline.zig b/src/tagline.zig
index 469d97d1..28cd2a9b 100644
--- a/src/tagline.zig
+++ b/src/tagline.zig
@@ -9,7 +9,6 @@ const panes = @import("panes.zig");
const edit = @import("edit.zig");
const exec = @import("exec.zig");
const config = @import("config.zig");
-const pdf_enabled = panes.Pdf.enabled;
const Layer = @import("Layer.zig");
const layout = @import("layout.zig");
const Pane = panes.Pane;
@@ -18,7 +17,6 @@ const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
const Pardes = pardes.Pardes;
pub const pane_tail = " " ++ config.pane_builtins_str;
-pub const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str;
pub const file_pane_tail = " " ++ config.file_pane_builtins_str;
fn withFileCommands(comptime tail: []const u8, comptime words: []const u8) []const u8 {
std.debug.assert(std.mem.endsWith(u8, tail, " Del"));
@@ -116,8 +114,6 @@ fn shownDir(arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
/// PDF's page, a terminal's directory -- without the space that parts it
/// from the tag's own text. It is never stored, and never edited.
pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
- if (comptime pdf_enabled) if (pane.pdf) |pv|
- return std.fmt.allocPrint(arena, "{s} [{d}/{d}]", .{ pv.path, pv.page + 1, pv.page_count });
// What is drawn: with no graphics, glyph art whatever `Petscii` says.
if (pane.addon != null) return pardes.Kind.prefix(p, arena, pane);
// A command pane: its directory, the line it runs, and how that went.
@@ -185,7 +181,8 @@ pub fn curTail(pane: *Pane) []const u8 {
}
pub fn defaultTail(pane: *const Pane) []const u8 {
- if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail;
+ // A kind's: Term, its words for its panes, Collapse Del (Kind.open).
+ if (pane.addon) |k| if (k.tail.len > 0) return k.tail.slice();
if (pane.query) |q| return if (q.frozen) query_frozen_tail else if (q.capped) query_capped_tail else query_live_tail;
if (pane.file) |file| if (file.output) |out| if (out.from == .preview) return query_live_tail;
if (pane.file) |file| if (file.listing != null) return dir_pane_tail;
@@ -293,8 +290,11 @@ pub fn wrapTag(arena: std.mem.Allocator, whole: []const u8, width: usize) !Shown
if (!first) try out.append(arena, '\n');
first = false;
var rest = line;
- while (panes.File.displayWidth(rest) > w) {
- var cut = modal.graphemeStart(rest, panes.File.rawAtDisplay(rest, w));
+ // The grapheme at column w, if the row runs past it: a row's
+ // measure, never the whole rest's (this runs on every step).
+ while (true) {
+ var cut = panes.File.byteAtDisplay(rest, w);
+ if (cut >= rest.len) break;
if (cut == 0) cut = modal.nextGrapheme(rest, 0);
try out.appendSlice(arena, rest[0..cut]);
try soft.append(arena, out.items.len);
diff --git a/src/tape.zig b/src/tape.zig
index cd777f96..2354fb06 100644
--- a/src/tape.zig
+++ b/src/tape.zig
@@ -573,7 +573,6 @@ pub const Tape = struct {
};
const gpa = t.core_gpa orelse t.gpa;
opts.image_allocator = gpa;
- opts.pdf_allocator = gpa;
opts.tree_sitter_allocator = gpa;
opts.frame_allocator = gpa;
t.core = switch (input) {
@@ -1033,6 +1032,12 @@ pub fn speculating() bool {
return if (on) |t| t.speculating else false;
}
+/// Inside a step: one being recorded, a replica's replay of one, or its
+/// speculation. A read made between steps (a frame drawn) is none.
+pub fn stepping() bool {
+ return if (on) |t| t.depth > 0 or t.replay or t.speculating else false;
+}
+
/// Screen-state terminals, on either side (`Tape.screen_state`).
pub fn screenState() bool {
return if (on) |t| t.screen_state else false;
@@ -1242,10 +1247,7 @@ pub fn startFromEnv() void {
pub fn replayMain(io: std.Io, path: []const u8) u8 {
const gpa = std.heap.c_allocator;
// What a shell starts before its core (tui.zig's localSession).
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.start(io, gpa);
- pardes.pdf.start(gpa);
- }
+ pardes.TerminalImages.start(io, gpa);
pardes.syntax.start(gpa);
const bytes = std.Io.Dir.cwd().readFileAlloc(std.Io.Threaded.global_single_threaded.io(), path, gpa, .unlimited) catch |err| {
std.debug.print("replay: cannot read {s}: {t}\n", .{ path, err });
diff --git a/src/terminal.zig b/src/terminal.zig
index 8204b0af..3d2e4943 100644
--- a/src/terminal.zig
+++ b/src/terminal.zig
@@ -21,9 +21,8 @@ pub const history_max = 64;
pub const VtSlot = ghostty_vt.Terminal;
/// A cell of an emulator's pages, as `getCell` reads it (src/echo.zig).
pub const PageCell = ghostty_vt.PageList.Cell;
-/// Kitty graphics are drawn where pixel geometry is (pdf_enabled, as for
-/// image panes' native placements).
-pub const images_enabled = pardes.pdf_enabled;
+/// Kitty graphics: a program's images are placements, as a kind's are.
+pub const images_enabled = true;
pub const TerminalImages = if (images_enabled) @import("TerminalImages.zig") else void;
pub const StreamSlot = ghostty_vt.Stream(MarkedHandler);
diff --git a/src/tui/tui.zig b/src/tui/tui.zig
index fd47cb67..78789f69 100644
--- a/src/tui/tui.zig
+++ b/src/tui/tui.zig
@@ -984,7 +984,6 @@ test "Kitty PDF fragments never declare pixels beyond their clipped bottom" {
}
test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cells is glyph art in every cell, and pixels stay put where it has them" {
- if (comptime !pardes.pdf_enabled) return;
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = 1 });
defer core.deinit();
@@ -1023,66 +1022,6 @@ test "on a terminal with no kitty graphics a program's 64x64 image over 8x4 cell
try std.testing.expectEqual(@as(usize, 32), painted);
}
-test "host watch closes initial race and reloads rename-over PDF while idle" {
- if (comptime !file_watch.supported or !pardes.pdf_enabled) return;
- const io = std.testing.io;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const original = try pardes.pdf.testFixture(gpa, "outline.pdf");
- defer gpa.free(original);
- const replacement = try pardes.pdf.testFixture(gpa, "offset-rotated.pdf");
- defer gpa.free(replacement);
- try tmp.dir.writeFile(io, .{ .sub_path = "live.pdf", .data = original });
- try tmp.dir.writeFile(io, .{ .sub_path = "initial.pdf", .data = replacement });
- try tmp.dir.writeFile(io, .{ .sub_path = "live-replacement.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 fd = file_watch.init(true);
- if (fd < 0) return error.WatchInitFailed;
- defer _ = libc.close(fd);
- var watches: file_watch.Table = @splat(null);
- defer file_watch.unwatchAll(fd, &watches);
-
- const core = try pardes.Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer core.deinit();
- try std.testing.expectEqual(@as(usize, 3), core.panes[0].?.pdf.?.page_count);
-
- try tmp.dir.rename("initial.pdf", tmp.dir, "live.pdf", io);
- var armed = false;
- while (core.nextEffect()) |effect| switch (effect) {
- .watch => |watch| if (watch.pane == 0 and watch.on) {
- armed = true;
- try std.testing.expect(!file_watch.applyEffect(core, io, fd, &watches, 0, true, watch.mode));
- },
- else => {},
- };
- try std.testing.expect(armed and watches[0] != null);
- try std.testing.expectEqual(@as(usize, 1), core.panes[0].?.pdf.?.page_count);
-
- try tmp.dir.rename("live-replacement.pdf", tmp.dir, "live.pdf", io);
- try std.testing.expect(file_watch.drain(fd));
-
- try std.testing.expect(!file_watch.reloadChanged(core, io, gpa, &watches));
- const pane = core.panes[0].?;
- try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count);
- const disk_identity = try file_watch.identify(io, path);
- switch (watches[0].?.generation) {
- .pdf => |accepted| try std.testing.expect(accepted != null and accepted.?.eql(disk_identity)),
- .text => return error.PdfWatchStoredTextGeneration,
- }
- try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "reloaded") != null);
-
- core.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- const surface = try core.render(frame.allocator());
- try std.testing.expect(surface.placements.items.len > 0);
- const shown = surface.placements.items[0];
- try std.testing.expectEqual(pardes.Placement.keyOf(pane.serial, 0, pardes.panes.Pdf.rasterForPage(pane.pdf.?, 0).?.revision), shown.key);
-}
-
fn kittyImageRepresentable(place: pardes.Placement) bool {
return place.raster.w > 0 and place.raster.h > 0 and
place.raster.w <= std.math.maxInt(u16) and place.raster.h <= std.math.maxInt(u16);
@@ -1096,26 +1035,6 @@ fn surfaceHasKittyKey(surface: *const pardes.Surface, key: u64) bool {
return false;
}
-const PdfWheelTarget = struct { pane: usize, page: usize };
-
-fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWheelTarget {
- if (comptime !pardes.pdf_enabled) return null;
- if (!core.view().frontend.native_images or mouse.type != .press or
- (mouse.button != .wheel_up and mouse.button != .wheel_down) or
- mouse.col < 0 or mouse.row < 0) return null;
- const col: u16 = @intCast(mouse.col);
- const row: u16 = @intCast(mouse.row);
- for (core.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- const rect = core.view().rects[id];
- if (col < rect.x or col >= rect.x + rect.w or
- row < rect.y or row >= rect.y + rect.h) continue;
- const page = pane.pdfPage() orelse return null;
- return .{ .pane = id, .page = page };
- }
- return null;
-}
-
/// Where a session's terminal comes from: /dev/tty, as a plain `pardes`
/// opens it; one open already (a session forked off its stub,
/// daemon.forkSession); or none, until one is attached (`--detach`).
@@ -1221,21 +1140,15 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se
const have: ?*replica.Have = if (far) &have_store else null;
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.start(io, allocs.image);
- pardes.pdf.start(allocs.pdf);
- }
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.Kind.heap = allocs.addon;
pardes.syntax.start(allocs.tree_sitter);
defer {
- if (comptime pardes.pdf_enabled) {
- pardes.TerminalImages.stop();
- pardes.pdf.stop();
- }
+ pardes.TerminalImages.stop();
pardes.syntax.stop();
}
var o = opts;
o.image_allocator = allocs.image;
- o.pdf_allocator = allocs.pdf;
var joined: replica.Joined = undefined;
var r = replica.join(gpa, &joined, path, session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)});
@@ -1507,7 +1420,6 @@ fn localSession(
defer pardes.memory.deinit();
var options = opts;
options.image_allocator = allocs.image;
- options.pdf_allocator = allocs.pdf;
options.tree_sitter_allocator = allocs.tree_sitter;
options.frame_allocator = allocs.frame;
@@ -1668,9 +1580,7 @@ fn localSession(
core.deinit();
core = nc;
sh.core = nc;
- if (comptime pardes.pdf_enabled) if (live.on) {
- core.update(.{ .resize = terminalSize(live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix) });
- };
+ if (live.on) core.update(.{ .resize = terminalSize(live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix) });
}
}
if (fs) |f| {
@@ -2316,17 +2226,7 @@ const Shell = struct {
const room = max_paste_bytes -| s.paste_buf.written().len;
s.paste_buf.writer.writeAll(bytes[0..@min(bytes.len, room)]) catch {};
} else s.feed(vaxis_input.keyEvent(key)),
- .mouse => |m| {
- const pdf_before = nativePdfWheelTarget(core, m);
- if (mouseEvent(m)) |ev| s.feed(ev);
- if (pdf_before) |before| {
- if (core.panes[before.pane]) |pane| {
- if (pane.pdfPage()) |page| {
- if (page != before.page) return true;
- }
- }
- }
- },
+ .mouse => |m| if (mouseEvent(m)) |ev| s.feed(ev),
.paste => |bytes| {
s.feed(.{ .paste = bytes });
s.gpa.free(@constCast(bytes));
@@ -2385,7 +2285,7 @@ const Shell = struct {
sc.size = ws;
sc.vx.resize(s.gpa, sc.tty.writer(), ws) catch {};
}
- s.feed(.{ .resize = if (comptime pardes.pdf_enabled) terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) else .{ .cols = ws.cols, .rows = ws.rows } });
+ s.feed(.{ .resize = terminalSize(ws.cols, ws.rows, ws.x_pixel, ws.y_pixel) });
}
/// A SIGWINCH: the terminal, if it changed size, resized in its view
diff --git a/src/walk.zig b/src/walk.zig
index dc743a4d..d7ee63b3 100644
--- a/src/walk.zig
+++ b/src/walk.zig
@@ -1051,7 +1051,6 @@ const DecodeError = error{ EndOfDump, BadDump, Incompatible, OutOfMemory };
/// `image` holds with `allocs.image`.
const Allocators = struct {
image: ?std.mem.Allocator = null,
- pdf: ?std.mem.Allocator = null,
terminal: ?std.mem.Allocator = null,
};
@@ -1281,8 +1280,8 @@ pub fn Load(comptime roots: []const type) type {
out.* = .{ .raw = raw };
return;
}
- // A field this build compiles out (a PDF slot where there is no
- // MuPDF): passed over, said only when it held something.
+ // A field this build compiles out (a void field): passed over,
+ // said only when it held something.
if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) {
const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0);
try l.skip(ty);
@@ -2378,8 +2377,8 @@ pub const Get = struct {
if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
l.gpa = a;
};
- // A field this build compiles out (a PDF slot where there is no
- // MuPDF): passed over, said when it held something.
+ // A field this build compiles out (a void field): passed over,
+ // said when it held something.
if (comptime kindOf(Canon(F)) == .void) {
if ((try slotOf(c)).tag != .none) l.note("{s}: not in this build", .{l.field});
return;
diff --git a/src/wire.zig b/src/wire.zig
index 91e805e7..d083ea82 100644
--- a/src/wire.zig
+++ b/src/wire.zig
@@ -9,6 +9,8 @@ const builtin = @import("builtin");
const pardes = @import("pardes.zig");
const config = @import("pardes_config");
+/// 22: a PDF's pixel scroll (0x1a) is gone with the core's PDF, the pdf
+/// addon's panes scrolled by the wheel as any kind's are;
/// 21: a session's views are `Pardes.views` in its dump and its digest
/// (src/views.zig), the panes' shares of the others under `shares`;
/// 20: a digest takes a blob of 4 KiB and up (a file's text, a register's,
@@ -29,7 +31,7 @@ const config = @import("pardes_config");
/// part B); 14: the hello names a session and
/// carries the semantics hash, and a ping is answered (phase 5's
/// groundwork); 13: the frames went (phase 3).
-pub const version: u16 = 21;
+pub const version: u16 = 22;
/// The terminal's build and the window's step alike (`semantics`).
const family = switch (config.platform) {
@@ -56,13 +58,13 @@ const family = switch (config.platform) {
pub const semantics: u64 = blk: {
@setEvalBranchQuota(1_000_000);
break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint(
- "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} mupdf {} workspace_tag {} sources {}\nusize {d} {t}\n{s}\n{s}",
+ "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n{s}\n{s}",
.{
version, config.version, config.commit orelse "unstamped",
family, config.syntax_highlighting, config.syntax_zig_grammar,
- config.syntax_minimal_grammars, config.syntax_full_grammars, config.mupdf,
- config.workspace_tag, config.embed_sources, @sizeOf(usize),
- builtin.cpu.arch.endian(), config.deps, pardes.tape.shape,
+ config.syntax_minimal_grammars, config.syntax_full_grammars, config.workspace_tag,
+ config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(),
+ config.deps, pardes.tape.shape,
},
));
};
@@ -103,8 +105,8 @@ pub const ClientTag = enum(u8) {
resize = 0x12,
paste = 0x18,
command = 0x19,
- pdf_scroll = 0x1a,
- // 0x1b and 0x1c were a pinch and a touch scroll, gone since.
+ // 0x1a was a PDF's pixel scroll, 0x1b and 0x1c a pinch and a touch
+ // scroll, gone since.
pointer_leave = 0x1d,
focus = 0x1e,
/// Which frontend the client is: a window, or a terminal.
@@ -323,14 +325,6 @@ fn getSlice32(r: *std.Io.Reader) Error![]const u8 {
return r.take(n);
}
-/// A pane id the core can actually index. `Event.output{ .pane = 200 }`
-/// would reach `p.panes[200]`.
-fn getPane(r: *std.Io.Reader) Error!u8 {
- const pane = try r.takeByte();
- if (pane >= pardes.MAX_PANES) return error.BadValue;
- return pane;
-}
-
/// A grid the core can render into. Zero is refused rather than clamped: a
/// frontend that has not been sized yet must not be allowed to collapse a
/// shared session to nothing.
@@ -539,11 +533,6 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
},
.paste => |b| try putSlice32(&w, b),
.command => |line| try putSlice16(&w, line),
- .pdf_scroll => |s| {
- try w.writeByte(s.pane);
- try w.writeInt(u32, @bitCast(s.delta_pixels), .little);
- try w.writeByte(@intFromBool(s.glide));
- },
.pointer_leave => {},
.focus => |focused| try w.writeByte(@intFromBool(focused)),
.frontend => |f| {
@@ -623,7 +612,6 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
},
.paste => .{ .event = .{ .paste = try getSlice32(&r) } },
.command => .{ .event = .{ .command = try r.take(try r.takeInt(u16, .little)) } },
- .pdf_scroll => .{ .event = .{ .pdf_scroll = .{ .pane = try getPane(&r), .delta_pixels = try getF32(&r), .glide = try getBool(&r) } } },
.pointer_leave => .{ .event = .pointer_leave },
.focus => .{ .event = .{ .focus = try getBool(&r) } },
.frontend => .{ .event = .{ .frontend = .{ .windowed = try getBool(&r), .native_images = try getBool(&r), .native_image_patches = try getBool(&r) } } },
@@ -646,7 +634,7 @@ pub fn clientBound(msg: ClientMsg) usize {
.event => |ev| switch (ev) {
// Its hits' places (14 bytes each) past the slack.
.mouse => 28,
- .resize, .pdf_scroll, .pointer_leave, .focus, .frontend => 0,
+ .resize, .pointer_leave, .focus, .frontend => 0,
.key => |k| k.text.len,
.paste => |b| b.len,
.command => |line| line.len,
@@ -746,12 +734,6 @@ test "detached wire: every Event variant round-trips" {
}
try testing.expectEqualStrings("clip", (try roundClient(&buf, .{ .event = .{ .paste = "clip" } })).event.paste);
try testing.expectEqualStrings("Look /x", (try roundClient(&buf, .{ .event = .{ .command = "Look /x" } })).event.command);
- {
- const got = (try roundClient(&buf, .{ .event = .{ .pdf_scroll = .{ .pane = 2, .delta_pixels = -12.5, .glide = false } } })).event.pdf_scroll;
- try testing.expectEqual(@as(u8, 2), got.pane);
- try testing.expectEqual(@as(f32, -12.5), got.delta_pixels);
- try testing.expect(!got.glide);
- }
try testing.expectEqual(
std.meta.Tag(pardes.Event).pointer_leave,
(try roundClient(&buf, .{ .event = .pointer_leave })).event,
@@ -780,7 +762,7 @@ test "detached wire: a session is never told to do a frontend's remembering" {
"stamp",
// ...and everything a person can do to a window.
"key", "mouse", "resize",
- "paste", "command", "pdf_scroll", "pointer_leave", "focus",
+ "paste", "command", "pointer_leave", "focus",
// ...and which of its frontends the person sits at: a window, or a
// terminal (what the view draws, and the words it takes).
"frontend",
@@ -893,13 +875,6 @@ test "detached wire: values a field cannot mean are refused" {
@backingInt(ClientTag.key),
&.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 },
));
- // A pane the core cannot index. `pdf_scroll` reads its pane byte before the
- // f32 that follows, so a one-byte payload reaches the check this is about
- // rather than tripping `EndOfStream` first.
- try testing.expectError(error.BadValue, decodeClient(
- @backingInt(ClientTag.pdf_scroll),
- &.{pardes.MAX_PANES},
- ));
// A session name longer than the daemon keeps one: refused, never cut
// to another session's name.
{
@@ -912,14 +887,6 @@ test "detached wire: values a field cannot mean are refused" {
try testing.expectEqual(@as(usize, max_name), (try decodeClient(@backingInt(ClientTag.hello), &hello)).hello.session.len);
try testing.expect(header_len + hello.len == hello_max);
}
- // A NaN or an infinite scroll distance.
- {
- var scroll: [6]u8 = .{ 0, 0, 0, 0, 0, 1 };
- std.mem.writeInt(u32, scroll[1..5], @bitCast(std.math.nan(f32)), .little);
- try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pdf_scroll), &scroll));
- std.mem.writeInt(u32, scroll[1..5], @bitCast(std.math.inf(f32)), .little);
- try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pdf_scroll), &scroll));
- }
}
test "detached wire: max_payload bounds every message this protocol can build" {
diff --git a/test/behaviour.zig b/test/behaviour.zig
index 685128df..de0cb83c 100644
--- a/test/behaviour.zig
+++ b/test/behaviour.zig
@@ -4,6 +4,7 @@
//! so a test sees the session as a 9P client does.
test {
_ = @import("behaviour/addons.zig");
+ _ = @import("behaviour/addons_pdf.zig");
_ = @import("behaviour/addresses.zig");
_ = @import("behaviour/builtins.zig");
_ = @import("behaviour/callstack.zig");
diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig
new file mode 100644
index 00000000..f3c2d872
--- /dev/null
+++ b/test/behaviour/addons_pdf.zig
@@ -0,0 +1,231 @@
+//! docs/typ/reference.typ, Addons <addons> and the PDF passages of Panes
+//! <panes> and Look and exec <look-and-exec>: a PDF is a pane of the pdf
+//! addon (addons/pdf/pdf.c), driven here as a 9P client drives it. What
+//! test/pdf.zig asked of the core's PDF code before it left the core.
+const std = @import("std");
+const Session = @import("session").Session;
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+/// The pictures /screen places for pane `serial`: their keys and the part
+/// of their pixels shown, `[x, y, w, h]`.
+const Shown = struct { key: []const u8, src: [4]i64 };
+
+fn shown(s: *Session, serial: u32) ![]Shown {
+ const a = s.arena.allocator();
+ const json = try std.json.parseFromSliceLeaky(std.json.Value, a, try s.read("/screen"), .{});
+ var out: std.ArrayList(Shown) = .empty;
+ const images = json.object.get("images") orelse return out.items;
+ for (images.array.items) |im| {
+ if (im.object.get("serial").?.integer != serial) continue;
+ var src: [4]i64 = undefined;
+ for (im.object.get("src").?.array.items, &src) |v, *o| o.* = v.integer;
+ const key = im.object.get("key").?;
+ try out.append(a, .{ .key = if (key == .string) key.string else try std.fmt.allocPrint(a, "{d}", .{key.integer}), .src = src });
+ }
+ return out.items;
+}
+
+fn ctlOf(s: *Session, n: u32) ![]const u8 {
+ return s.read(s.at("/pane/{d}/ctl", .{n}));
+}
+
+test "addons: a PDF is the pdf addon's pane, its pages pictures, its page in its tag, its fit and tint in its ctl and stepped by its words, all of it back from a Dump" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ try std.testing.expect(has(try s.read("/index"), " pdf "));
+ try std.testing.expect(std.mem.startsWith(u8, try s.read("/addons"), "pdf 1 2.1 1 /"));
+ const pages = (try s.pdfPage(n))[1];
+ try std.testing.expectEqual(@as(u32, 16), pages);
+ // Its first page, a picture over its body.
+ const first = try shown(&s, n);
+ try std.testing.expect(first.len >= 1);
+ // Its tag: its page, then the core's art words (it placed a picture),
+ // its path and its kind's words.
+ const tag = try s.read(s.at("/pane/{d}/tag", .{n}));
+ try std.testing.expect(std.mem.startsWith(u8, tag, "[1/16] petscii:on palette:commodore ascii:on /"));
+ try std.testing.expect(has(tag, "/docs/design.pdf Term PdfSections PdfTint PdfFit Collapse Del"));
+ try std.testing.expect(has(try ctlOf(&s, n), " fit:width tint:filtered mode:normal "));
+ // The words: bare they step, given a value they take it, any other
+ // value refused; another pane's is refused and leaves the PDF alone.
+ const ctl = s.at("/pane/{d}/ctl", .{n});
+ try s.write(ctl, "PdfFit\n");
+ try std.testing.expect(has(try ctlOf(&s, n), " fit:height "));
+ try s.write(ctl, "PdfTint full\n");
+ try std.testing.expect(has(try ctlOf(&s, n), " tint:full "));
+ // A tint is a page drawn again: another picture.
+ const tinted = try shown(&s, n);
+ try std.testing.expect(tinted.len >= 1 and !std.mem.eql(u8, tinted[0].key, first[0].key));
+ _ = try s.refused(ctl, "PdfTint loud\n");
+ try std.testing.expect(has(s.said, "PdfTint takes disabled, filtered or full"));
+ const text = std.mem.sliceTo(try s.read("/index"), ' ');
+ _ = try s.refused(s.at("/pane/{s}/ctl", .{text}), "PdfFit\n");
+ try std.testing.expect(has(try ctlOf(&s, n), " fit:height tint:full "));
+ // Its last page, then a Dump: restored it is there, as it was.
+ try s.keys("ge");
+ try std.testing.expectEqual(@as(u32, 16), (try s.pdfPage(n))[0]);
+ try s.write("/ctl", "Dump\n");
+ const label = try s.arena.allocator().dupe(u8, std.mem.sliceTo(try s.read("/dumps"), ' '));
+ try s.write(ctl, "Del\n");
+ try s.write("/ctl", s.at("Restore {s}\n", .{label}));
+ // (A test's session steps only on its writes: a key that moves nothing
+ // is the step after the Restore a host's wake makes.)
+ try s.keys("0");
+ var back: u32 = 0;
+ var lines = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (lines.next()) |line| if (has(line, " pdf ")) {
+ back = try std.fmt.parseInt(u32, std.mem.sliceTo(line, ' '), 10);
+ };
+ try std.testing.expect(back != 0);
+ try std.testing.expectEqual(@as(u32, 16), (try s.pdfPage(back))[0]);
+ try std.testing.expect(has(try ctlOf(&s, back), " fit:height tint:full "));
+ try std.testing.expect((try shown(&s, back)).len >= 1);
+}
+
+test "addons: a PDF's / lists its hits as file.pdf:P:H rows in a +Search, n walks them, a Look of one turns to its page, Esc drops the search first and then leaves, and a hit not there is a miss" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ try s.keys("/pardes\r");
+ var rows: []const u8 = "";
+ var it = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (it.next()) |line| if (has(line, "+Search")) {
+ rows = try s.read(s.at("/pane/{s}/body", .{std.mem.sliceTo(line, ' ')}));
+ };
+ // (Each row its place, then the text, as a +Search lays its rows out.)
+ try std.testing.expect(std.mem.startsWith(u8, rows, "design.pdf:1:1\n"));
+ try std.testing.expect(std.mem.count(u8, rows, "design.pdf:") > 3);
+ // At its first hit's page; from the PDF n walks its rows (the
+ // keyboard on the next, selected), and a Look of a row turns there.
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ var search: u32 = 0;
+ it = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (it.next()) |line| if (has(line, "+Search")) {
+ search = try std.fmt.parseInt(u32, std.mem.sliceTo(line, ' '), 10);
+ };
+ try s.write("/focus", s.at("{d}\n", .{n}));
+ try s.keys("n");
+ try std.testing.expectEqual(search, try s.focused());
+ var last: []const u8 = "";
+ var places = std.mem.tokenizeScalar(u8, rows, '\n');
+ while (places.next()) |row| if (std.mem.startsWith(u8, row, "design.pdf:")) {
+ last = row;
+ };
+ const page = try std.fmt.parseInt(u32, last["design.pdf:".len..std.mem.indexOfScalarPos(u8, last, "design.pdf:".len, ':').?], 10);
+ try s.write(s.at("/pane/{d}/look", .{search}), s.at("{s}\n", .{last}));
+ try std.testing.expectEqual(page, (try s.pdfPage(n))[0]);
+ try std.testing.expectEqual(n, try s.focused());
+ // A hit there is a place; one not there a miss said with its path.
+ const look = s.at("/pane/{d}/look", .{n});
+ try s.write(look, ":1:1\n");
+ _ = try s.refused(look, ":1:99\n");
+ try std.testing.expect(has(try s.read("/log"), "design.pdf has no search hit 99 on page 1"));
+ // Esc: the search goes first (no hit is a place now), then the pane.
+ try s.keys("\x1b");
+ try std.testing.expectEqual(n, try s.focused());
+ _ = try s.refused(look, ":1:1\n");
+ try s.keys("\x1b");
+ try std.testing.expect(try s.focused() != n);
+}
+
+test "addons: a PDF's f is its PdfSections, its outline as places a Look in it goes to (none once the PDF is gone), and a jump back over a far one is Ctrl-o's, Forward's on, two places on a page a window apart two" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("test/pdf-fixtures/outline.pdf");
+ try s.keys("f");
+ var list: u32 = 0;
+ var it = std.mem.tokenizeScalar(u8, try s.read("/index"), '\n');
+ while (it.next()) |line| if (has(line, "/+PdfSections")) {
+ list = try std.fmt.parseInt(u32, std.mem.sliceTo(line, ' '), 10);
+ };
+ try std.testing.expect(list != 0);
+ const body = try s.read(s.at("/pane/{d}/body", .{list}));
+ try std.testing.expect(std.mem.startsWith(u8, body, "outline.pdf:"));
+ // The last row of a section in it: its page, where a Look lands.
+ var last: []const u8 = "";
+ var rows = std.mem.tokenizeScalar(u8, body, '\n');
+ while (rows.next()) |row| if (std.mem.startsWith(u8, row, "outline.pdf:")) {
+ last = row;
+ };
+ const place = last[0..std.mem.indexOfScalar(u8, last, ' ').?];
+ var fields = std.mem.splitScalar(u8, place, ':');
+ _ = fields.next();
+ const page = try std.fmt.parseInt(u32, fields.next().?, 10);
+ try s.write(s.at("/pane/{d}/look", .{list}), s.at("{s}\n", .{place}));
+ try std.testing.expectEqual(page, (try s.pdfPage(n))[0]);
+ // A jump far: Ctrl-o goes back, Ctrl-i on.
+ try s.write(s.at("/pane/{d}/look", .{n}), ":1\n");
+ try s.keys("ge");
+ const end = (try s.pdfPage(n))[0];
+ try s.keys("\x0f");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ // (Ctrl-i is Tab without kitty's keyboard: its word, Forward.)
+ try s.write("/ctl", "Forward\n");
+ try std.testing.expectEqual(end, (try s.pdfPage(n))[0]);
+ // Two places on page 1 more than a window apart (the second its 0.8,
+ // as its `where` says a place) are two visits: Ctrl-o from a far one
+ // goes to the second, then the first, where they were.
+ const look = s.at("/pane/{d}/look", .{n});
+ try s.write(look, ":1\n");
+ const top = (try shown(&s, n))[0].src[1];
+ try s.write(look, ":1:0.8\n");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ const down = (try shown(&s, n))[0].src[1];
+ try std.testing.expect(down > top);
+ try s.write(look, ":3\n");
+ try s.keys("\x0f");
+ try std.testing.expectEqual(down, (try shown(&s, n))[0].src[1]);
+ try s.keys("\x0f");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ try std.testing.expectEqual(top, (try shown(&s, n))[0].src[1]);
+ // The PDF gone, its list's rows are no place: not another pane's.
+ try s.write(s.at("/pane/{d}/ctl", .{n}), "Del\n");
+ _ = try s.refused(s.at("/pane/{d}/look", .{list}), s.at("{s}\n", .{place}));
+ try std.testing.expect(has(try s.read("/log"), "the pane its list is of is gone"));
+}
+
+test "addons: a closed PDF is in Recent and its jumps, and a jump back to it opens it at its page; a tall page is shown a band of it at a time" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ try s.write(s.at("/pane/{d}/look", .{n}), ":5\n");
+ const name = std.mem.trimEnd(u8, try s.read(s.at("/pane/{d}/name", .{n})), "\n");
+ // From a scratch, Back is the nearest place of any file: the PDF's,
+ // closed meanwhile, opened again at its page.
+ const scratch = try s.newPane();
+ try s.write("/focus", s.at("{d}\n", .{scratch}));
+ try s.write(s.at("/pane/{d}/ctl", .{n}), "Del\n");
+ try std.testing.expect(has(try s.read("/recent"), s.at("closed {s}", .{name})));
+ try s.keys("\x0f");
+ const again = try s.focused();
+ try std.testing.expect(again != scratch);
+ try std.testing.expectEqual(@as(u32, 5), (try s.pdfPage(again))[0]);
+ // A page 9000 points tall: a band of its rows, never the whole.
+ const tall = try s.lookFile("test/pdf-fixtures/tall.pdf");
+ const bands = try shown(&s, tall);
+ try std.testing.expect(bands.len >= 1);
+ try std.testing.expect(bands[0].src[3] <= 8192);
+}
+
+test "addons: a PDF's body is its page's text layer, read from any offset and never written; a truncated PDF is a refused Look saying why" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("test/pdf-fixtures/links.pdf");
+ const body = s.at("/pane/{d}/body", .{n});
+ const whole = try s.arena.allocator().dupe(u8, try s.read(body));
+ try std.testing.expect(has(whole, "target.txt"));
+ // (Read from an offset, as a mount's chunked reads ask.)
+ try std.testing.expectEqualStrings(whole[3..], try s.readAt(body, 3, 4096));
+ try std.testing.expect(try s.refused(body, "more\n") != 0);
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "test/pdf-fixtures/links.pdf", s.arena.allocator(), .unlimited);
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "cut.pdf", .data = bytes[0..40] });
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)];
+ _ = try s.refused("/look", s.at("{s}/cut.pdf\n", .{dir}));
+ try std.testing.expect(has(s.said, "cut.pdf") and has(s.said, "not a PDF pardes can read"));
+}
diff --git a/test/behaviour/keys.zig b/test/behaviour/keys.zig
index eeaacf7d..879ff441 100644
--- a/test/behaviour/keys.zig
+++ b/test/behaviour/keys.zig
@@ -136,28 +136,33 @@ test "keys: a count or a prefix a click or a change of pane cancels leaves nothi
}
}
-test "keys: a PDF shown as text turns pages for the moving keys, counted, and the editing keys do nothing" {
+test "keys: a PDF's moving keys scroll its strip, counted, gg G and ge go to pages, and the editing keys do nothing" {
var s = try Session.initFile(std.testing.allocator, "x\n");
defer s.deinit();
const n = try s.lookFile("docs/design.pdf");
const pages = (try s.pdfPage(n))[1];
try std.testing.expect(pages > 3);
- // j k, Ctrl-d Ctrl-u, Ctrl-f Ctrl-b: a page each, counted.
- for ([_][]const u8{ "2j", "2k", "2\x04", "2\x15", "2\x06", "2\x02" }, 0..) |keys, i| {
- try s.keys(keys);
- try std.testing.expectEqual(@as(u32, if (i % 2 == 0) 3 else 1), (try s.pdfPage(n))[0]);
- }
- for ([_]struct { []const u8, u32 }{ .{ "ge", pages }, .{ "gg", 1 }, .{ "3gg", 3 }, .{ "2G", 2 } }) |step| {
+ for ([_]struct { []const u8, u32 }{ .{ "ge", pages }, .{ "gg", 1 }, .{ "3gg", 3 }, .{ "2G", 2 }, .{ "G", pages }, .{ "gg", 1 } }) |step| {
try s.keys(step[0]);
try std.testing.expectEqual(step[1], (try s.pdfPage(n))[0]);
}
+ // j a cell's pixels, Ctrl-f a window's: a count moves that many, so
+ // thirty windows down is past the first page (a window is a few rows
+ // of a page here), thirty back at the first, and k at the top stays.
+ try s.keys("k");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ try s.keys("30\x06");
+ try std.testing.expect((try s.pdfPage(n))[0] > 1);
+ try s.keys("30\x02");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ try s.keys("200j");
+ try std.testing.expect((try s.pdfPage(n))[0] > 1);
+ try s.keys("2G");
// Consumed, with their count: the page stays, no selection begins, and
- // the next j is one page.
- try s.keys("4dv|");
+ // no mode changes.
+ try s.keys("4dv|i");
try std.testing.expectEqual(@as(u32, 2), (try s.pdfPage(n))[0]);
try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{n})), " mode:normal "));
- try s.keys("j");
- try std.testing.expectEqual(@as(u32, 3), (try s.pdfPage(n))[0]);
}
test "keys: SPC j n and SPC j p in plain text select its places, never a comment's slashes, round the end, opening nothing" {
@@ -334,23 +339,26 @@ test "keys: a PDF in normal mode keeps : (its tag and back), SPC (a leader, canc
var s = try Session.initFile(std.testing.allocator, "x\n");
defer s.deinit();
const n = try s.lookFile("docs/design.pdf");
- const body = (try s.cursor()).?;
- const tag = (try s.where("docs/design.pdf [1/"))[1];
+ // A page has no text cursor: the body shows none.
+ try std.testing.expect(try s.cursor() == null);
+ _ = try s.pdfPage(n);
+ const tag = (try s.where("[1/"))[1];
try s.keys(":");
+ // On its tag, which runs to three rows (its path, the core's art words).
const on_tag = (try s.cursor()).?[1];
- try std.testing.expect(on_tag == tag or on_tag == tag + 1);
+ try std.testing.expect(on_tag >= tag and on_tag <= tag + 2);
try std.testing.expect(std.mem.endsWith(u8, try s.read(s.at("/pane/{d}/ctl", .{n})), " mode:normal "));
try s.keys(":");
- try std.testing.expectEqual(body, (try s.cursor()).?);
- // The leader shows its keys at the row's end until one it has not.
+ try std.testing.expect(try s.cursor() == null);
+ // The leader shows its keys until one it has not.
try s.keys(" ");
- try std.testing.expect(std.mem.endsWith(u8, std.mem.trimEnd(u8, try screenRow(&s, body[1]), " "), " SPC"));
+ try std.testing.expect(std.mem.indexOf(u8, try s.screen(), " SPC") != null);
try s.keys("!");
- try std.testing.expect(!std.mem.endsWith(u8, std.mem.trimEnd(u8, try screenRow(&s, body[1]), " "), " SPC"));
+ try std.testing.expect(std.mem.indexOf(u8, try s.screen(), " SPC") == null);
try s.keys("/");
- try std.testing.expect(!std.meta.eql(body, (try s.cursor()).?));
+ try std.testing.expect(try s.cursor() != null);
try std.testing.expectEqual(n, try s.focused());
try s.keys("\x1b");
- try std.testing.expectEqual(body, (try s.cursor()).?);
+ try std.testing.expect(try s.cursor() == null);
try std.testing.expectEqual(n, try s.focused());
}
diff --git a/test/image_harness.zig b/test/image_harness.zig
index 02e6690b..46564dee 100644
--- a/test/image_harness.zig
+++ b/test/image_harness.zig
@@ -36,14 +36,14 @@ pub fn main(init: std.process.Init) !void {
defer arena_state.deinit();
const arena = arena_state.allocator();
const args = try init.minimal.args.toSlice(arena);
- // <pardes> <image.so> tui|gui [pdf]
- if (args.len != 4 and args.len != 5) return error.BadArgs;
+ // <pardes> <image.so> tui|gui [pdf <pdf.so>]
+ if (args.len != 4 and args.len != 6) return error.BadArgs;
const exe = try arena.dupeSentinel(u8, args[1], 0);
const image_addon = try std.Io.Dir.cwd().realPathFileAlloc(init.io, args[2], arena);
const backend = args[3];
- const pdf_mode = args.len == 5 and std.mem.eql(u8, args[4], "pdf");
- if (args.len == 5 and !pdf_mode) return error.BadArgs;
+ const pdf_mode = args.len == 6 and std.mem.eql(u8, args[4], "pdf");
+ if (args.len == 6 and !pdf_mode) return error.BadArgs;
const base = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-image-harness-{d}", .{libc.getpid()}, 0);
if (libc.mkdir(base, 0o755) != 0 and libc.errno(-1) != .EXIST) return error.MkdirFailed;
defer cleanupBase(arena, base);
@@ -60,6 +60,7 @@ pub fn main(init: std.process.Init) !void {
_ = setenv("XDG_DATA_HOME", try std.fmt.allocPrintSentinel(arena, "{s}/data", .{base}, 0), 1);
for ([_][]const u8{ "data", "data/pardes", "data/pardes/addons" }) |sub| _ = libc.mkdir(try std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ base, sub }, 0), 0o755);
if (libc.symlink(image_addon, try std.fmt.allocPrintSentinel(arena, "{s}/data/pardes/addons/image.so", .{base}, 0)) != 0) return error.SymlinkFailed;
+ if (pdf_mode) if (libc.symlink(try std.Io.Dir.cwd().realPathFileAlloc(init.io, args[5], arena), try std.fmt.allocPrintSentinel(arena, "{s}/data/pardes/addons/pdf.so", .{base}, 0)) != 0) return error.SymlinkFailed;
_ = setenv("HISTFILE", "/dev/null", 1);
_ = setenv("TERM", "xterm-256color", 1);
_ = setenv("LC_ALL", "C", 1);
@@ -84,7 +85,7 @@ fn cleanupBase(arena: std.mem.Allocator, base: [:0]const u8) void {
_ = libc.rmdir(config_dir);
const config_home = std.fmt.allocPrintSentinel(arena, "{s}/.config", .{base}, 0) catch return;
_ = libc.rmdir(config_home);
- const names = [_][]const u8{ "native.ppm", "pages.pdf", "latest.ppm", "latest.ppm.tmp", ".bash_history", "data/pardes/addons/image.so" };
+ const names = [_][]const u8{ "native.ppm", "pages.pdf", "latest.ppm", "latest.ppm.tmp", ".bash_history", "data/pardes/addons/image.so", "data/pardes/addons/pdf.so" };
for (names) |name| {
const path = std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ base, name }, 0) catch continue;
_ = libc.unlink(path);
diff --git a/test/mode.zig b/test/mode.zig
index 7335b4ef..1f21c7db 100644
--- a/test/mode.zig
+++ b/test/mode.zig
@@ -89,25 +89,10 @@ test "Mode from actual tag Exec preserves parked file and output insert transact
}
}
-test "Mode leaves image and PDF document modes unchanged" {
+test "Mode leaves a kind's pane (a picture) as it is" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const picture = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/mode-test.png", "");
try mode(p, 1, .normal);
try std.testing.expect(picture.addon != null);
- if (comptime panes.Pdf.enabled) {
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try panes.Pdf.pdf.testFixture(std.testing.allocator, "links.pdf");
- defer std.testing.allocator.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mode.pdf", .data = bytes });
- var buffer: [4096]u8 = undefined;
- const len = try tmp.dir.realPath(std.testing.io, &buffer);
- const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/mode.pdf", .{buffer[0..len]});
- defer std.testing.allocator.free(path);
- const document = try panes.Pdf.openPane(p, 2, path, 1, .last);
- const page = document.pdf.?.page;
- try mode(p, 2, .normal);
- try std.testing.expectEqual(page, document.pdf.?.page);
- }
}
diff --git a/test/panes.zig b/test/panes.zig
index 28a884ab..a19af1a6 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -2307,154 +2307,6 @@ const ImageTests = struct {
}
};
-const PdfTests = struct {
- const enabled = panes.Pdf.enabled;
- const pdf = panes.Pdf.pdf;
- const Point = panes.Pdf.Point;
- const Document = panes.Pdf.Document;
- const State = panes.Pdf.State;
- const probeWord = panes.Pdf.probeWord;
- const pointAtGeometry = panes.Pdf.pointAtGeometry;
- const SectionRows = panes.Pdf.SectionRows;
-
- test "feature-off PDF state is zero-sized" {
- if (!enabled) try std.testing.expectEqual(@as(usize, 0), @sizeOf(State));
- }
-
- test "PDF section rows preserve DFS ordinals and sanitise hierarchy" {
- if (!enabled) return;
- const entries = [_]pdf.OutlineEntry{
- .{ .depth = 0, .title = null, .destination = .none },
- .{ .depth = 1, .title = " Child\n\tTitle\x01 Café \u{2028} Next ", .destination = .{ .internal = .{ .page = 2, .x = 12, .y = 34 } } },
- .{ .depth = 0, .title = "", .destination = .{ .internal = .{ .page = 0, .x = null, .y = null } } },
- .{ .depth = 0, .title = "External", .destination = .{ .external = "https://example.com/manual" } },
- .{ .depth = 0, .title = "Dead branch", .destination = .none },
- .{ .depth = 0, .title = "Unsafe", .destination = .{ .external = "javascript:alert" } },
- .{ .depth = 0, .title = "Linked branch", .destination = .none },
- .{ .depth = 1, .title = "Deep link", .destination = .{ .external = "https://example.com/deep" } },
- };
- const rows = try SectionRows.render(std.testing.allocator, "/tmp/manual.pdf", &entries);
- defer std.testing.allocator.free(rows);
- try std.testing.expectEqualStrings(
- "manual.pdf:3:1 [untitled]\n" ++
- "manual.pdf:3:2 Child Title Café Next\n" ++
- "manual.pdf:1:3 [empty title]\n" ++
- "https://example.com/manual External\n" ++
- "https://example.com/deep Linked branch\n" ++
- "https://example.com/deep Deep link\n",
- rows,
- );
- try std.testing.expect(SectionRows.resolve(&entries, 4) == null);
- try std.testing.expect(SectionRows.resolve(&entries, 5) == null);
- const resolved = try SectionRows.resolveOrdinals(std.testing.allocator, &entries);
- defer std.testing.allocator.free(resolved);
- for (entries, 0..) |_, ordinal| {
- const single = SectionRows.resolve(&entries, ordinal);
- if (resolved[ordinal] == std.math.maxInt(usize)) {
- try std.testing.expect(single == null);
- } else {
- const bulk = SectionRows.usableDestination(entries[resolved[ordinal]].destination) orelse
- return error.MissingBulkPdfSectionDestination;
- try std.testing.expect(single != null);
- try std.testing.expect(std.meta.eql(single.?, bulk));
- }
- }
-
- // Every allocation site in the ordinal table and output growth remains
- // atomic: the testing allocator sees each induced failure cleaned up
- // before the first index at which the whole render can succeed.
- var rendered = false;
- for (0..64) |fail_index| {
- var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{
- .fail_index = fail_index,
- });
- const failure_gpa = failing.allocator();
- const attempt = SectionRows.render(failure_gpa, "/tmp/manual.pdf", &entries) catch |err| {
- try std.testing.expectEqual(error.OutOfMemory, err);
- continue;
- };
- failure_gpa.free(attempt);
- rendered = true;
- break;
- }
- try std.testing.expect(rendered);
- }
-
- test "bulk PDF section resolution matches single Look policy across DFS boundaries" {
- if (!enabled) return;
- const entries = [_]pdf.OutlineEntry{
- .{ .depth = 0, .title = "Resolved root", .destination = .none },
- .{ .depth = 1, .title = "Unsafe branch", .destination = .{ .external = "javascript:unsafe" } },
- .{ .depth = 2, .title = "Safe grandchild", .destination = .{ .internal = .{ .page = 1, .x = 4, .y = 8 } } },
- .{ .depth = 1, .title = "Unresolved child", .destination = .none },
- .{ .depth = 1, .title = "Sibling", .destination = .{ .internal = .{ .page = 2, .x = null, .y = null } } },
- .{ .depth = 0, .title = "Unresolved root", .destination = .none },
- .{ .depth = 0, .title = "Next root", .destination = .{ .internal = .{ .page = 3, .x = null, .y = null } } },
- };
- const bulk = try SectionRows.resolveOrdinals(std.testing.allocator, &entries);
- defer std.testing.allocator.free(bulk);
- const none = std.math.maxInt(usize);
- try std.testing.expectEqualSlices(usize, &.{ 2, none, 2, none, 4, none, 6 }, bulk);
- for (entries, 0..) |_, ordinal| {
- const single = SectionRows.resolve(&entries, ordinal);
- if (bulk[ordinal] == none) {
- try std.testing.expect(single == null);
- } else {
- const destination = SectionRows.usableDestination(entries[bulk[ordinal]].destination) orelse
- return error.MissingBoundaryPdfSectionDestination;
- try std.testing.expect(single != null);
- try std.testing.expect(std.meta.eql(single.?, destination));
- }
- }
- }
-
- test "PDF word probe owns quads and text without a selection object" {
- if (comptime !enabled) return;
- const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "docs/design.pdf", std.testing.allocator, .unlimited);
- defer std.testing.allocator.free(bytes);
- var document = try Document.openBytes(bytes);
- defer document.deinit();
- var found = try document.search(std.testing.allocator, 0, "Pardes");
- defer found.deinit(std.testing.allocator);
- const quad = found.quads[0].quad;
- const point = Point{
- .x = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4,
- .y = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4,
- };
-
- // Exactly one shared probe exercises the primitive used by both UI paths;
- // click-vs-hover equivalence belongs to production structure, not a second
- // test that can only restate this MuPDF result.
- var probe = (try probeWord(&document, std.testing.allocator, 0, point)) orelse
- return error.MissingPdfWordProbe;
- defer probe.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, 0), probe.page);
- try std.testing.expect(probe.quads.len > 0);
- try std.testing.expect(std.ascii.findIgnoreCase(probe.text, "Pardes") != null);
- }
-
- test "PDF point mapping restores band origin and fractional placement" {
- if (comptime !enabled) return;
- const point = pointAtGeometry(
- .{
- .src = .{ .x = 20, .y = 10, .w = 40, .h = 20 },
- .dst = .{ .x = 100, .y = 30, .w = 80, .h = 20 },
- },
- -0.5,
- 200,
- 200,
- 80,
- 120,
- 34,
- false,
- ) orelse return error.MissingPdfMappedPoint;
- // x: src 30; y: band 80 + local src 14. The returned coordinates address
- // pixel centers, matching MuPDF's normalized page-space contract.
- try std.testing.expectApproxEqAbs(@as(f32, 30.5 / 200.0), point.x, 0.000_001);
- try std.testing.expectApproxEqAbs(@as(f32, 94.5 / 200.0), point.y, 0.000_001);
- }
-};
-
const TerminalTests = struct {
// Tests asserting raw ANSI indices explicitly select helix, whose palette
// is inherited. Native-palette coverage lives in the overlay/eviction and
@@ -3636,13 +3488,11 @@ test {
_ = @import("output.zig");
_ = @import("column_drag.zig");
_ = @import("mode.zig");
- _ = @import("pdf.zig");
_ = @import("fs_namespace.zig");
_ = @import("hxdiff.zig");
_ = FileTests;
_ = OutputTests;
_ = ImageTests;
- _ = PdfTests;
_ = TerminalTests;
}
@@ -3858,3 +3708,166 @@ test "a terminal keeps its tag and two body rows through a squeeze, a drag and a
p.sync();
try std.testing.expect(p.view().rects[term].h >= p.panes[term].?.tag_rows + layout.min_body_rows);
}
+
+// ---- a PDF: a pane of the pdf addon (addons/pdf/pdf.c) ----
+
+const PdfAddon = struct {
+ const addons = @import("test_addons");
+ const pdf_lib: []const u8 = if (addons.has_pdf) addons.pdf else "";
+
+ /// Its jobs, run here and answered as a host's workers answer: an
+ /// event `land` steps (a core's own update, or an authority's). An
+ /// authority's host takes them as a session's does (`job`): one run
+ /// inside the effect would be an update a replica cannot replay.
+ fn jobs(core: *Pardes, land: anytype) !void {
+ while (core.nextEffect()) |e| if (e == .job) asked.append(e.job);
+ while (asked.pop()) |a| {
+ const j = pardes.host_io.KindJob.take(core, a.pane, a.serial, a.token) orelse continue;
+ defer j.drop();
+ j.run();
+ try land.step(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } });
+ }
+ }
+
+ const Asked = struct { pane: u8, serial: u32, token: u32 };
+ var asked: struct {
+ items: [16]Asked = undefined,
+ n: usize = 0,
+ fn append(q: *@This(), j: anytype) void {
+ if (q.n < q.items.len) q.items[q.n] = .{ .pane = j.pane, .serial = j.serial, .token = j.token };
+ q.n += @intFromBool(q.n < q.items.len);
+ }
+ fn pop(q: *@This()) ?Asked {
+ if (q.n == 0) return null;
+ q.n -= 1;
+ return q.items[q.n];
+ }
+ } = .{};
+
+ const host_vtable: pardes.Host.VTable = .{
+ .watched = struct {
+ fn f(_: ?*anyopaque) bool {
+ return false;
+ }
+ }.f,
+ .job = struct {
+ fn f(_: ?*anyopaque, pane: u8, serial: u32, token: u32) void {
+ asked.append(.{ .pane = pane, .serial = serial, .token = token });
+ }
+ }.f,
+ };
+
+ test "a client without the pdf addon shows a PDF pane as the session's frames of it, its pages by key, and its wheel goes to the session" {
+ if (!addons.has_pdf) return error.SkipZigTest;
+ const R = pardes.replica;
+ const gpa = std.testing.allocator;
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false);
+ defer a.deinit();
+ var screens: R.Screens = .init(gpa);
+ defer screens.deinit(a.core);
+ const peer = try screens.addPeer();
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
+ defer r.deinit();
+ const Land = struct {
+ a: *R.Authority,
+ r: *R.Replica,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ l.r.confirm(try l.a.local(ev));
+ }
+ };
+ const land: Land = .{ .a = a, .r = r };
+ var words: [64]pardes.Kind.LoadedWord = undefined;
+ var why: pardes.Kind.Buf(160) = .{};
+ const lib = pardes.Addon.readLoaded(pdf_lib, &words, &why);
+ try land.step(.{ .addon = .{ .op = .load, .pane = 0, .kind = &lib } });
+ try std.testing.expect(r.core().kinds.ops[r.core().kinds.n - 1] == null);
+ var buf: [4096]u8 = undefined;
+ const real = try std.Io.Dir.cwd().realPathFile(std.testing.io, "docs/design.pdf", &buf);
+ var line: [4200]u8 = undefined;
+ try land.step(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{buf[0..real]}) });
+ for (0..3) |_| {
+ try land.step(.tick);
+ try jobs(a.core, land);
+ }
+ // Its frame crosses: the replica draws the pane as the session
+ // painted it, its pages placed by key, its page in its tag.
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const deliver = struct {
+ fn f(au: *R.Authority, sc: *R.Screens, pe: u16, re: *R.Replica) !void {
+ var msgs: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (msgs.items) |m| std.testing.allocator.free(m);
+ msgs.deinit(std.testing.allocator);
+ }
+ try sc.flush(au.core, pe, re.view, &msgs);
+ for (msgs.items) |m| if (re.screen(m)) |reply| {
+ _ = try sc.take(au.core, pe, reply);
+ };
+ }
+ }.f;
+ _ = try a.core.render(arena.allocator());
+ // (A kind's prefix is its last frame's, and the tag a step's: a
+ // Shadow's is the authority's last step's.)
+ try land.step(.tick);
+ try deliver(a, &screens, peer, r);
+ const id = for (r.core().panes, 0..) |slot, i| {
+ if (slot) |pane| if (pane.addon != null) break i;
+ } else return error.NoPdfPane;
+ const shown = try r.core().render(arena.allocator());
+ var placed: usize = 0;
+ for (shown.placements.items) |pl| placed += @intFromBool(pl.pane == id);
+ try std.testing.expect(placed >= 1);
+ try std.testing.expect(std.mem.startsWith(u8, try pardes.tagline.tagPrefix(r.core(), r.core().panes[id].?), "[1/16]"));
+ // A wheel at the replica: the session's kind takes it, and the
+ // replica shows where the session's strip went.
+ const before = a.core.panes[id].?.addon.?.thumb_at;
+ const rect = r.core().view().rects[id];
+ for (0..20) |_| r.confirm(try a.take(try r.input(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + rect.w / 2, .row = rect.y + rect.h / 2 } })));
+ try jobs(a.core, land);
+ _ = try a.core.render(arena.allocator());
+ try std.testing.expect(a.core.panes[id].?.addon.?.thumb_at > before);
+ try deliver(a, &screens, peer, r);
+ r.settle();
+ try std.testing.expect(r.diverged == null);
+ }
+
+ test "a PDF pane whose file changes on disk opens again from it at its page, its fit kept" {
+ if (!addons.has_pdf) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try std.Io.Dir.cwd().copyFile("docs/design.pdf", tmp.dir, "live.pdf", std.testing.io, .{});
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)];
+ const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .tty_only = true });
+ defer p.deinit();
+ pardes.Addon.perform(p, .load, 0, pdf_lib);
+ var line: [4200]u8 = undefined;
+ try std.testing.expect(p.executeBuiltinLine(p.view().active, try std.fmt.bufPrint(&line, "Look {s}/live.pdf:5", .{dir})));
+ const id = p.view().active;
+ try std.testing.expect(p.executeBuiltinLine(id, "PdfFit height"));
+ const Self = struct {
+ core: *Pardes,
+ fn step(l: @This(), ev: pardes.Event) !void {
+ l.core.update(ev);
+ }
+ };
+ p.update(.tick);
+ try jobs(p, Self{ .core = p });
+ // Another file under its name (an outline's three pages): opened
+ // again, on the page it can still be on, as height-fitted.
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "test/pdf-fixtures/outline.pdf", p.scratch.allocator(), .unlimited) });
+ try std.testing.expect(p.reloadWatchedFile(@intCast(id), &.{}));
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ _ = try p.render(arena.allocator());
+ try std.testing.expectEqualStrings("[3/3]", p.panes[id].?.addon.?.prefix.slice());
+ var fields: [256]u8 = undefined;
+ try std.testing.expect(std.mem.indexOf(u8, pardes.Kind.ctlRead(p.panes[id].?, &fields), "fit:height") != null);
+ }
+};
+
+test {
+ _ = PdfAddon;
+}
diff --git a/test/pdf.zig b/test/pdf.zig
deleted file mode 100644
index 98e8a0ae..00000000
--- a/test/pdf.zig
+++ /dev/null
@@ -1,2246 +0,0 @@
-const std = @import("std");
-const pardes = @import("pardes");
-const panes = pardes.panes;
-const look = pardes.look;
-const pdf_impl = panes.Pdf.pdf;
-const config = pardes.config;
-const builtins = pardes.builtins;
-const layout = pardes.layout;
-
-const dump = pardes.dump;
-
-const Pardes = pardes.Pardes;
-const Builtin = builtins.registry.Builtin();
-const Key = pardes.Key;
-const Event = pardes.Event;
-const Mode = panes.Text.Mode;
-const Surface = pardes.Surface;
-const Placement = pardes.Placement;
-
-/// A placement as these cases read it: its page and revision (its key
-/// among its pane's pages), where it goes and its pixels.
-const Shown = struct {
- page: u32,
- revision: u32,
- fit: pardes.panes.Pdf.NativeFit,
- geometry: pardes.NativeGeometry,
- pixel_offset_y: f32,
- rgba: []const u8,
- iw: usize,
- ih: usize,
-};
-
-/// A frame of `p`, and its placements read so.
-fn renderShown(p: *Pardes, arena: std.mem.Allocator) ![]Shown {
- _ = try p.render(arena);
- return shownAll(p, arena);
-}
-
-/// `p`'s frame's placements, read so.
-fn shownAll(p: *Pardes, arena: std.mem.Allocator) ![]Shown {
- const s = &p.surface;
- const out = try arena.alloc(Shown, s.placements.items.len);
- for (s.placements.items, out) |place, *o| {
- const pane = p.panes[place.pane].?;
- const pv = pane.pdf.?;
- var page: u32 = 0;
- var revision: u32 = 0;
- found: {
- for (pv.rasters[0..pv.rasters_len]) |r| if (r.valid and Placement.keyOf(pane.serial, @intCast(r.page), r.revision) == place.key) {
- page = @intCast(r.page);
- revision = r.revision;
- break :found;
- };
- for (0..pv.page_count) |pg| if (Placement.keyOf(pane.serial, @intCast(pg), 0) == place.key) {
- page = @intCast(pg);
- break :found;
- };
- return error.UnknownPlacement;
- }
- var scroll: f64 = 0;
- for (s.regionList()) |r| if (r.kind == .body and r.owner == place.pane) {
- scroll = r.scroll_px;
- break;
- };
- o.* = .{
- .page = page,
- .revision = revision,
- .fit = switch (pv.fit) {
- .width => .width,
- .height => .height,
- },
- .geometry = .{ .src = place.src, .dst = place.at orelse return error.MissingPdfGeometry },
- .pixel_offset_y = -@as(f32, @floatCast(scroll - @floor(scroll))),
- .rgba = place.raster.bytes(),
- .iw = place.raster.w,
- .ih = place.raster.h,
- };
- }
- return out;
-}
-const PdfFitMode = panes.Pdf.FitMode;
-const PdfTintMode = panes.Pdf.TintMode;
-const pdf_enabled = panes.Pdf.enabled;
-const platform = pardes.platform;
-const themes = pardes.themes;
-const pdf_raster_policy = pardes.pdf_raster_policy;
-const PDF_PAGE_GAP_PX = pardes.PDF_PAGE_GAP_PX;
-const BOX_H = pardes.BOX_H;
-const sel_slot = @backingInt(config.select_button);
-const pane_tail = " " ++ config.pdf_pane_builtins_str;
-
-fn hasPdf(pane: *const pardes.Pane) bool {
- return if (comptime pdf_enabled) pane.pdf != null else false;
-}
-
-const PdfLinkTests = struct {
- const Cell = struct { col: u16, row: u16 };
-
- fn init(tmp: std.testing.TmpDir) !*Pardes {
- const bytes = try pdf_impl.testFixture(std.testing.allocator, "links.pdf");
- defer std.testing.allocator.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "links.pdf", .data = bytes });
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "target.txt", .data = "chosen file\n" });
- var dir_buf: [4096]u8 = undefined;
- const len = try tmp.dir.realPath(std.testing.io, &dir_buf);
- const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/links.pdf", .{dir_buf[0..len]});
- defer std.testing.allocator.free(path);
- const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 100, .rows = 36 });
- p.view().frontend.native_images = true;
- p.panes[0].?.pdf.?.fit = .height;
- return p;
- }
-
- fn cellAt(p: *Pardes, x: f32, y: f32) !Cell {
- const pane = p.panes[0].?;
- const rect = p.view().rects[0];
- var best: ?Cell = null;
- var distance: f32 = std.math.inf(f32);
- for (rect.y..rect.y + rect.h) |row| for (rect.x..rect.x + rect.w) |col| {
- const point = panes.Pdf.panePointAtPage(p, pane, 0, @intCast(col), @intCast(row), false) orelse continue;
- const dx = point.x - x;
- const dy = point.y - y;
- const d = dx * dx + dy * dy;
- if (d < distance) {
- distance = d;
- best = .{ .col = @intCast(col), .row = @intCast(row) };
- }
- };
- return best orelse error.LinkOutsideViewport;
- }
-
- fn textCell(p: *Pardes, text: []const u8) !Cell {
- var found = try p.panes[0].?.pdf.?.document.search(p.gpa, 0, text);
- defer found.deinit(p.gpa);
- if (found.quads.len == 0) return error.MissingLinkFixtureText;
- const q = found.quads[0].quad;
- return cellAt(p, (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4, (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4);
- }
-
- fn click(p: *Pardes, cell: Cell) void {
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = cell.col, .row = cell.row } });
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = cell.col, .row = cell.row } });
- }
-
- fn expectOpened(p: *Pardes, expected: ?[]const u8) !void {
- var count: usize = 0;
- while (p.nextEffect()) |effect| {
- if (effect == .open_link) {
- count += 1;
- try std.testing.expectEqualStrings(expected orelse return error.UnexpectedExternalOpen, effect.open_link.slice());
- }
- }
- try std.testing.expectEqual(@as(usize, if (expected != null) 1 else 0), count);
- }
-
- test "PDF links activate embedded URLs and blank internal annotations" {
- if (!pdf_enabled) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const p = try init(tmp);
- defer p.deinit();
- var frame = std.heap.ArenaAllocator.init(p.gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- while (p.nextEffect()) |_| {}
- click(p, try textCell(p, "label"));
- try expectOpened(p, "https://example.com/only");
- try std.testing.expectEqual(@as(usize, 0), p.panes[0].?.pdf.?.page);
- click(p, try cellAt(p, 0.3, 0.38));
- try expectOpened(p, null);
- try std.testing.expectEqual(@as(usize, 1), p.panes[0].?.pdf.?.page);
- }
-
- test "PDF links offer distinct visible destinations and do not duplicate the same URL" {
- if (!pdf_enabled) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const p = try init(tmp);
- defer p.deinit();
- var frame = std.heap.ArenaAllocator.init(p.gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- while (p.nextEffect()) |_| {}
- const target_cell = try textCell(p, "target.txt");
- try std.testing.expect(panes.Pdf.beginDrag(p, p.panes[0].?, target_cell.col, target_cell.row, true));
- try std.testing.expect(p.panes[0].?.pdf.?.selection != null);
- click(p, target_cell);
- try expectOpened(p, null);
- try std.testing.expect(p.panes[0].?.pdf.?.selection == null);
- const choices = for (p.panes, 0..) |slot, id| {
- if (id == 0) continue;
- if (slot) |pane| if (pane.file) |file| if (file.output != null) break pane;
- } else return error.MissingPdfLinkChoices;
- try std.testing.expect(std.mem.indexOf(u8, choices.file.?.content, "https://example.com/embedded") != null);
- try std.testing.expect(std.mem.indexOf(u8, choices.file.?.content, "target.txt") != null);
- const choices_id = for (p.panes, 0..) |slot, id| {
- if (slot == choices) break id;
- } else return error.MissingPdfLinkChoices;
- pardes.look.lookAt(p, choices_id, "https://example.com/embedded");
- try expectOpened(p, "https://example.com/embedded");
- pardes.look.lookAt(p, choices_id, "target.txt");
- try std.testing.expectEqualStrings("chosen file\n", p.panes[p.view().active].?.file.?.content);
- p.view().active = 0;
- _ = try p.render(frame.allocator());
- click(p, try textCell(p, "https://example.com/same"));
- try expectOpened(p, "https://example.com/same");
- }
-
- fn hover(p: *Pardes, cell: Cell) void {
- p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = cell.col, .row = cell.row } });
- for (0..config.look_preview_delay_frames) |_| p.update(.tick);
- }
-
- test "PDF links hover clears on leave page and reload while right drag chooses Look text" {
- if (!pdf_enabled) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const p = try init(tmp);
- defer p.deinit();
- const pane = p.panes[0].?;
- var frame = std.heap.ArenaAllocator.init(p.gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- const plain_revision = (try shownAll(p, frame.allocator()))[0].revision;
- while (p.nextEffect()) |_| {}
- const blank = try cellAt(p, 0.3, 0.38);
- hover(p, blank);
- const hovered = try p.render(frame.allocator());
- try std.testing.expectEqual(Surface.PointerShape.link, hovered.pointer_shape);
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != plain_revision);
- const highlights = panes.Pdf.highlightInput(p, 0, pane);
- try std.testing.expect(!std.meta.eql(highlights.hover_color, highlights.selection_color));
- try std.testing.expect(pane.pdf.?.selection == null);
- try expectOpened(p, null);
- p.update(.pointer_leave);
- try std.testing.expectEqual(Surface.PointerShape.arrow, (try p.render(frame.allocator())).pointer_shape);
- hover(p, blank);
- panes.Pdf.activatePage(p, pane, 1, true);
- try std.testing.expectEqual(Surface.PointerShape.arrow, (try p.render(frame.allocator())).pointer_shape);
- panes.Pdf.activatePage(p, pane, 0, true);
- _ = try p.render(frame.allocator());
- hover(p, try cellAt(p, 0.3, 0.38));
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(Surface.PointerShape.arrow, (try p.render(frame.allocator())).pointer_shape);
-
- const label = try textCell(p, "label");
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = label.col, .row = label.row } });
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .drag, .col = label.col + 3, .row = label.row } });
- try std.testing.expect(pane.pdf.?.selection != null);
- try std.testing.expect(pane.pdf.?.selection_text.len > 0);
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = label.col + 3, .row = label.row } });
- try expectOpened(p, null);
- try std.testing.expect(pane.pdf.?.selection == null);
- try std.testing.expect(pane.pdf.?.selection_text.len == 0);
- try std.testing.expect(pane.pdf.?.search_query.len > 0);
- }
-};
-
-test {
- _ = PdfLinkTests;
-}
-
-test "PDF mounted bytes own their source after the caller frees it" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- const source = try pardes.filesystem.readFile(gpa, "docs/design.pdf");
- var document = pdf_impl.Document.openBytes(source) catch |err| {
- gpa.free(source);
- return err;
- };
- @memset(source, 0);
- gpa.free(source);
- defer document.deinit();
-
- const again = try pardes.filesystem.readFile(gpa, "docs/design.pdf");
- defer gpa.free(again);
- var original = try pdf_impl.Document.openBytes(again);
- defer original.deinit();
- try std.testing.expectEqual(original.pages, document.pages);
- try std.testing.expectEqual(try original.pageSize(0), try document.pageSize(0));
- const raster = try document.render(gpa, 0, .{}, &.{});
- defer gpa.free(raster.rgba);
- try std.testing.expect(raster.rgba.len > 0);
-}
-
-test "explicit OS PDF opens and reloads keep their namespace path" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const original = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(original);
- const replacement = try pdf_impl.testFixture(gpa, "offset-rotated.pdf");
- defer gpa.free(replacement);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = original });
- var directory_buffer: [4096]u8 = undefined;
- const directory_len = try tmp.dir.realPath(std.testing.io, &directory_buffer);
- const path = try std.fmt.allocPrint(gpa, "/n/os{s}/live.pdf", .{directory_buffer[0..directory_len]});
- defer gpa.free(path);
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 24 });
- defer p.deinit();
- const pane = p.panes[0].?;
- try std.testing.expectEqualStrings(path, pane.pdf.?.path);
- try std.testing.expectEqual(@as(usize, 3), pane.pdf.?.page_count);
- var watched = false;
- while (p.nextEffect()) |effect| {
- if (effect == .watch and effect.watch.pane == 0 and effect.watch.on) watched = true;
- }
- try std.testing.expect(watched);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = replacement });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqualStrings(path, pane.pdf.?.path);
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page_count);
-}
-
-test "PDF feature gates keep argv and builtin behavior coherent" {
- const maybe_fit = std.meta.stringToEnum(Builtin, "PdfFit");
- const maybe_tint = std.meta.stringToEnum(Builtin, "PdfTint");
- const maybe_sections = std.meta.stringToEnum(Builtin, "PdfSections");
- try std.testing.expectEqual(pdf_enabled, maybe_fit != null);
- try std.testing.expectEqual(pdf_enabled, maybe_tint != null);
- try std.testing.expectEqual(pdf_enabled, maybe_sections != null);
- if (pdf_enabled) {
- try std.testing.expectEqualStrings("tz", config.leader_path.get(maybe_fit.?).?);
- try std.testing.expectEqualStrings("ti", config.leader_path.get(maybe_tint.?).?);
- try std.testing.expectEqualStrings("ts", config.leader_path.get(maybe_sections.?).?);
- } else {
- const p = try Pardes.init(std.testing.allocator, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- try std.testing.expect(pane.file != null);
- try std.testing.expect(pane.image == null);
- try std.testing.expect(!hasPdf(pane));
- }
-}
-
-test "PdfSections Look follows the exact owning PDF, not an equal path" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const fixture = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
-
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- const first = p.panes[0].?;
- // Bare normal-mode `f` on a PDF dispatches the PdfSections builtin.
- p.update(.{ .key = .{ .cp = 'f', .text = "f" } });
- const first_output_id = first.search_pane orelse return error.MissingPdfSectionsOutput;
- const first_output = p.panes[first_output_id].?;
- try std.testing.expect(panes.Pdf.isSectionsOutput(first_output));
- try std.testing.expect(first_output.file.?.content.len > 0);
-
- // A clean result is re-armed in place without rebuilding it.
- const first_revision = first_output.file.?.revision;
- panes.Pdf.openSections(p, 0);
- try std.testing.expectEqual(first_output_id, first.search_pane.?);
- try std.testing.expectEqual(first_revision, first_output.file.?.revision);
-
- const duplicate_id = p.freeSlot() orelse return error.NoDuplicatePdfSlot;
- const duplicate = try panes.Pdf.openPane(p, duplicate_id, path, 0, .last);
- pardes.exec.placeNew(p, 0, 0, duplicate_id, .doc);
- layout.compute(p);
- panes.Pdf.openSections(p, duplicate_id);
- const duplicate_output_id = duplicate.search_pane orelse return error.MissingDuplicatePdfSections;
-
- const first_row = std.mem.sliceTo(first_output.file.?.content, '\n');
- const target = first_row[0 .. std.mem.indexOfScalar(u8, first_row, ' ') orelse first_row.len];
- pardes.look.lookAt(p, first_output_id, target);
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- pardes.look.lookAt(p, duplicate_output_id, target);
- try std.testing.expectEqual(duplicate_id, p.view().active);
-
- // Once the original document is gone, its output cannot reinterpret an
- // old ordinal against the still-open equal-path duplicate.
- try std.testing.expect(pardes.test_api.runBuiltin(p, "Del", 0, "", null));
- p.view().active = first_output_id;
- pardes.look.lookAt(p, first_output_id, target);
- try std.testing.expectEqual(first_output_id, p.view().active);
-}
-
-test "SDL PDF raster policy is materially denser than Kitty" {
- try std.testing.expect(
- pardes.sdl_pdf_raster_policy.dpi >= pardes.kitty_pdf_raster_policy.dpi * 2,
- );
- try std.testing.expect(
- pardes.sdl_pdf_raster_policy.max_dimension >
- pardes.kitty_pdf_raster_policy.max_dimension * 3,
- );
- try std.testing.expect(!pardes.kitty_pdf_raster_policy.match_viewport);
- try std.testing.expect(pardes.sdl_pdf_raster_policy.match_viewport);
-}
-
-test "watched PDF reload replaces MuPDF state and preserves the reading view" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const original = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(original);
- const replacement = try pdf_impl.testFixture(gpa, "offset-rotated.pdf");
- defer gpa.free(replacement);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = original });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(
- &path_buf,
- ".zig-cache/tmp/{s}/live.pdf",
- .{tmp.sub_path},
- );
-
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- var watched = false;
- while (p.nextEffect()) |effect| switch (effect) {
- .watch => |watch| if (watch.pane == 0 and watch.on) {
- watched = true;
- },
- else => {},
- };
- try std.testing.expect(watched);
-
- const pane = p.panes[0].?;
- const state = pane.pdf.?;
- try std.testing.expectEqual(@as(usize, 3), state.page_count);
- panes.Pdf.openSections(p, 0);
- const sections_id = pane.search_pane orelse return error.MissingPdfSectionsOutput;
- const sections = p.panes[sections_id].?;
- try std.testing.expect(sections.file.?.content.len > 0);
-
- p.view().frontend.native_images = true;
- state.fit = .height;
- state.tint = .full;
- state.pan_x = 1234;
- state.pan_y = 4321;
- try state.setSearchQuery(p.pdf_gpa, "needle");
- panes.Pdf.activatePage(p, pane, 2, true);
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- state.text_scroll = 7;
- state.search_hit = 4;
- state.search_reveal_pending = false;
- const reveal_viewport_w = state.reveal_viewport_w;
- const reveal_viewport_h = state.reveal_viewport_h;
- const reveal_fit = state.reveal_fit;
- const reveal_viewport_valid = state.reveal_viewport_valid;
- const old_revision = panes.Pdf.rasterForPage(state, 2).?.revision;
- const old_revision_counter = state.next_raster_revision;
- const anchor_fraction: f64 = 0.375;
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[2])) +
- anchor_fraction * @as(f64, @floatFromInt(state.page_heights[2]));
- state.scroll_to_page_pending = false;
- state.layout_anchor_pending = false;
- pane.body.cur_row = 9;
- pane.body.cur_col = 8;
-
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = replacement });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
-
- try std.testing.expectEqual(@as(usize, 1), state.page_count);
- try std.testing.expectEqual(@as(usize, 0), state.page);
- try std.testing.expectEqual(PdfFitMode.height, state.fit);
- try std.testing.expectEqual(PdfTintMode.full, state.tint);
- try std.testing.expectEqual(@as(u16, 1234), state.pan_x);
- try std.testing.expectEqual(@as(u16, 4321), state.pan_y);
- try std.testing.expectEqual(@as(usize, 7), state.text_scroll);
- try std.testing.expect(state.text_scroll_clamp_pending);
- try std.testing.expectEqualStrings("needle", state.search_query);
- try std.testing.expectEqual(@as(usize, 4), state.search_hit);
- try std.testing.expectEqual(reveal_viewport_w, state.reveal_viewport_w);
- try std.testing.expectEqual(reveal_viewport_h, state.reveal_viewport_h);
- try std.testing.expectEqual(reveal_fit, state.reveal_fit);
- try std.testing.expectEqual(reveal_viewport_valid, state.reveal_viewport_valid);
- try std.testing.expectEqual(old_revision_counter, state.next_raster_revision);
- try std.testing.expectEqual(@as(usize, 0), state.rasters_len);
- try std.testing.expect(state.layout_anchor_pending);
- try std.testing.expectEqual(@as(usize, 2), state.layout_anchor_page);
- try std.testing.expectApproxEqAbs(anchor_fraction, state.layout_anchor_fraction, 0.0001);
- try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row);
- try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col);
- _ = state.ensureText(p.pdf_gpa);
- const text_lines = std.mem.count(u8, state.text, "\n") + 1;
- try std.testing.expect(state.text_scroll < text_lines);
- try std.testing.expect(!state.text_scroll_clamp_pending);
-
- // A clean generated outline is derived data: it refreshes in place and
- // remains the remembered output. This replacement deliberately has none.
- try std.testing.expectEqual(@as(usize, 0), sections.file.?.content.len);
- try std.testing.expectEqual(sections_id, state.sections_output.?.pane);
- try std.testing.expectEqual(sections.file.?.revision, state.sections_output.?.revision);
-
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const fresh_raster = panes.Pdf.rasterForPage(state, 0).?;
- try std.testing.expect(fresh_raster.revision != old_revision);
- try std.testing.expect(fresh_raster.revision > old_revision_counter);
- const expected_scroll = anchor_fraction *
- @as(f64, @floatFromInt(state.page_heights[0]));
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- try std.testing.expectApproxEqAbs(@min(expected_scroll, max_scroll), state.document_scroll_y, 0.001);
-
- // Reopen is transactional: malformed replacement bytes leave the last
- // good MuPDF handle and every durable setting untouched.
- const good_handle = state.document.handle;
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = "not a PDF" });
- try std.testing.expect(!p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(good_handle, state.document.handle);
- try std.testing.expectEqual(@as(usize, 1), state.page_count);
- try std.testing.expectEqualStrings("needle", state.search_query);
- try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "PDF reload") != null);
-
- // A user edit breaks the generated-revision token. A later valid reload
- // updates the document but leaves those user-owned output bytes alone.
- panes.File.setContent(p, &sections.file.?, try gpa.dupe(u8, "edited sections\n"));
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = original });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(@as(usize, 3), state.page_count);
- try std.testing.expectEqualStrings("edited sections\n", sections.file.?.content);
-
- // The watch follows the PDF payload's lifetime just like a text file's;
- // emit the stop while the slot still identifies the disappearing pane.
- try pardes.panes.deinitPane(p, pane);
- p.panes[0] = null;
- var unwatched = false;
- while (p.nextEffect()) |effect| switch (effect) {
- .watch => |watch| if (watch.pane == 0 and !watch.on) {
- unwatched = true;
- },
- else => {},
- };
- try std.testing.expect(unwatched);
-}
-
-test "PDF reload does not re-center an already revealed matching search" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- const fixture = try pardes.filesystem.readFile(gpa, "docs/design.pdf");
- defer gpa.free(fixture);
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "search.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/search.pdf", .{tmp.sub_path});
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const state = pane.pdf.?;
- try state.setSearchQuery(p.pdf_gpa, "Pardes");
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- try std.testing.expect(state.search_results != null);
- try std.testing.expect(state.search_results.?.hit_count > 0);
- try std.testing.expect(state.reveal_viewport_valid);
-
- // Reading moved on after the original reveal. A reload retains the query
- // and rebuilds its quads, but it must not mistake that for a new request to
- // jump back to the hit.
- const anchor_page = state.page;
- const anchor_fraction: f64 = 0.82;
- state.document_scroll_y = @as(f64, @floatFromInt(state.page_starts[anchor_page])) +
- anchor_fraction * @as(f64, @floatFromInt(state.page_heights[anchor_page]));
- state.scroll_to_page_pending = false;
- state.layout_anchor_pending = false;
- state.search_reveal_pending = false;
- const reveal_w = state.reveal_viewport_w;
- const reveal_h = state.reveal_viewport_h;
- const reveal_fit = state.reveal_fit;
-
- // Same semantic document on a fresh generation keeps the expected anchor
- // easy to state while still rebuilding every MuPDF-owned search object.
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "search.pdf", .data = fixture });
- try std.testing.expect(p.reloadWatchedFile(0, &.{}));
- try std.testing.expectEqual(reveal_w, state.reveal_viewport_w);
- try std.testing.expectEqual(reveal_h, state.reveal_viewport_h);
- try std.testing.expectEqual(reveal_fit, state.reveal_fit);
- try std.testing.expect(!state.search_reveal_pending);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
-
- const page = @min(anchor_page, state.page_count - 1);
- const anchored = @as(f64, @floatFromInt(state.page_starts[page])) +
- anchor_fraction * @as(f64, @floatFromInt(state.page_heights[page]));
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- const max_scroll = @as(f64, @floatFromInt(state.document_height -| viewport.pixel_h));
- try std.testing.expectApproxEqAbs(@min(anchored, max_scroll), state.document_scroll_y, 0.001);
-}
-
-test "MuPDF pane renders, navigates, searches, and round-trips its page" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- try std.testing.expect(hasPdf(pane));
- try std.testing.expect(pane.pdf.?.page_count > 1);
- try std.testing.expectEqual(PdfFitMode.width, pane.pdf.?.fit);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y);
- try std.testing.expectEqual(@as(u16, 8), p.view().cell_pixels.w);
- try std.testing.expectEqual(@as(u16, 16), p.view().cell_pixels.h);
- const initial_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane);
- const expected_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [1/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page_count, pane_tail });
- try std.testing.expectEqualStrings(expected_tag, initial_tag);
- try std.testing.expect(std.mem.endsWith(u8, initial_tag, pane_tail));
-
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- const first = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 1), first.placements.items.len);
- const first_place = (try shownAll(p, frame.allocator()))[0];
- try std.testing.expect(first_place.rgba.len == first_place.iw * first_place.ih * 4);
- try std.testing.expectEqual(pardes.panes.Pdf.NativeFit.width, first_place.fit);
- const request = panes.Pdf.renderRequest(
- panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport,
- pdf_raster_policy,
- pane.pdf.?.fit,
- );
- try std.testing.expectEqual(pdf_raster_policy.dpi, request.dpi);
- try std.testing.expectEqual(pdf_raster_policy.max_dimension, request.max_dimension);
- try std.testing.expectEqual(
- request,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.request,
- );
- try std.testing.expect(@max(first_place.iw, first_place.ih) <= request.max_dimension);
- if (pdf_raster_policy.match_viewport) {
- const viewport = panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport;
- try std.testing.expectEqual(viewport.pixel_w, request.minimum_width);
- try std.testing.expectEqual(viewport.pixel_h, request.minimum_height);
- try std.testing.expect(first_place.iw >= viewport.pixel_w or
- @max(first_place.iw, first_place.ih) == request.max_dimension);
- try std.testing.expect(first_place.ih >= viewport.pixel_h or
- @max(first_place.iw, first_place.ih) == request.max_dimension);
- } else {
- try std.testing.expectEqual(@as(u32, 0), request.minimum_width);
- try std.testing.expectEqual(@as(u32, 0), request.minimum_height);
- }
-
- // SDL's raw dy path retains fractions in the placement itself; it does
- // not leave native pixels fixed while only the underlying cells slide.
- p.update(.{ .pdf_scroll = .{ .pane = 0, .delta_pixels = 0.25, .glide = false } });
- try std.testing.expectEqual(@as(f64, 0.25), pane.pdf.?.document_scroll_y);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(first_place.revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expectEqual(@as(f32, -0.25), (try shownAll(p, frame.allocator()))[0].pixel_offset_y);
- pane.pdf.?.document_scroll_y = 0;
-
- // The default reading view moves one exact display-cell distance without
- // replacing page pixels. Document placement, not texture identity, moves.
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.page);
- try std.testing.expectEqual(@as(f64, p.view().cell_pixels.h), pane.pdf.?.document_scroll_y);
- try std.testing.expectEqual(
- first_place.revision,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(first_place.revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].geometry.src.y > first_place.geometry.src.y);
-
- const row_scroll = pane.pdf.?.document_scroll_y;
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '3' } });
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(f64, p.view().cell_pixels.h * 3), pane.pdf.?.document_scroll_y);
-
- // Counts survive a shared multi-key prefix. An invalid continuation is
- // consumed and clears both prefix and count before the following action.
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(f64, p.view().cell_pixels.h * 2), pane.pdf.?.document_scroll_y);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '4' } });
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = '?' } });
- try std.testing.expectEqual(null, pane.body.normal.prefix);
- try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count);
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y);
-
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
- const half_scroll = pane.pdf.?.document_scroll_y;
- try std.testing.expect(half_scroll > row_scroll);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'd', .ctrl = true } });
- const counted_half = pane.pdf.?.document_scroll_y;
- try std.testing.expectEqual(half_scroll * 2, counted_half);
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'u', .ctrl = true } });
- try std.testing.expectEqual(@as(f64, 0), pane.pdf.?.document_scroll_y);
- pane.pdf.?.document_scroll_y = @as(f64, p.view().cell_pixels.h) * 4;
- p.update(.{ .key = .{ .cp = '3' } });
- p.update(.{ .key = .{ .cp = 'k' } });
- try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
- try std.testing.expect(pane.pdf.?.document_scroll_y >= half_scroll);
- pane.pdf.?.document_scroll_y = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'f', .ctrl = true } });
- const key_viewport = panes.Pdf.paneViewport(p, pane).?;
- const max_key_scroll = @as(f64, @floatFromInt(pane.pdf.?.document_height -| key_viewport.pixel_h));
- const counted_full = @min(@as(f64, @floatFromInt(key_viewport.pixel_h * 2)), max_key_scroll);
- try std.testing.expectEqual(counted_full, pane.pdf.?.document_scroll_y);
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'b', .ctrl = true } });
- try std.testing.expectEqual(@max(@as(f64, 0), counted_full - @as(f64, @floatFromInt(key_viewport.pixel_h * 2))), pane.pdf.?.document_scroll_y);
- try std.testing.expectEqual(
- first_place.revision,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
-
- // At a page boundary both page rasters coexist, the gap remains uncovered,
- // and a row step crosses it without snapping either page to an edge.
- //
- // This lands by ASSIGNMENT, which is a jump and not a fling — and the
- // travel counter has to say so: the keys above scrolled two screenfuls
- // without any frame in between to spend that distance, which no shell does
- // (every wheel batch is followed by a draw). Left unspent it would make the
- // frame below the first frame of a fling and hand it bands.
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- pane.pdf.?.scroll_travel = 0;
- pane.pdf.?.document_scroll_y = @floatFromInt(
- pane.pdf.?.page_starts[1] -| viewport.pixel_h / 2,
- );
- _ = frame.reset(.retain_capacity);
- const boundary = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 2), boundary.placements.items.len);
- try std.testing.expectEqual(@as(u32, 0), (try shownAll(p, frame.allocator()))[0].page);
- try std.testing.expectEqual(@as(u32, 1), (try shownAll(p, frame.allocator()))[1].page);
- const first_bottom = @as(f32, @floatFromInt(
- (try shownAll(p, frame.allocator()))[0].geometry.dst.y +
- (try shownAll(p, frame.allocator()))[0].geometry.dst.h,
- )) + (try shownAll(p, frame.allocator()))[0].pixel_offset_y;
- const second_top = @as(f32, @floatFromInt(
- (try shownAll(p, frame.allocator()))[1].geometry.dst.y,
- )) + (try shownAll(p, frame.allocator()))[1].pixel_offset_y;
- const visible_gap = second_top - first_bottom;
- try std.testing.expect(visible_gap >= @as(f32, PDF_PAGE_GAP_PX));
- try std.testing.expect(visible_gap <= @as(f32, PDF_PAGE_GAP_PX + 1));
- const before_boundary_scroll = pane.pdf.?.document_scroll_y;
- const page0_revision = (try shownAll(p, frame.allocator()))[0].revision;
- const page1_revision = (try shownAll(p, frame.allocator()))[1].revision;
-
- // A scroll can activate the already-cached neighbor before the shell's
- // next draw. Every consumer resolves the active page's resident raster,
- // so a queued click cannot accidentally use page zero's dimensions.
- pane.pdf.?.document_scroll_y = @as(f64, @floatFromInt(pane.pdf.?.page_starts[1])) - 0.5;
- try std.testing.expectEqual(
- page0_revision,
- panes.Pdf.rasterForPage(pane.pdf.?, 0).?.revision,
- );
- try std.testing.expect(panes.Pdf.scrollPane(p, pane, 1, false));
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page);
- try std.testing.expectEqual(
- page1_revision,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
- panes.Pdf.activatePage(p, pane, 0, false);
- pane.pdf.?.document_scroll_y = before_boundary_scroll;
-
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(before_boundary_scroll + p.view().cell_pixels.h, pane.pdf.?.document_scroll_y);
- _ = frame.reset(.retain_capacity);
- const second = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 2), second.placements.items.len);
- try std.testing.expectEqual(page0_revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expectEqual(page1_revision, (try shownAll(p, frame.allocator()))[1].revision);
- p.update(.{ .key = .{ .cp = 'k' } });
- try std.testing.expectEqual(before_boundary_scroll, pane.pdf.?.document_scroll_y);
-
- // Once page zero is wholly outside the viewport, both its owned RGBA and
- // backend placement disappear; returning later renders a new raster. What
- // does NOT go back is the memory: the departing page's bytes are parked in
- // the relay and the arriving page of the same size takes them, so a fling
- // never asks the allocator (or the kernel's fault handler) for megabytes it
- // just gave up.
- panes.Pdf.activatePage(p, pane, 1, true);
- _ = frame.reset(.retain_capacity);
- const away = try p.render(frame.allocator());
- try std.testing.expect(away.placements.items.len > 0);
- for (try shownAll(p, frame.allocator())) |place|
- try std.testing.expect(place.page != 0);
- try std.testing.expect(panes.Pdf.rasterForPage(pane.pdf.?, 0) == null);
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.spare_len);
- const retired = pane.pdf.?.spare[0];
- panes.Pdf.activatePage(p, pane, 0, true);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(u32, 0), (try shownAll(p, frame.allocator()))[0].page);
- try std.testing.expectEqual(retired.ptr, (try shownAll(p, frame.allocator()))[0].rgba.ptr);
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != page0_revision);
-
- // PdfFit exists as a real builtin in this build. It resets placement but
- // preserves the current page pixels; fit-height j/k remains continuous in
- // the same document-pixel coordinate space.
- const fit_builtin = std.meta.stringToEnum(Builtin, "PdfFit") orelse
- return error.MissingPdfFitBuiltin;
- const revision_before_toggle = panes.Pdf.rasterForPage(
- pane.pdf.?,
- pane.pdf.?.page,
- ).?.revision;
- try std.testing.expect(pardes.test_api.runBuiltin(
- p,
- @tagName(fit_builtin),
- 0,
- "",
- null,
- ));
- try std.testing.expectEqual(PdfFitMode.height, pane.pdf.?.fit);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y);
- try std.testing.expectEqual(
- revision_before_toggle,
- panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?.revision,
- );
- const height_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane);
- const expected_height_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [{d}/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page + 1, pane.pdf.?.page_count, pane_tail });
- try std.testing.expectEqualStrings(expected_height_tag, height_tag);
- for (p.panes) |slot| {
- const other = slot orelse continue;
- if (hasPdf(other)) continue;
- panes.Pdf.toggleFit(other); // pane-scoped and deliberately inert here
- try std.testing.expectEqual(PdfFitMode.height, pane.pdf.?.fit);
- break;
- }
-
- // A fit-height landscape page exposes horizontal overflow to a horizontal
- // wheel without rerasterizing. Use synthetic dimensions only for the
- // geometry check; no frame is drawn while they differ from the buffer.
- const active_raster = panes.Pdf.rasterForPage(pane.pdf.?, pane.pdf.?.page).?;
- const saved_iw = active_raster.iw;
- const saved_ih = active_raster.ih;
- active_raster.iw = 2000;
- active_raster.ih = 500;
- panes.Pdf.horizontalWheel(p, pane, 1);
- try std.testing.expect(pane.pdf.?.pan_x > 0);
- try std.testing.expectEqual(revision_before_toggle, active_raster.revision);
- pane.pdf.?.pan_x = 0;
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'l' } });
- try std.testing.expect(pane.pdf.?.pan_x > 0);
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'l' } });
- try std.testing.expectEqual(std.math.maxInt(u16), pane.pdf.?.pan_x);
- p.update(.{ .key = .{ .cp = '2' } });
- p.update(.{ .key = .{ .cp = 'h' } });
- try std.testing.expect(pane.pdf.?.pan_x < std.math.maxInt(u16));
- p.update(.{ .key = .{ .cp = '0' } });
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'l' } });
- try std.testing.expectEqual(std.math.maxInt(u16), pane.pdf.?.pan_x);
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'h' } });
- try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_x);
- active_raster.iw = saved_iw;
- active_raster.ih = saved_ih;
- pane.pdf.?.pan_x = 0;
-
- const before_height_scroll = pane.pdf.?.document_scroll_y;
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expect(pane.pdf.?.document_scroll_y > before_height_scroll);
-
- const revision_before_search = active_raster.revision;
- _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true);
- try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query);
- try std.testing.expectEqual(revision_before_search, active_raster.revision);
- const results_id = pane.search_pane orelse return error.MissingPdfSearchResults;
- const results = p.panes[results_id].?.file.?.content;
- try std.testing.expect(std.mem.indexOf(u8, results, "design.pdf:") != null);
- // n SELECTS the first result row and opens nothing: the walk's only list
- // here is the unlooked +Search buffer, so focus lands THERE. Enter is what
- // jumps, and the document query survives both.
- p.update(.{ .key = .{ .cp = 'n' } });
- try std.testing.expectEqual(results_id, p.view().active);
- const results_pane = p.panes[results_id].?;
- try std.testing.expect(results_pane.body.vsel.active and results_pane.body.vsel.explicit);
- try std.testing.expectEqual(@as(i32, 0), results_pane.body.cur_row);
- try std.testing.expectEqual(@as(i32, 0), results_pane.body.cur_col);
- p.update(.{ .key = .{ .cp = Key.enter } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query);
-
- // Search state is owned and untruncated, and changing pages invalidates
- // only page-local state while retaining the document query.
- const long_query = "a query deliberately longer than any tag display budget: " ++
- "012345678901234567890123456789012345678901234567890123456789" ++
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
- try pane.pdf.?.setSearchQuery(p.pdf_gpa, long_query);
- try std.testing.expectEqualStrings(long_query, pane.pdf.?.search_query);
- const next_page = if (pane.pdf.?.page == 0) @as(usize, 1) else 0;
- panes.Pdf.activatePage(p, pane, next_page, true);
- try std.testing.expectEqualStrings(long_query, pane.pdf.?.search_query);
-
- // PDF dumps keep the image-compatible schema: page/path, the exact
- // editable tail, and the pane's fit and tint (pdf_fit, pdf_tint).
- panes.Pdf.toggleTint(pane);
- try std.testing.expectEqual(PdfTintMode.full, pane.pdf.?.tint);
- pane.pdf.?.fit = .height;
- const custom_tail = " Keep Del";
- if (pane.tag.own) |own| p.gpa.free(own);
- pane.tag.own = try p.gpa.dupe(u8, custom_tail);
- try pardes.dump.dumpState(p);
- const restored = try pardes.dump.initFromDump(gpa, .{}, p.dump_out.?);
- defer restored.deinit();
- try std.testing.expect(hasPdf(restored.panes[0].?));
- try std.testing.expectEqual(pane.pdf.?.page, restored.panes[0].?.pdf.?.page);
- try std.testing.expectEqual(PdfFitMode.height, restored.panes[0].?.pdf.?.fit);
- try std.testing.expectEqual(PdfTintMode.full, restored.panes[0].?.pdf.?.tint);
- const restored_pane = restored.panes[0].?;
- try std.testing.expect(restored_pane.tag.own != null);
- try std.testing.expectEqualStrings(
- custom_tail,
- restored_pane.tag.own.?,
- );
-}
-
-test "a fling's banded pages show the reader exactly what whole pages would" {
- if (!pdf_enabled) return;
-
- // The contract fast scrolling is allowed to change: HOW pixels are carried
- // (a strip of a page instead of the page) but never WHICH pixels arrive. So
- // the same frame is drawn twice — once at fling speed, once at reading
- // speed — and every pixel inside every source rectangle must match, along
- // with where on screen it goes.
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{ .file = "docs/design.pdf", .cols = 120, .rows = 40 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
-
- const viewport = panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport;
- // Land mid-page-boundary so the frame carries TWO pages, each showing a
- // fraction of itself — the shape a fling actually produces.
- const landing = @as(f64, @floatFromInt(pv.page_starts[1] -| viewport.pixel_h / 3));
- const Shot = struct {
- page: u32,
- dst: pardes.RectPx,
- pixels: []u8,
- };
- var shots: [8]Shot = undefined;
- var shots_len: usize = 0;
- defer for (shots[0..shots_len]) |shot| gpa.free(shot.pixels);
-
- // A fling: one frame's worth of wheel travel carrying the viewport more
- // than a screenful, delivered through the real scroll path so the distance
- // is counted the way a wheel batch counts it.
- pv.document_scroll_y = 0;
- pv.scroll_travel = 0;
- try std.testing.expect(panes.Pdf.scrollPane(p, pane, landing, false));
- _ = frame.reset(.retain_capacity);
- const flung = try p.render(frame.allocator());
- try std.testing.expect(flung.placements.items.len >= 2);
- var banded = false;
- for (try shownAll(p, frame.allocator())) |place| {
- const geometry = place.geometry;
- const raster = panes.Pdf.rasterForPage(pv, place.page) orelse
- return error.MissingPdfRaster;
- if (raster.band_h < raster.ih) banded = true;
- try std.testing.expectEqual(place.iw * raster.band_h * 4, place.rgba.len);
- shots[shots_len] = .{
- .page = place.page,
- .dst = geometry.dst,
- .pixels = try copySourceRect(gpa, place, geometry.src),
- };
- shots_len += 1;
- }
- // ...and it really did band, or the comparison below is two identical
- // whole-page renders agreeing with each other.
- try std.testing.expect(banded);
- // ...at reading speed: no travel at all since the frame above, so every
- // page is rasterized whole again, and that is the picture the banded frame
- // has to have matched.
- _ = frame.reset(.retain_capacity);
- const rested = try p.render(frame.allocator());
- try std.testing.expectEqual(shots_len, rested.placements.items.len);
- for (try shownAll(p, frame.allocator()), shots[0..shots_len]) |place, shot| {
- const geometry = place.geometry;
- const raster = panes.Pdf.rasterForPage(pv, place.page) orelse
- return error.MissingPdfRaster;
- try std.testing.expectEqual(raster.ih, raster.band_h); // promoted at rest
- try std.testing.expectEqual(shot.page, place.page);
- try std.testing.expectEqual(shot.dst.x, geometry.dst.x);
- try std.testing.expectEqual(shot.dst.y, geometry.dst.y);
- try std.testing.expectEqual(shot.dst.w, geometry.dst.w);
- try std.testing.expectEqual(shot.dst.h, geometry.dst.h);
- const whole = try copySourceRect(gpa, place, geometry.src);
- defer gpa.free(whole);
- try std.testing.expectEqualSlices(u8, shot.pixels, whole);
- }
-}
-
-/// MuPDF clips the edges of a path to the pixmap, and an edge that crosses a
-/// band's clip is stepped from a different start: along its whole length in
-/// the band, its antialiased pixels can be a level or two off the whole
-/// page's. Never more.
-const band_tolerance: u8 = 4;
-
-fn expectNearRows(expected: []const u8, got: []const u8) !void {
- try std.testing.expectEqual(expected.len, got.len);
- var worst: u8 = 0;
- for (expected, got) |a, b| worst = @max(worst, if (a > b) a - b else b - a);
- if (worst > band_tolerance) {
- std.debug.print("band rows are {d} levels off the whole page's\n", .{worst});
- return error.TestExpectedEqual;
- }
-}
-
-test "a tall page is drawn at the display's resolution, in bands that are the whole page's rows" {
- if (!pdf_enabled) return;
-
- // The page is fifteen A4 heights tall. Squeezed whole into the raster
- // budget it was a third as wide as the pane and blown up, blurred; it is
- // drawn instead at the pane's own resolution, a band around the screen at
- // a time, and every band row must be the row a whole-page render makes
- // (to `band_tolerance`), and the same row however it was scrolled to.
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try pdf_impl.testFixture(gpa, "tall.pdf");
- defer gpa.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "tall.pdf", .data = bytes });
- var dir_buf: [4096]u8 = undefined;
- const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf);
- const path = try std.fmt.allocPrint(gpa, "{s}/tall.pdf", .{dir_buf[0..dir_len]});
- defer gpa.free(path);
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 120, .rows = 40 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
-
- const viewport = panes.Pdf.paneViewport(p, pane) orelse return error.MissingPdfViewport;
- const request = panes.Pdf.renderRequest(viewport, pdf_raster_policy, pv.fit);
- const shape = try pv.document.measureRenderAt(0, request);
- if (pdf_raster_policy.match_viewport) {
- // The rendered scale IS the screen's: one raster pixel per pixel of
- // the pane's width, so nothing is scaled up.
- try std.testing.expectEqual(@as(usize, viewport.pixel_w), shape.width);
- } else {
- // Kitty's policy is a dpi, kept low for the wire; the tall page gets
- // it as every other page does, not a quarter of it.
- try std.testing.expectEqual(
- @as(usize, @intFromFloat(pdf_impl.tall_test_page.width)) * pdf_raster_policy.dpi / 72,
- shape.width,
- );
- }
- try std.testing.expect(panes.Pdf.isBanded(shape));
-
- // The reference: the whole page in one render, before highlights and
- // tint, and tinted as the pane tints.
- const plain = try gpa.alloc(u8, shape.len);
- defer gpa.free(plain);
- try pv.document.renderIntoAtWithPaper(0, request, shape, shape.wholePage(), &.{}, plain, false);
- const whole = try gpa.dupe(u8, plain);
- defer gpa.free(whole);
- try pdf_impl.tintRgba(whole, pv.tint, panes.Pdf.tintColors(p));
-
- const max_scroll = @as(f64, @floatFromInt(pv.document_height - viewport.pixel_h));
- var middle: []u8 = &.{};
- defer gpa.free(middle);
- var middle_y: usize = 0;
- for ([_]f64{ 0, @round(max_scroll / 2), max_scroll }, 0..) |at, step| {
- _ = panes.Pdf.scrollPane(p, pane, at - pv.document_scroll_y, false);
- pv.scroll_travel = 0; // read, not flung
- _ = frame.reset(.retain_capacity);
- const surface = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 1), surface.placements.items.len);
- const place = (try shownAll(p, frame.allocator()))[0];
- const geometry = place.geometry;
- const raster = panes.Pdf.rasterForPage(pv, 0) orelse return error.MissingPdfRaster;
- // Bounded: a band, never the page, and within one buffer's budget.
- try std.testing.expectEqual(shape.width, place.iw);
- try std.testing.expect(raster.band_h < raster.ih);
- try std.testing.expect(place.rgba.len <= pdf_impl.max_owned_raster_bytes);
- // Prefetched: a screenful beyond what is shown, both ways, where the
- // page goes on.
- const seen_top = raster.band_y + geometry.src.y;
- const seen_end = seen_top + geometry.src.h;
- try std.testing.expect(raster.band_y <= seen_top -| geometry.src.h);
- try std.testing.expect(raster.band_y + raster.band_h >= @min(raster.ih, seen_end + geometry.src.h));
- // ...and every row of the band is the whole page's row.
- const stride = shape.stride;
- try expectNearRows(whole[raster.band_y * stride ..][0 .. raster.band_h * stride], place.rgba);
- if (step == 1) {
- middle = try gpa.dupe(u8, place.rgba);
- middle_y = raster.band_y;
- }
- }
-
- // Straight back to the middle from the foot: the rows rendered afresh
- // are the very rows rendered on the way down, so no seam moves with the
- // path a reader took.
- _ = panes.Pdf.scrollPane(p, pane, @round(max_scroll / 2) - pv.document_scroll_y, false);
- pv.scroll_travel = 0;
- _ = frame.reset(.retain_capacity);
- const again = (try renderShown(p, frame.allocator()))[0];
- const again_y = panes.Pdf.rasterForPage(pv, 0).?.band_y;
- const stride = shape.stride;
- const common_top = @max(middle_y, again_y);
- const common_end = @min(middle_y + middle.len / stride, again_y + again.rgba.len / stride);
- try std.testing.expect(common_end > common_top);
- try std.testing.expectEqualSlices(
- u8,
- middle[(common_top - middle_y) * stride .. (common_end - middle_y) * stride],
- again.rgba[(common_top - again_y) * stride .. (common_end - again_y) * stride],
- );
- _ = panes.Pdf.scrollPane(p, pane, max_scroll - pv.document_scroll_y, false);
- pv.scroll_travel = 0;
- _ = frame.reset(.retain_capacity);
- const foot = try gpa.dupe(u8, (try renderShown(p, frame.allocator()))[0].rgba);
- defer gpa.free(foot);
-
- // At the foot of the page, a search hit: its highlight lands on exactly
- // the rows and pixels it would on the whole page, and a pointer over the
- // word finds the word.
- try pv.setSearchQuery(gpa, "bottommost");
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const place = (try shownAll(p, frame.allocator()))[0];
- const raster = panes.Pdf.rasterForPage(pv, 0) orelse return error.MissingPdfRaster;
- const highlights = try panes.Pdf.buildHighlights(pv, frame.allocator(), panes.Pdf.highlightInput(p, 0, pane));
- const marks = highlights.forPage(0);
- try std.testing.expect(marks.len > 0);
- const rows = try pv.document.highlightRows(0, request, marks);
- try std.testing.expect(rows.start >= raster.band_y and rows.end <= raster.band_y + raster.band_h);
- // Exactly the highlight's rows changed, and nothing else...
- try std.testing.expectEqual(foot.len, place.rgba.len);
- const from = (rows.start - raster.band_y) * stride;
- const to = (rows.end - raster.band_y) * stride;
- try std.testing.expectEqualSlices(u8, foot[0..from], place.rgba[0..from]);
- try std.testing.expectEqualSlices(u8, foot[to..], place.rgba[to..]);
- try std.testing.expect(!std.mem.eql(u8, foot[from..to], place.rgba[from..to]));
- // ...to what the whole page painted with them is.
- const expected = try gpa.dupe(u8, plain[rows.start * stride .. rows.end * stride]);
- defer gpa.free(expected);
- try pv.document.paintHighlightsAt(0, request, shape, shape.band(rows.start, rows.end - rows.start), marks, expected);
- try pdf_impl.tintRgba(expected, pv.tint, panes.Pdf.tintColors(p));
- try expectNearRows(expected, place.rgba[from..to]);
-
- const quad = pv.search_results.?.quads[0].quad;
- const left = @min(quad.ul.x, quad.ll.x);
- const right = @max(quad.ur.x, quad.lr.x);
- const top = @min(quad.ul.y, quad.ur.y);
- const bottom = @max(quad.ll.y, quad.lr.y);
- const rect = p.view().rects[0];
- var inside: usize = 0;
- for (rect.y..rect.y + rect.h) |row| for (rect.x..rect.x + rect.w) |col| {
- const point = panes.Pdf.panePointAtPage(p, pane, 0, @intCast(col), @intCast(row), false) orelse continue;
- if (point.x >= left and point.x <= right and point.y >= top and point.y <= bottom) inside += 1;
- };
- try std.testing.expect(inside > 0);
-}
-
-/// The pixels a backend samples out of one placement: the source rectangle,
-/// row by row, at the texture's own stride. Test-only, and the one operation
-/// that makes "same picture" mean something when the textures differ in shape.
-fn copySourceRect(
- gpa: std.mem.Allocator,
- place: Shown,
- src: pardes.RectPx,
-) ![]u8 {
- const stride = place.iw * 4;
- const row_len = @as(usize, src.w) * 4;
- const out = try gpa.alloc(u8, row_len * src.h);
- errdefer gpa.free(out);
- var row: usize = 0;
- while (row < src.h) : (row += 1) {
- const from = (@as(usize, src.y) + row) * stride + @as(usize, src.x) * 4;
- @memcpy(out[row * row_len ..][0..row_len], place.rgba[from..][0..row_len]);
- }
- return out;
-}
-
-test "Escape cancels PDF chrome in place, then leaves the pane; Shift-Escape leaves at once" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 28,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
-
- // A second pane, then focus it and come back: `Last` has somewhere to go
- // and the PDF is where the keys land.
- panes.Pdf.openSections(p, 0);
- p.update(.{ .key = .{ .cp = 'w', .ctrl = true } });
- p.update(.{ .key = .{ .cp = 'j' } });
- p.update(.{ .key = .{ .cp = Key.enter } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- p.update(.{ .key = .{ .cp = 'w', .ctrl = true } });
- p.update(.{ .key = .{ .cp = 'k' } });
- p.update(.{ .key = .{ .cp = Key.enter } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
-
- // Everything a reader can see over the page: a search overlay and a live
- // word selection.
- try pv.setSearchQuery(p.pdf_gpa, "Pardes");
- var found = try pv.document.search(gpa, pv.page, "Pardes");
- defer found.deinit(gpa);
- try std.testing.expect(found.quads.len > 0);
- const quad = found.quads[0].quad;
- try std.testing.expectEqual(
- panes.Pdf.SelectionUpdate.changed,
- pv.setSelection(p.pdf_gpa, quad.ul, quad.lr, false),
- );
- p.update(.{ .key = .{ .cp = '3' } });
- const page_before = pv.page;
- const scroll_before = pv.document_scroll_y;
-
- // Escape drops the overlay and the selection, keeps the reading position,
- // and does NOT hand the keyboard to another pane.
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try std.testing.expect(pv.selection == null and pv.selection_text.len == 0);
- try std.testing.expectEqual(@as(usize, 0), pv.search_query.len);
- try std.testing.expect(pv.search_results == null);
- try std.testing.expect(!pv.highlights_dirty and !pv.search_reveal_pending);
- try std.testing.expectEqual(page_before, pv.page);
- try std.testing.expectEqual(scroll_before, pv.document_scroll_y);
- try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count);
- try std.testing.expectEqual(null, pane.body.normal.prefix);
- // With nothing left to drop, Escape goes back a pane as anywhere else,
- // and leaves the document as it found it.
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- try std.testing.expectEqual(page_before, pv.page);
- try std.testing.expectEqual(scroll_before, pv.document_scroll_y);
-
- // Shift-Escape goes at once, over a selection too.
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try std.testing.expectEqual(
- panes.Pdf.SelectionUpdate.changed,
- pv.setSelection(p.pdf_gpa, quad.ul, quad.lr, false),
- );
- p.update(.{ .key = .{ .cp = Key.escape, .shift = true } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- try std.testing.expect(pv.selection != null);
-
- // A text-only page shows neither: one Escape drops them and goes.
- p.view().frontend.native_images = false;
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 0), p.view().active);
- try pv.setSearchQuery(p.pdf_gpa, "Pardes");
- p.update(.{ .key = .{ .cp = Key.escape } });
- try std.testing.expectEqual(@as(usize, 1), p.view().active);
- try std.testing.expect(pv.selection == null and pv.search_query.len == 0);
-}
-
-test "PDF continuous strip renders every intersecting short page" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- try std.testing.expect(pv.page_count > 3);
- p.view().frontend.native_images = true;
-
- // A legal wide MediaBox can make more than three pages intersect one
- // viewport. Seed tiny matching rasters so this tests transport/cache
- // cardinality without spending the unit test rendering fake page sizes.
- for (pv.page_sizes) |*size| size.* = .{ .width = 100_000, .height = 1 };
- pv.layout_valid = false;
- pv.scroll_to_page_pending = true;
- const viewport = panes.Pdf.ensurePaneLayout(p, pane).?;
- const visible = panes.Pdf.visiblePages(pv, viewport);
- try std.testing.expectEqual(pv.page_count, visible.len);
- const request = panes.Pdf.renderRequest(viewport, pdf_raster_policy, pv.fit);
- try std.testing.expect(pv.page_count <= pv.rasters.len);
- for (0..pv.page_count) |page| {
- const rgba = try gpa.alloc(u8, @as(usize, viewport.pixel_w) * 4);
- @memset(rgba, @intCast(page));
- pv.rasters[pv.rasters_len] = .{
- .valid = true,
- .page = page,
- .rgba = rgba,
- .iw = viewport.pixel_w,
- .ih = 1,
- .request = request,
- .request_valid = true,
- .tried = true,
- .tint_key = .{ .mode = pv.tint, .colors = panes.Pdf.tintColors(p) },
- .revision = @intCast(page + 1),
- };
- pv.rasters_len += 1;
- }
-
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- const surface = try p.render(frame.allocator());
- try std.testing.expectEqual(pv.page_count, surface.placements.items.len);
- try std.testing.expectEqual(pv.page_count, pv.rasters_len);
- for (try shownAll(p, frame.allocator()), 0..) |place, page| {
- try std.testing.expectEqual(@as(u32, @intCast(page)), place.page);
- try std.testing.expectEqual(@as(u32, 1), place.geometry.dst.h);
- }
-}
-
-test "PDF tint resolves a theme's null page colors to its chrome" {
- if (!pdf_enabled) return;
-
- const p = try Pardes.init(std.testing.allocator, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- // `dark` intentionally leaves page bg/fg null. PDF tint resolves those
- // deterministically to its chrome colors rather than host defaults.
- const dark_index = for (themes, 0..) |th, i| {
- if (std.mem.eql(u8, th.name, "dark")) break i;
- } else return error.MissingDarkTheme;
- pardes.colors.setThemeIndex(p, dark_index);
- const colors = panes.Pdf.tintColors(p);
- try std.testing.expectEqual(p.theme().tag_bg, colors.background);
- try std.testing.expectEqual(p.theme().tag_fg, colors.foreground);
-}
-
-test "PDF tint and tinted theme changes rebuild every visible raster only" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- _ = try p.render(frame.allocator());
- const viewport = panes.Pdf.paneViewport(p, pane).?;
- pv.document_scroll_y = @floatFromInt(pv.page_starts[1] -| viewport.pixel_h / 2);
- _ = frame.reset(.retain_capacity);
- const default_surface = try p.render(frame.allocator());
- try std.testing.expectEqual(PdfTintMode.filtered, pv.tint);
- try std.testing.expectEqual(@as(usize, 2), default_surface.placements.items.len);
- try std.testing.expectEqual(@as(usize, 2), pv.rasters_len);
-
- const Snapshot = struct {
- page: u32,
- revision: u32,
- geometry: pardes.NativeGeometry,
- pixel_offset_y: f32,
- iw: usize,
- ih: usize,
- checksum: u64,
- };
- const Capture = struct {
- fn get(core: *Pardes, arena: std.mem.Allocator) ![2]Snapshot {
- if (core.surface.placements.items.len != 2) return error.UnexpectedVisiblePdfCount;
- var out: [2]Snapshot = undefined;
- const shown = try shownAll(core, arena);
- for (&out, 0..) |*snapshot, i| {
- const place = shown[i];
- snapshot.* = .{
- .page = place.page,
- .revision = place.revision,
- .geometry = place.geometry,
- .pixel_offset_y = place.pixel_offset_y,
- .iw = place.iw,
- .ih = place.ih,
- .checksum = std.hash.Wyhash.hash(0x5044_4654_494e_5421, place.rgba),
- };
- }
- return out;
- }
-
- fn expectGeometry(before: [2]Snapshot, after: [2]Snapshot) !void {
- for (before, after) |old, new| {
- try std.testing.expectEqual(old.page, new.page);
- try std.testing.expectEqual(old.geometry, new.geometry);
- try std.testing.expectEqual(old.pixel_offset_y, new.pixel_offset_y);
- try std.testing.expectEqual(old.iw, new.iw);
- try std.testing.expectEqual(old.ih, new.ih);
- }
- }
- };
- const default_filtered = try Capture.get(p, frame.allocator());
- for (pv.rasters[0..pv.rasters_len]) |raster|
- try std.testing.expectEqual(PdfTintMode.filtered, raster.tint_key.?.mode);
-
- const dark_index = for (themes, 0..) |th, i| {
- if (std.mem.eql(u8, th.name, "dark")) break i;
- } else return error.MissingDarkTheme;
- pardes.colors.setThemeIndex(p, dark_index);
- for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(!raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const themed = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(default_filtered, themed);
- for (default_filtered, themed) |old, new| {
- try std.testing.expect(new.revision > old.revision);
- try std.testing.expect(new.checksum != old.checksum);
- }
-
- panes.Pdf.toggleTint(pane);
- try std.testing.expectEqual(PdfTintMode.full, pv.tint);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const full = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(themed, full);
- for (themed, full) |old, new| {
- try std.testing.expect(new.revision > old.revision);
- }
- for (pv.rasters[0..pv.rasters_len]) |raster|
- try std.testing.expectEqual(PdfTintMode.full, raster.tint_key.?.mode);
-
- panes.Pdf.toggleTint(pane);
- try std.testing.expectEqual(PdfTintMode.disabled, pv.tint);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const disabled = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(full, disabled);
- for (full, disabled) |old, source| {
- try std.testing.expect(source.revision > old.revision);
- try std.testing.expect(source.checksum != old.checksum);
- }
-
- const acme_index = for (themes, 0..) |th, i| {
- if (std.mem.eql(u8, th.name, "acme")) break i;
- } else return error.MissingAcmeTheme;
- for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(raster.tried);
- pardes.colors.setThemeIndex(p, acme_index);
- // Disabled keys ignore theme colors, so neither explicit invalidation nor
- // the per-raster key comparison asks MuPDF for replacement pixels.
- for (pv.rasters[0..pv.rasters_len]) |raster| try std.testing.expect(raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const unchanged = try Capture.get(p, frame.allocator());
- try Capture.expectGeometry(disabled, unchanged);
- for (disabled, unchanged) |old, new| {
- try std.testing.expectEqual(old.revision, new.revision);
- try std.testing.expectEqual(old.checksum, new.checksum);
- }
- try std.testing.expectEqual(@as(usize, 2), pv.rasters_len);
-}
-
-test "PDF resize preserves page-relative document position" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- panes.Pdf.activatePage(p, pane, 1, true);
- _ = try p.render(frame.allocator());
- const fraction: f64 = 0.375;
- pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[1])) +
- fraction * @as(f64, @floatFromInt(pv.page_heights[1]));
- p.update(.{ .resize = .{
- .cols = 100,
- .rows = 24,
- .cell_pixels = p.view().cell_pixels,
- } });
- try std.testing.expect(!pv.layout_valid);
- try std.testing.expect(pv.layout_anchor_pending);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const resized_fraction = (pv.document_scroll_y -
- @as(f64, @floatFromInt(pv.page_starts[1]))) /
- @as(f64, @floatFromInt(pv.page_heights[1]));
- try std.testing.expectApproxEqAbs(fraction, resized_fraction, 0.000_001);
- try std.testing.expectEqual(@as(usize, 1), pv.page);
-
- const held = pv.document_scroll_y;
- p.update(.{ .resize = .{
- .cols = 100,
- .rows = 24,
- .cell_pixels = p.view().cell_pixels,
- } });
- try std.testing.expectEqual(held, pv.document_scroll_y);
- try std.testing.expect(pv.layout_valid);
-}
-
-test "PDF pane geometry change preserves its page-relative position" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- // A FILE boot is one pane now and a lone column always fills the window,
- // so the divider drag below needs a second column to take the width from.
- _ = try p.newShell(1, "");
- _ = layout.splitColumn(p, 0, 1, false);
- p.sync(); // rects for the new column, exactly as the two-pane boot did
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- panes.Pdf.activatePage(p, pane, 1, true);
- _ = try p.render(frame.allocator());
- const fraction: f64 = 0.625;
- pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[1])) +
- fraction * @as(f64, @floatFromInt(pv.page_heights[1]));
- const old_width = pv.layout_viewport_w;
-
- // A divider/split changes rects through computeGeom without emitting a
- // shell resize. panes.Pdf.ensurePaneLayout anchors against the old layout
- // before rebuilding it for this wider pane.
- const sibling_weight = p.view().cols[1].weight;
- p.view().cols[0].weight = sibling_weight * 6;
- layout.compute(p);
- try std.testing.expect(panes.Pdf.paneViewport(p, pane).?.pixel_w != old_width);
- try std.testing.expect(pv.layout_valid);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const changed_fraction = (pv.document_scroll_y -
- @as(f64, @floatFromInt(pv.page_starts[1]))) /
- @as(f64, @floatFromInt(pv.page_heights[1]));
- try std.testing.expectApproxEqAbs(fraction, changed_fraction, 0.000_001);
- try std.testing.expectEqual(@as(usize, 1), pv.page);
-
- // An explicit pending reveal wins over an implicit layout anchor.
- pv.page = 2;
- pv.scroll_to_page_pending = true;
- p.view().cols[0].weight = sibling_weight * 2;
- layout.compute(p);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- @as(f64, @floatFromInt(pv.page_starts[2])),
- pv.document_scroll_y,
- );
-}
-
-test "PDF n/N addresses and reveals distinct MuPDF hits on one page" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 120,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- const pv = pane.pdf.?;
- p.view().frontend.native_images = true;
-
- var page_hits = try pv.document.search(gpa, 0, "Pardes");
- defer page_hits.deinit(gpa);
- try std.testing.expect(page_hits.hit_count >= 3);
-
- p.locations_config.context = 2;
- p.locations_config.tscontext = true;
- _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true);
- const results_id = pane.search_pane orelse return error.MissingPdfSearchResults;
- const results = p.panes[results_id].?.file.?;
- var found: [3]bool = @splat(false);
- for (results.location_rows, 0..) |row, index| {
- // PDF locations address page/hit pairs, not binary file lines. Each
- // address owns one snippet, which must not add a navigation stop.
- if (index % 2 == 1) {
- try std.testing.expectEqual(.preview, row.kind);
- try std.testing.expectEqual(results.location_rows[index - 1].at, row.at);
- try std.testing.expectEqual(@as(usize, 0), row.code_start);
- try std.testing.expectEqualStrings("Pardes", pardes.modal.lineSlice(results.content, index));
- continue;
- }
- try std.testing.expectEqual(.match, row.kind);
- const line = pardes.modal.lineSlice(results.content, index);
- try std.testing.expectEqual(line.len, row.code_start);
- if (!std.mem.endsWith(u8, row.path, "design.pdf") or row.at.line != 1) continue;
- if (row.at.col < 1 or row.at.col > found.len) continue;
- found[row.at.col - 1] = true;
- }
- for (found) |present| try std.testing.expect(present);
-
- // Exaggerate the cell aspect only to make the three fixture hits occupy
- // distinct fit-width crops. The search/reveal math must use the same
- // reported metrics as placement, whatever a backend reports.
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = .{ .w = 16, .h = 4 },
- } });
-
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
- try std.testing.expect(pardes.look.searchStep(p, 0, 1));
- try std.testing.expectEqual(@as(usize, 0), pv.search_hit);
- try std.testing.expectEqual(@as(usize, 0), pane.search_row.?);
- _ = try p.render(frame.allocator());
- const revision = (try shownAll(p, frame.allocator()))[0].revision;
- const raster = panes.Pdf.rasterForPage(pv, pv.page).?;
- const first_scroll = pv.document_scroll_y;
- const first_results = pv.search_results orelse return error.MissingPdfPageSearch;
- const first_quad = for (first_results.quads) |item| {
- if (item.hit == 0) break item.quad;
- } else return error.MissingFirstPdfHit;
- const first_y = panes.Pdf.normalizedPixel(
- (first_quad.ul.y + first_quad.ur.y + first_quad.ll.y + first_quad.lr.y) / 4,
- raster.ih,
- );
- const first_geometry = panes.Pdf.paneGeometry(p, pane) orelse return error.MissingPdfGeometry;
- try std.testing.expect(first_y >= first_geometry.src.y and
- first_y < first_geometry.src.y + first_geometry.src.h);
-
- try std.testing.expect(pardes.look.searchStep(p, 0, 1));
- try std.testing.expectEqual(@as(usize, 1), pv.search_hit);
- try std.testing.expectEqual(@as(usize, 2), pane.search_row.?);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(revision, (try shownAll(p, frame.allocator()))[0].revision);
-
- try std.testing.expect(pardes.look.searchStep(p, 0, 1));
- try std.testing.expectEqual(@as(usize, 2), pv.search_hit);
- try std.testing.expectEqual(@as(usize, 4), pane.search_row.?);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(revision, (try shownAll(p, frame.allocator()))[0].revision);
- try std.testing.expect(pv.document_scroll_y != first_scroll);
- const third_results = pv.search_results orelse return error.MissingPdfPageSearch;
- const third_quad = for (third_results.quads) |item| {
- if (item.hit == 2) break item.quad;
- } else return error.MissingThirdPdfHit;
- const third_y = panes.Pdf.normalizedPixel(
- (third_quad.ul.y + third_quad.ur.y + third_quad.ll.y + third_quad.lr.y) / 4,
- raster.ih,
- );
- const third_geometry = panes.Pdf.paneGeometry(p, pane) orelse return error.MissingPdfGeometry;
- try std.testing.expect(third_y >= third_geometry.src.y and
- third_y < third_geometry.src.y + third_geometry.src.h);
-}
-
-test "PDF native mouse selection, Look, and highlights share page geometry" {
- if (!pdf_enabled) return;
-
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{
- .file = "docs/design.pdf",
- .cols = 80,
- .rows = 24,
- });
- defer p.deinit();
- const pane = p.panes[0].?;
- var frame = std.heap.ArenaAllocator.init(gpa);
- defer frame.deinit();
-
- // A host without Kitty/native pixels keeps the projected-text contract:
- // j/k can still change pages and a body drag remains a generic selection.
- const fallback = try p.render(frame.allocator());
- try std.testing.expectEqual(@as(usize, 0), fallback.placements.items.len);
- p.update(.{ .key = .{ .cp = 'j' } });
- try std.testing.expectEqual(@as(usize, 1), pane.pdf.?.page);
- p.update(.{ .key = .{ .cp = 'k' } });
- try std.testing.expectEqual(@as(usize, 0), pane.pdf.?.page);
- const fallback_rect = p.view().rects[0];
- const fallback_col = fallback_rect.x + config.GUTTER + 1;
- const fallback_row = fallback_rect.y + BOX_H + 1;
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = fallback_col, .row = fallback_row } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = fallback_col + 4, .row = fallback_row } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = fallback_col + 4, .row = fallback_row } });
- try std.testing.expectEqual(.done, pane.sel[sel_slot].state);
- try std.testing.expect(pane.pdf.?.selection == null);
- pane.sel[sel_slot].state = .none;
-
- p.view().frontend.native_images = true;
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const plain_revision = (try shownAll(p, frame.allocator()))[0].revision;
-
- var found = try pane.pdf.?.document.search(gpa, 0, "Pardes");
- defer found.deinit(gpa);
- const quad = found.quads[0].quad;
- const nx = (quad.ul.x + quad.ur.x + quad.ll.x + quad.lr.x) / 4;
- const ny = (quad.ul.y + quad.ur.y + quad.ll.y + quad.lr.y) / 4;
- const pv = pane.pdf.?;
- const raster = panes.Pdf.rasterForPage(pv, pv.page).?;
- const source_x: u32 = @intCast(@min(
- raster.iw - 1,
- @as(usize, @intFromFloat(nx * @as(f32, @floatFromInt(raster.iw)))),
- ));
- const source_y: u32 = @intCast(@min(
- raster.ih - 1,
- @as(usize, @intFromFloat(ny * @as(f32, @floatFromInt(raster.ih)))),
- ));
-
- // Bring the known word into the fit-width crop, then invert the shared
- // source/destination geometry to the nearest body cell.
- var geometry = panes.Pdf.paneGeometry(p, pane).?;
- if (source_y < geometry.src.y or source_y >= geometry.src.y + geometry.src.h) {
- const overflow = @as(u32, @intCast(raster.ih)) - geometry.src.h;
- const wanted = @min(overflow, source_y -| geometry.src.h / 2);
- pv.pan_y = if (overflow == 0) 0 else @intCast(
- (@as(u64, wanted) * std.math.maxInt(u16) + overflow / 2) / overflow,
- );
- geometry = panes.Pdf.paneGeometry(p, pane).?;
- }
- const pixel_x = geometry.dst.x + @as(u32, @intCast(
- @as(u64, source_x - geometry.src.x) * geometry.dst.w / geometry.src.w,
- ));
- const pixel_y = geometry.dst.y + @as(u32, @intCast(
- @as(u64, source_y - geometry.src.y) * geometry.dst.h / geometry.src.h,
- ));
- const r = p.view().rects[0];
- const base_col: i32 = @intCast(r.x + config.GUTTER + pixel_x / p.view().cell_pixels.w);
- const base_row: i32 = @intCast(r.y + BOX_H + pixel_y / p.view().cell_pixels.h);
-
- var selected_col: ?u16 = null;
- var selected_row: u16 = 0;
- const nearby = [_]i32{ 0, -1, 1, -2, 2 };
- find_word: for (nearby) |dy| for (nearby) |dx| {
- const col: u16 = @intCast(std.math.clamp(
- base_col + dx,
- @as(i32, r.x + config.GUTTER),
- @as(i32, r.x + r.w - 1),
- ));
- const row: u16 = @intCast(std.math.clamp(
- base_row + dy,
- @as(i32, r.y + BOX_H),
- @as(i32, r.y + r.h - 1),
- ));
- if (!panes.Pdf.beginDrag(p, pane, col, row, true)) continue;
- if (std.ascii.findIgnoreCase(pv.selection_text, "Pardes") != null) {
- selected_col = col;
- selected_row = row;
- break :find_word;
- }
- };
- const word_col = selected_col orelse return error.PdfMouseMappingMissedWord;
- try std.testing.expect(std.ascii.findIgnoreCase(
- pardes.exec.heldSelection(p, 0).?,
- "Pardes",
- ) != null);
-
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const selected_revision = (try shownAll(p, frame.allocator()))[0].revision;
- try std.testing.expect(selected_revision != plain_revision);
-
- // Repeating an identical drag endpoint is a no-op: Kitty/SDL keep the
- // same texture generation instead of retransmitting identical pixels.
- try std.testing.expect(panes.Pdf.beginDrag(p, pane, word_col, selected_row, true));
- try std.testing.expect(raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(selected_revision, (try shownAll(p, frame.allocator()))[0].revision);
-
- // Delayed native hover retains independent quads/text and changes only
- // presentation state. In particular it must not borrow the click path,
- // whose page activation and persistent selection are intentional effects
- // of a gesture rather than observation.
- {
- const delay = config.look_preview_delay_frames;
- const active_before = p.view().active;
- const page_before = pv.page;
- const scroll_before = pv.document_scroll_y;
- const sels_before = pane.sel;
- const cursor_before = .{ pane.body.cur_row, pane.body.cur_col };
- const modal_before = .{ pane.body.vsel, pane.body.nsel };
- const selection_before = pv.selection orelse return error.MissingPdfSelection;
- const selection_quads_before = try gpa.dupe(pdf_impl.Quad, selection_before.quads);
- defer gpa.free(selection_quads_before);
- const selection_text_before = try gpa.dupe(u8, pv.selection_text);
- defer gpa.free(selection_text_before);
- const selection_anchor_before = pv.selection_anchor;
- const selection_head_before = pv.selection_head;
- const query_before = try gpa.dupe(u8, pv.search_query);
- defer gpa.free(query_before);
- const search_hit_before = pv.search_hit;
- const jumps_before = .{ p.view().jumps.n, p.view().jumps.cur, p.n_look_src };
- const effects_before = p.effects_len;
- try std.testing.expect(p.view().drag == .none);
-
- const hover_motion = Event{ .mouse = .{
- .button = .none,
- .kind = .motion,
- .col = word_col,
- .row = selected_row,
- } };
- p.update(hover_motion);
- try std.testing.expect(p.look_hover_wait != null);
- for (0..delay) |_| p.update(.tick);
- const hover = p.pdf_hover_preview orelse return error.MissingPdfHoverPreview;
- try std.testing.expectEqual(@as(usize, 0), hover.probe.page);
- try std.testing.expect(hover.probe.quads.len > 0);
- try std.testing.expect(std.ascii.findIgnoreCase(hover.probe.text, "Pardes") != null);
- try std.testing.expect(p.look_hover_preview == null);
- try std.testing.expect(p.look_hover_wait == null);
-
- const decorated = try panes.Pdf.buildHighlights(
- pv,
- p.scratch.allocator(),
- panes.Pdf.highlightInput(p, 0, pane),
- );
- const page_highlights = decorated.forPage(pv.page);
- try std.testing.expectEqual(pdf_impl.HighlightKind.custom, page_highlights[0].kind);
- try std.testing.expectEqual(pdf_impl.HighlightKind.selection, page_highlights[page_highlights.len - 1].kind);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const hovered_revision = (try shownAll(p, frame.allocator()))[0].revision;
- try std.testing.expect(hovered_revision != selected_revision);
-
- p.update(.pointer_leave);
- try std.testing.expect(p.pdf_hover_preview == null);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != hovered_revision);
-
- try std.testing.expectEqual(active_before, p.view().active);
- try std.testing.expectEqual(page_before, pv.page);
- try std.testing.expectEqual(scroll_before, pv.document_scroll_y);
- try std.testing.expect(std.meta.eql(sels_before, pane.sel));
- try std.testing.expectEqual(cursor_before, .{ pane.body.cur_row, pane.body.cur_col });
- try std.testing.expect(std.meta.eql(modal_before, .{ pane.body.vsel, pane.body.nsel }));
- const selection_after = pv.selection orelse return error.HoverDroppedPdfSelection;
- try std.testing.expectEqualSlices(pdf_impl.Quad, selection_quads_before, selection_after.quads);
- try std.testing.expectEqualStrings(selection_text_before, pv.selection_text);
- try std.testing.expect(std.meta.eql(selection_anchor_before, pv.selection_anchor));
- try std.testing.expect(std.meta.eql(selection_head_before, pv.selection_head));
- try std.testing.expectEqualStrings(query_before, pv.search_query);
- try std.testing.expectEqual(search_hit_before, pv.search_hit);
- try std.testing.expectEqual(jumps_before, .{ p.view().jumps.n, p.view().jumps.cur, p.n_look_src });
- try std.testing.expectEqual(effects_before, p.effects_len);
- try std.testing.expect(p.view().drag == .none);
- }
-
- // A native right-click resolves the same MuPDF-snapped word and feeds it
- // to Look. Resolving it clears the previous selection, leaving the new
- // search highlights without carrying an old selection into the result.
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .press, .col = word_col, .row = selected_row } });
- p.update(.{ .mouse = .{ .button = config.look_button, .kind = .release, .col = word_col, .row = selected_row } });
- try std.testing.expect(std.ascii.findIgnoreCase(pv.search_query, "Pardes") != null);
- pv.resolveSearch(p.pdf_gpa);
- const highlights = (try panes.Pdf.buildHighlights(
- pv,
- p.scratch.allocator(),
- panes.Pdf.highlightInput(p, 0, pane),
- )).forPage(pv.page);
- try std.testing.expect(highlights.len > 0);
- for (highlights) |highlight| try std.testing.expectEqual(pdf_impl.HighlightKind.search, highlight.kind);
- try std.testing.expect(pv.selection == null and pv.selection_text.len == 0);
- const revision_before_reveal = raster.revision;
- const max_document_scroll = @as(f64, @floatFromInt(
- pv.document_height -| panes.Pdf.paneViewport(p, pane).?.pixel_h,
- ));
- pv.document_scroll_y = max_document_scroll;
- panes.Pdf.revealSearch(pv, panes.Pdf.paneViewport(p, pane).?, panes.Pdf.paneGeometry(p, pane));
- const revealed_scroll = pv.document_scroll_y;
- try std.testing.expect(revealed_scroll != max_document_scroll);
- try std.testing.expectEqual(revision_before_reveal, raster.revision);
- pv.document_scroll_y = max_document_scroll;
- panes.Pdf.revealSearch(
- pv,
- panes.Pdf.paneViewport(p, pane).?,
- panes.Pdf.paneGeometry(p, pane),
- ); // one shot: subsequent manual pan stays put
- try std.testing.expectEqual(max_document_scroll, pv.document_scroll_y);
- pv.document_scroll_y = revealed_scroll;
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision != selected_revision);
-
- // Fit and viewport changes can crop a hit which was already revealed.
- // Fit remains placement-only. SDL's physical-viewport quality request
- // changes with a resize and therefore replaces pixels; Kitty's fixed,
- // bandwidth-conscious request retains them.
- const revision_before_geometry_change = (try shownAll(p, frame.allocator()))[0].revision;
- pv.search_reveal_pending = false;
- panes.Pdf.toggleFit(pane);
- try std.testing.expect(pv.search_reveal_pending);
- pv.search_reveal_pending = false;
- panes.Pdf.toggleFit(pane); // restore the reading-width geometry
- try std.testing.expect(pv.search_reveal_pending);
- pv.search_reveal_pending = false;
- const original_cell_pixels = p.view().cell_pixels;
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = p.view().cell_pixels,
- } });
- try std.testing.expect(!pv.search_reveal_pending);
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = .{
- .w = original_cell_pixels.w,
- .h = original_cell_pixels.h + 1,
- },
- } });
- try std.testing.expect(pv.search_reveal_pending);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- if (pdf_raster_policy.match_viewport)
- try std.testing.expect((try shownAll(p, frame.allocator()))[0].revision !=
- revision_before_geometry_change)
- else
- try std.testing.expectEqual(
- revision_before_geometry_change,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- p.update(.{ .resize = .{
- .cols = p.view().screen_w,
- .rows = p.view().screen_h,
- .cell_pixels = original_cell_pixels,
- } });
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
-
- // Unsupported text-selection actions are consumed by the PDF adapter:
- // they neither invent a range over placeholder cells nor disturb the
- // native MuPDF selection. The select-button's no-drag click still clears.
- try std.testing.expect(panes.Pdf.beginDrag(p, pane, word_col, selected_row, true));
- p.update(.{ .key = .{ .cp = 'v' } });
- try std.testing.expect(pv.selection != null);
- try std.testing.expect(!pane.body.vsel.active);
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = word_col, .row = selected_row } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = word_col, .row = selected_row } });
- try std.testing.expect(pv.selection == null);
- try std.testing.expect(panes.Pdf.beginDrag(p, pane, word_col, selected_row, true));
-
- // Native drag events update MuPDF quads and copied text immediately, but
- // keep the already transmitted page generation stable until release.
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- const before_drag_revision = (try shownAll(p, frame.allocator()))[0].revision;
- const drag_col = @min(r.x + r.w - 1, word_col +| 12);
- const drag_row = @min(r.y + r.h - 1, selected_row +| 4);
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .press,
- .col = word_col,
- .row = selected_row,
- } });
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .drag,
- .col = @min(drag_col, word_col +| 4),
- .row = @min(drag_row, selected_row +| 2),
- } });
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- before_drag_revision,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .drag,
- .col = drag_col,
- .row = drag_row,
- } });
- try std.testing.expect(p.view().drag.select.pdf.selection_changed);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- before_drag_revision,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- p.update(.{ .mouse = .{
- .button = config.select_button,
- .kind = .release,
- .col = drag_col,
- .row = drag_row,
- } });
- try std.testing.expect(!raster.tried);
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- before_drag_revision + 1,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
- _ = frame.reset(.retain_capacity);
- _ = try p.render(frame.allocator());
- try std.testing.expectEqual(
- (try shownAll(p, frame.allocator()))[0].revision,
- (try shownAll(p, frame.allocator()))[0].revision,
- );
-
- const saved_query = try gpa.dupe(u8, pv.search_query);
- defer gpa.free(saved_query);
- const saved_selection = try gpa.dupe(u8, pv.selection_text);
- defer gpa.free(saved_selection);
- const selected_page = pv.selection_page;
- panes.Pdf.activatePage(p, pane, 1, true);
- try std.testing.expect(pv.selection != null);
- try std.testing.expectEqual(selected_page, pv.selection_page);
- try std.testing.expectEqualStrings(saved_selection, pv.selection_text);
- try std.testing.expectEqualStrings(saved_query, pv.search_query);
-}
-
-test "Esc back into a PDF keeps the offset within its page" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const fixture = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
-
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- p.update(.{ .resize = .{ .cols = 80, .rows = 28 } });
- const doc = p.view().active;
- const dp = p.panes[doc].?;
- try std.testing.expect(dp.pdf != null);
- p.sync();
-
- // Read a little way DOWN the page you are on, then step away.
- const pv = dp.pdf.?;
- pv.document_scroll_y += 137;
- const mid = pv.document_scroll_y;
- pv.scroll_to_page_pending = false;
- p.update(.{ .key = .{ .cp = 'n', .alt = true } }); // a shell under the doc
- p.sync();
- const shell = p.view().active;
- try std.testing.expect(shell != doc);
-
- p.update(.{ .key = .{ .cp = Key.escape } }); // Esc: back into the PDF
- p.sync();
- try std.testing.expectEqual(doc, p.view().active);
-
- // The jumps stack records a PDF as its PAGE, so returning revealed the page
- // you were already on — and a reveal sets `document_scroll_y` to that page's
- // start, throwing away where you had read to inside it.
- try std.testing.expectEqual(mid, pv.document_scroll_y);
- // Same reveal, the other half: with no valid layout yet it only ARMS the
- // snap, so a test that watched the offset alone would not see it coming.
- try std.testing.expect(!pv.scroll_to_page_pending);
-}
-
-test "PDF Back and Forward clear selections and land on recorded pages" {
- if (!pdf_enabled) return error.SkipZigTest;
- const p = try Pardes.init(std.testing.allocator, .{ .file = "docs/design.pdf", .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const pane = p.panes[0].?;
- const state = pane.pdf.?;
- try std.testing.expect(state.page_count > 1);
- try std.testing.expect(state.focusLocation(p.pdf_gpa, 2, 0));
- p.view().jumps.n = 2;
- p.view().jumps.cur = 1;
- p.view().jumps.list[0] = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 0 };
- p.view().jumps.list[1] = .{ .pane = 0, .serial = pane.serial, .line = 2, .col = 0 };
- for ([_]u21{ 'o', 'i' }, 0..) |key, destination| {
- try std.testing.expectEqual(panes.Pdf.SelectionUpdate.changed, state.setSelection(p.pdf_gpa, .{ .x = 0, .y = 0 }, .{ .x = 1, .y = 1 }, true));
- try std.testing.expect(state.selection != null and state.selection_text.len > 0);
- p.update(.{ .key = .{ .cp = key, .ctrl = true } });
- try std.testing.expectEqual(destination, p.view().jumps.cur);
- try std.testing.expectEqual(destination, state.page);
- try std.testing.expect(state.selection == null);
- try std.testing.expect(state.selection_page == null);
- try std.testing.expectEqual(@as(usize, 0), state.selection_text.len);
- try std.testing.expect(state.drag_anchor == null and state.drag_head == null);
- }
-}
-
-test "a PDF's fit and tint, and Collapse, read in its ctl and come back from a Dump" {
- if (!pdf_enabled) return;
- const gpa = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const fixture = try pdf_impl.testFixture(gpa, "outline.pdf");
- defer gpa.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "outline.pdf", .data = fixture });
- var path_buf: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/outline.pdf", .{tmp.sub_path});
- const p = try Pardes.init(gpa, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- const doc = p.panes[0].?;
- try std.testing.expect(p.executeBuiltinLine(0, "PdfFit height"));
- try std.testing.expect(p.executeBuiltinLine(0, "PdfTint full"));
- const ctlfs = pardes.ctlfs;
- const ctl_node = ctlfs.Node.of(doc.serial, .ctl);
- const read = p.fsPayload(p.serveFs(.{ .tag = 1, .op = .read, .node = ctl_node, .size = 4096 }));
- try std.testing.expect(std.mem.indexOf(u8, read, "fit:height tint:full ") != null);
- try pardes.dump.dumpState(p);
- const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
- defer restored.deinit();
- const pv = restored.panes[0].?.pdf.?;
- try std.testing.expectEqualStrings("height", @tagName(pv.fit));
- try std.testing.expectEqualStrings("full", @tagName(pv.tint));
-}
-
-/// The jumplist's PDF (pdfrender): the Intel SDM (5363 pages, the author's
-/// stress file) when this machine has it, else the docs' PDF; the same
-/// checks either way.
-fn jumpPdf() []const u8 {
- const sdm = "/home/goblin/00-projects/kvmctf/harnesses/contained-official/visor-uefi/intel-ia32-manual.pdf";
- std.Io.Dir.accessAbsolute(std.testing.io, sdm, .{}) catch return "docs/design.pdf";
- return sdm;
-}
-
-/// Lays the PDF pane out (a frame drawn) and syncs, so the jumplist sees it.
-fn jumpFrame(p: *Pardes) !void {
- var frame: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer frame.deinit();
- _ = try p.render(frame.allocator());
- p.sync();
-}
-
-fn stripAtPlace(p: *Pardes, pane: *pardes.Pane, page: usize, fraction: f64) !f64 {
- const pv = pane.pdf.?;
- pv.document_scroll_y = @as(f64, @floatFromInt(pv.page_starts[page])) + fraction * @as(f64, @floatFromInt(pv.page_heights[page]));
- try jumpFrame(p);
- return pv.document_scroll_y;
-}
-
-test "a PDF's jumps: Back after a far jump returns to the exact offset, two places on one page are two entries" {
- if (!pdf_enabled) return error.SkipZigTest;
- const p = try Pardes.init(std.testing.allocator, .{ .file = jumpPdf(), .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const id = p.view().active;
- const pane = p.panes[id].?;
- const pv = pane.pdf.?;
- try jumpFrame(p);
- try std.testing.expect(pv.page_count > 3);
- // Two places on page 1, more than a body apart: two entries.
- const before = p.view().jumps.n;
- _ = try stripAtPlace(p, pane, 1, 0.05);
- const near = try stripAtPlace(p, pane, 1, 0.8);
- try std.testing.expectEqual(before + 2, p.view().jumps.n);
- try std.testing.expect(p.view().jumps.list[p.view().jumps.n - 1].pdf);
- // A far jump (a Look at a page), then Back: the exact offset, not the
- // page's top, and its page.
- look.lookAt(p, id, if (pv.page_count > 3000) ":3000" else ":4");
- try jumpFrame(p);
- try std.testing.expect(pv.page >= 3);
- pardes.Jump.jumpBy(p, -1);
- try jumpFrame(p);
- try std.testing.expectEqual(@as(usize, 1), pv.page);
- try std.testing.expectApproxEqAbs(near, pv.document_scroll_y, 0.5);
- // A wheel's small steps are the same visit: the entry follows them.
- const n = p.view().jumps.n;
- for (0..4) |_| {
- _ = panes.Pdf.scrollPane(p, pane, 30, true);
- try jumpFrame(p);
- }
- try std.testing.expectEqual(n, p.view().jumps.n);
-}
-
-test "a PDF's jumps keep to the PDF, and a closed PDF reopens at its place" {
- if (!pdf_enabled) return error.SkipZigTest;
- // Recent keeps a file by the path it was opened as: a real one here,
- // as a Look opens one.
- var cwd_buf: [4096]u8 = undefined;
- const cwd = cwd_buf[0..try std.Io.Dir.cwd().realPath(std.testing.io, &cwd_buf)];
- var path_buf: [4200]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, "{s}/docs/design.pdf", .{cwd});
- const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 28 });
- defer p.deinit();
- p.view().frontend.native_images = true;
- const doc = p.view().active;
- const pane = p.panes[doc].?;
- try jumpFrame(p);
- const first = try stripAtPlace(p, pane, 1, 0.3);
- // A text between, then a far place in the PDF.
- look.lookAt(p, doc, "../build.zig:10");
- try jumpFrame(p);
- try std.testing.expect(p.view().active != doc);
- p.view().active = doc;
- _ = try stripAtPlace(p, pane, 3, 0.5);
- // Back from the PDF keeps to it: its own earlier place, not the text.
- pardes.Jump.jumpBy(p, -1);
- try jumpFrame(p);
- try std.testing.expectEqual(doc, p.view().active);
- try std.testing.expectApproxEqAbs(first, pane.pdf.?.document_scroll_y, 0.5);
- // Closed, its entries stay; Back from the text reopens it at the place.
- pardes.Jump.jumpBy(p, 1);
- try jumpFrame(p);
- try p.removePane(doc, null);
- try jumpFrame(p);
- var closed = false;
- for (p.view().jumps.list[0..p.view().jumps.n]) |j| closed = closed or (j.serial == 0 and j.pdf);
- try std.testing.expect(closed);
- var tries: usize = 0;
- while (tries < 4) : (tries += 1) {
- pardes.Jump.jumpBy(p, -1);
- try jumpFrame(p);
- if (p.panes[p.view().active].?.pdf != null) break;
- }
- const reopened = p.panes[p.view().active].?;
- try std.testing.expect(reopened.pdf != null);
- const pv = reopened.pdf.?;
- // The newest PDF place before the text: page 4, half way down.
- try std.testing.expectEqual(@as(usize, 3), pv.page);
- const want = @as(f64, @floatFromInt(pv.page_starts[3])) + 0.5 * @as(f64, @floatFromInt(pv.page_heights[3]));
- try std.testing.expectApproxEqAbs(want, pv.document_scroll_y, 0.5);
-}
diff --git a/test/process.zig b/test/process.zig
index 0a443a21..67d883ca 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -512,9 +512,11 @@ pub fn of(gpa: std.mem.Allocator, h: *const eh.Harness) Files {
/// host it was built with.
pub const Backend = enum { tui, gui };
pub var backend: Backend = .tui;
-/// The image addon the build made (the runner's --image-addon=), linked
-/// into each session's data directory, where its start scan finds it.
-pub var image_addon: ?[:0]const u8 = null;
+/// The addons the build made (the runner's --addon=, image and pdf),
+/// linked into each session's data directory, where its start scan finds
+/// them.
+pub var addons: [4][:0]const u8 = undefined;
+pub var naddons: usize = 0;
/// A case about one frontend's own behaviour (`--tty`, a killed terminal
/// editor) skips on the other.
@@ -586,9 +588,13 @@ pub const Detached = struct {
errdefer if (d.cap_len > 0) removeDir(d.captures());
const dir = d.root();
var bufs: [6][4096]u8 = undefined;
- if (image_addon) |lib| {
- for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| _ = libc.mkdir(try std.fmt.bufPrintSentinel(&bufs[5], "{s}{s}", .{ dir, sub }, 0), 0o755);
- _ = libc.symlink(lib, try std.fmt.bufPrintSentinel(&bufs[5], "{s}/.local/share/pardes/addons/image.so", .{dir}, 0));
+ if (naddons > 0) for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| {
+ _ = libc.mkdir(try std.fmt.bufPrintSentinel(&bufs[5], "{s}{s}", .{ dir, sub }, 0), 0o755);
+ };
+ for (addons[0..naddons]) |lib| {
+ const base = std.fs.path.basename(lib);
+ const installed = if (std.mem.startsWith(u8, base, "lib")) base[3..] else base;
+ _ = libc.symlink(lib, try std.fmt.bufPrintSentinel(&bufs[5], "{s}/.local/share/pardes/addons/{s}", .{ dir, installed }, 0));
}
if (opts.init) |text| {
const cfg = try std.fmt.bufPrintSentinel(&bufs[5], "{s}/config", .{dir}, 0);
diff --git a/test/process_test.zig b/test/process_test.zig
index 37dd0954..b1f64a45 100644
--- a/test/process_test.zig
+++ b/test/process_test.zig
@@ -22,14 +22,16 @@ const files = .{
pub fn main(init: std.process.Init) !void {
const all = try init.minimal.args.toSlice(init.arena.allocator());
- // <pardes> [--backend=tui|gui] [--image-addon=<image.so>] [filter]
+ // <pardes> [--backend=tui|gui] [--addon=<lib>]... [filter]
var args: [3][:0]const u8 = undefined;
var n: usize = 0;
for (all[1..]) |a| {
if (std.mem.startsWith(u8, a, "--backend=")) {
process.backend = std.meta.stringToEnum(process.Backend, a["--backend=".len..]) orelse return error.Usage;
- } else if (std.mem.startsWith(u8, a, "--image-addon=")) {
- process.image_addon = try std.Io.Dir.cwd().realPathFileAlloc(init.io, a["--image-addon=".len..], init.arena.allocator());
+ } else if (std.mem.startsWith(u8, a, "--addon=")) {
+ if (process.naddons == process.addons.len) return error.Usage;
+ process.addons[process.naddons] = try std.Io.Dir.cwd().realPathFileAlloc(init.io, a["--addon=".len..], init.arena.allocator());
+ process.naddons += 1;
} else if (n < args.len) {
args[n] = a;
n += 1;
diff --git a/test/session.zig b/test/session.zig
index 5b608521..8b8ec17f 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -403,24 +403,39 @@ pub const Session = struct {
// pdf:
+ /// The pdf addon (addons/pdf/pdf.c), as the build makes it; a build
+ /// without it (-Dmupdf=false) has none.
+ pub const pdf_addon: ?[]const u8 = if (@import("session_options").has_pdf_addon) @import("session_options").pdf_addon else null;
+
+ /// The pdf addon loaded into the session, once: a test of a PDF in a
+ /// build without it skips.
+ pub fn loadPdf(s: *Session) !void {
+ const lib = pdf_addon orelse return error.SkipZigTest;
+ if (std.mem.indexOf(u8, try s.read("/addons"), "pdf ") != null) return;
+ const real = try std.Io.Dir.cwd().realPathFileAlloc(std.testing.io, lib, s.arena.allocator());
+ try s.write("/ctl", s.at("Addon load {s}\n", .{real}));
+ }
+
/// A Look of `path` at the root (one relative to the working directory
/// made absolute first); the serial of the pane with the keyboard after.
- /// A PDF in a build without them (-Dmupdf=false: no PdfTint in
- /// /commands) skips the test.
+ /// A PDF loads the pdf addon first.
pub fn lookFile(s: *Session, path: []const u8) !u32 {
- if (std.mem.endsWith(u8, path, ".pdf") and std.mem.indexOf(u8, try s.read("/commands"), "PdfTint") == null) return error.SkipZigTest;
+ if (std.mem.endsWith(u8, path, ".pdf")) try s.loadPdf();
var buf: [4096]u8 = undefined;
const abs = if (std.fs.path.isAbsolute(path)) path else s.at("{s}/{s}", .{ buf[0..try std.Io.Dir.cwd().realPath(std.testing.io, &buf)], path });
try s.write("/look", s.at("{s}\n", .{abs}));
return s.focused();
}
- /// The page a PDF pane shows and its pages, from its tag's `[page/pages]`.
+ /// The page a PDF pane shows and its pages, from its tag's `[page/pages]`
+ /// (the pdf addon's prefix, which starts it).
pub fn pdfPage(s: *Session, n: u32) !struct { u32, u32 } {
+ // A kind's prefix is its last frame's: one drawn first.
+ _ = try s.read("/screen");
const tag = try s.read(s.at("/pane/{d}/tag", .{n}));
- const lo = std.mem.indexOf(u8, tag, " [") orelse return error.NoPage;
- const close = std.mem.indexOfScalarPos(u8, tag, lo, ']') orelse return error.NoPage;
- var it = std.mem.splitScalar(u8, tag[lo + 2 .. close], '/');
+ if (!std.mem.startsWith(u8, tag, "[")) return error.NoPage;
+ const close = std.mem.indexOfScalar(u8, tag, ']') orelse return error.NoPage;
+ var it = std.mem.splitScalar(u8, tag[1..close], '/');
return .{ try std.fmt.parseInt(u32, it.next().?, 10), try std.fmt.parseInt(u32, it.next() orelse return error.NoPage, 10) };
}
diff --git a/test/snapshot.zig b/test/snapshot.zig
index 26022a41..51c81dd9 100644
--- a/test/snapshot.zig
+++ b/test/snapshot.zig
@@ -86,9 +86,10 @@ var careful = false;
/// abs path of the deterministic mock language server the build handed over
/// (--lspmock=); null leaves the protocol client fully disabled for the run
var lspmock_bin: ?[:0]const u8 = null;
-/// abs path of the image addon the build made (--image-addon=), linked into
-/// each script's data directory, where a session's start scan finds it
-var image_addon: ?[:0]const u8 = null;
+/// abs paths of the addons the build made (--addon=, image and pdf), linked
+/// into each script's data directory, where a session's start scan finds them
+var addons: [4][:0]const u8 = undefined;
+var naddons: usize = 0;
var record_dir: ?[]const u8 = null;
/// --tape=DIR: each session records its tape there (PARDES_RECORD, src/tape.zig)
/// and the script fails unless every tape replays without diverging.
@@ -136,8 +137,10 @@ pub fn main(init: std.process.Init) !void {
trace_stable = true;
} else if (std.mem.startsWith(u8, a, "--lspmock=")) {
lspmock = try absPath(arena, orig_cwd, a["--lspmock=".len..]);
- } else if (std.mem.startsWith(u8, a, "--image-addon=")) {
- image_addon = try arena.dupeSentinel(u8, try absPath(arena, orig_cwd, a["--image-addon=".len..]), 0);
+ } else if (std.mem.startsWith(u8, a, "--addon=")) {
+ if (naddons == addons.len) return error.TooManyAddons;
+ addons[naddons] = try arena.dupeSentinel(u8, try absPath(arena, orig_cwd, a["--addon=".len..]), 0);
+ naddons += 1;
} else if (std.mem.startsWith(u8, a, "--record=")) {
record_dir = try absPath(arena, orig_cwd, a["--record=".len..]);
} else if (std.mem.startsWith(u8, a, "--tape=")) {
@@ -170,7 +173,7 @@ pub fn main(init: std.process.Init) !void {
std.mem.eql(u8, a, "--no-retry") or
std.mem.eql(u8, a, "--trace-stable") or
std.mem.startsWith(u8, a, "--lspmock=") or
- std.mem.startsWith(u8, a, "--image-addon=") or
+ std.mem.startsWith(u8, a, "--addon=") or
std.mem.startsWith(u8, a, "--record=") or
std.mem.startsWith(u8, a, "--tape=") or
std.mem.eql(u8, a, "--dump") or
@@ -637,9 +640,12 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const
// ...and its data directory (dumps, the addons its start scan loads).
const data_home = try std.fmt.allocPrintSentinel(arena, "{s}/.local/share", .{home}, 0);
_ = setenv("XDG_DATA_HOME", data_home, 1);
- if (image_addon) |lib| {
- for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| try mkdir(arena, try std.fmt.allocPrint(arena, "{s}{s}", .{ home, sub }), true);
- if (libc.symlink(lib, try std.fmt.allocPrintSentinel(arena, "{s}/pardes/addons/image.so", .{data_home}, 0)) != 0) return error.SymlinkFailed;
+ if (naddons > 0) for ([_][]const u8{ "/.local", "/.local/share", "/.local/share/pardes", "/.local/share/pardes/addons" }) |sub| try mkdir(arena, try std.fmt.allocPrint(arena, "{s}{s}", .{ home, sub }), true);
+ for (addons[0..naddons]) |lib| {
+ // libpdf.so as pdf.so: the name a build installs it as.
+ const file = std.fs.path.basename(lib);
+ const installed = if (std.mem.startsWith(u8, file, "lib")) file[3..] else file;
+ if (libc.symlink(lib, try std.fmt.allocPrintSentinel(arena, "{s}/pardes/addons/{s}", .{ data_home, installed }, 0)) != 0) return error.SymlinkFailed;
}
// ...and it is not empty: the DEFAULT shell is $SHELL, whatever this
// machine's user logs in with (fish's prompt carries a hostname and its