summaryrefslogtreecommitdiff
path: root/src/pdf.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/pdf.zig')
-rw-r--r--src/pdf.zig710
1 files changed, 363 insertions, 347 deletions
diff --git a/src/pdf.zig b/src/pdf.zig
index 712750dc..18037bb7 100644
--- a/src/pdf.zig
+++ b/src/pdf.zig
@@ -2,66 +2,28 @@
//! 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 = @cImport({
- @cInclude("pdf_bridge.h");
-});
+const c = @import("pdf_c"); // src/pdf_bridge.h, translated by build.zig
-const allocation_header_size = 16;
+/// 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;
-comptime {
- if (allocation_header_size < @sizeOf(usize))
- @compileError("PDF allocation header is too small");
-}
-
-fn bridgeAlloc(user: ?*anyopaque, size_arg: usize) callconv(.c) ?*anyopaque {
- const user_ptr = user orelse return null;
- const allocator: *std.mem.Allocator = @ptrCast(@alignCast(user_ptr));
- const size = @max(size_arg, 1);
- const total = std.math.add(usize, allocation_header_size, size) catch
- return null;
- const bytes = allocator.alignedAlloc(u8, .@"16", total) catch return null;
- const header: *align(16) usize = @ptrCast(bytes.ptr);
- header.* = total;
- return @ptrCast(bytes.ptr + allocation_header_size);
+fn bridgeAlloc(_: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
+ return bridge_heap.malloc(size);
}
-fn bridgeFree(user: ?*anyopaque, pointer: ?*anyopaque) callconv(.c) void {
- const data = pointer orelse return;
- const user_ptr = user orelse @panic("PDF allocator callback has no allocator");
- const allocator: *std.mem.Allocator = @ptrCast(@alignCast(user_ptr));
- const data_bytes: [*]u8 = @ptrCast(data);
- const base: [*]align(16) u8 =
- @ptrCast(@alignCast(data_bytes - allocation_header_size));
- const header: *align(16) usize = @ptrCast(base);
- allocator.free(base[0..header.*]);
+fn bridgeRealloc(_: ?*anyopaque, block: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
+ return bridge_heap.realloc(block, size);
}
-fn bridgeRealloc(
- user: ?*anyopaque,
- pointer: ?*anyopaque,
- size_arg: usize,
-) callconv(.c) ?*anyopaque {
- if (pointer == null) return bridgeAlloc(user, size_arg);
- if (size_arg == 0) {
- bridgeFree(user, pointer);
- return null;
- }
-
- const user_ptr = user orelse return null;
- const allocator: *std.mem.Allocator = @ptrCast(@alignCast(user_ptr));
- const total = std.math.add(usize, allocation_header_size, size_arg) catch
- return null;
- const data_bytes: [*]u8 = @ptrCast(pointer.?);
- const base: [*]align(16) u8 =
- @ptrCast(@alignCast(data_bytes - allocation_header_size));
- const header: *align(16) usize = @ptrCast(base);
- const resized = allocator.realloc(base[0..header.*], total) catch return null;
- const resized_header: *align(16) usize = @ptrCast(resized.ptr);
- resized_header.* = total;
- return @ptrCast(resized.ptr + allocation_header_size);
+fn bridgeFree(_: ?*anyopaque, block: ?*anyopaque) callconv(.c) void {
+ bridge_heap.free(block);
}
/// Installs the allocator used by all subsequently opened PDF documents and
@@ -70,7 +32,7 @@ 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 = &bridge_allocator,
+ .user = null,
.alloc = bridgeAlloc,
.realloc = bridgeRealloc,
.free = bridgeFree,
@@ -90,50 +52,65 @@ pub fn stop() void {
bridge_allocator = undefined;
}
-test "PDF C allocator callbacks preserve and free exact allocations" {
- var allocator = std.testing.allocator;
-
- var live: ?*anyopaque = bridgeAlloc(&allocator, 4) orelse
- return error.OutOfMemory;
- defer if (live) |pointer| bridgeFree(&allocator, pointer);
- const original: [*]u8 = @ptrCast(live.?);
- @memcpy(original[0..4], "data");
-
- live = bridgeRealloc(&allocator, live, 32) orelse
- return error.OutOfMemory;
- const grown: [*]u8 = @ptrCast(live.?);
- try std.testing.expectEqualSlices(u8, "data", grown[0..4]);
-
- try std.testing.expect(bridgeAlloc(
- &allocator,
- std.math.maxInt(usize),
- ) == null);
-
- const zero = bridgeAlloc(&allocator, 0) orelse return error.OutOfMemory;
- bridgeFree(&allocator, zero);
- try std.testing.expect(bridgeRealloc(&allocator, live, 0) == null);
- live = null;
-}
-
test "custom allocator owns a complete PDF document lifecycle" {
start(std.testing.allocator);
defer stop();
- var document = try Document.open("docs/design.pdf");
+ var document = try openTestFile("docs/design.pdf");
defer document.deinit();
- const raster = try document.render(std.testing.allocator, 0);
+ 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` remains the hard allocation
-/// ceiling for hostile page sizes and very large displays.
+/// 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);
@@ -142,8 +119,12 @@ pub const RenderRequest = struct {
pub const default_render_request: RenderRequest = .{};
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;
+/// The tallest page raster any request produces (rows), whatever it is shown at.
+pub const max_raster_rows: usize = c.PARDES_PDF_MAX_RASTER_ROWS;
/// MuPDF's per-document eviction cache ceiling. The owned RGBA render buffer
/// is allocated separately by Pardes and does not count against this store.
pub const store_limit_bytes: usize = c.PARDES_PDF_STORE_LIMIT_BYTES;
@@ -157,6 +138,7 @@ test "MuPDF document cache has an explicit conservative ceiling" {
/// 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;
@@ -721,20 +703,6 @@ pub const Document = struct {
handle: *c.pardes_pdf_document,
pages: usize,
- pub fn open(path: []const u8) !Document {
- var path_buf: [4096]u8 = undefined;
- const path_z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch
- return error.PathTooLong;
- var page_count: c_int = 0;
- const handle = c.pardes_pdf_open(path_z.ptr, &page_count) orelse
- return error.OpenFailed;
- if (page_count < 1) {
- c.pardes_pdf_close(handle);
- return error.EmptyDocument;
- }
- return .{ .handle = handle, .pages = @intCast(page_count) };
- }
-
pub fn deinit(document: *Document) void {
c.pardes_pdf_close(document.handle);
document.* = undefined;
@@ -747,6 +715,25 @@ pub const Document = struct {
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 {
@@ -898,44 +885,22 @@ pub const Document = struct {
return .{ .width = size.width, .height = size.height };
}
- /// Render one zero-based page directly into allocator-owned packed RGBA.
- pub fn render(document: *Document, gpa: std.mem.Allocator, page: usize) !Render {
- return document.renderAt(gpa, page, default_render_request);
- }
-
- pub fn renderAt(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- request: RenderRequest,
- ) !Render {
- return document.renderInternal(gpa, page, request, null);
- }
-
- /// Render and bake normalized oriented highlights through MuPDF's draw
- /// device. An empty list takes the exact same plain-render path as render.
- pub fn renderWithHighlights(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- highlights: []const Highlight,
- ) !Render {
- return document.renderWithHighlightsAt(
- gpa,
- page,
- default_render_request,
- highlights,
- );
- }
-
- pub fn renderWithHighlightsAt(
+ /// 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 {
- return document.renderInternal(gpa, page, request, highlights);
+ 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.
@@ -956,18 +921,21 @@ pub const Document = struct {
bounded.minimum_width,
bounded.minimum_height,
bounded.max_dimension,
+ bounded.display_width,
+ bounded.display_height,
&raw_layout,
) != c.PARDES_PDF_OK) return error.RenderFailed;
- const layout = try checkedRasterLayout(raw_layout);
- if (layout.len > max_owned_raster_bytes) return error.PixmapTooLarge;
- return layout;
+ // 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.
- pub fn renderIntoAt(
+ /// 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,
@@ -975,12 +943,46 @@ pub const Document = struct {
band: Raster.Band,
highlights: []const Highlight,
rgba: []u8,
+ transparent_paper: bool,
) !void {
- return document.renderIntoAtWithPaper(page, request, raster, band, highlights, rgba, false);
+ 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.dpi,
+ bounded.minimum_width,
+ bounded.minimum_height,
+ bounded.max_dimension,
+ bounded.display_width,
+ bounded.display_height,
+ 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;
}
- /// Preserve the PDF's content coverage when the host paints paper separately.
- pub fn renderIntoAtWithPaper(
+ /// 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,
@@ -988,23 +990,22 @@ pub const Document = struct {
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;
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);
- if (c.pardes_pdf_render_into(
+ if (c.pardes_pdf_paint_highlights(
document.handle,
@intCast(page),
bounded.dpi,
bounded.minimum_width,
bounded.minimum_height,
bounded.max_dimension,
- highlight_ptr,
+ bounded.display_width,
+ bounded.display_height,
+ if (highlights.len == 0) null else @ptrCast(highlights.ptr),
highlights.len,
rgba.ptr,
rgba.len,
@@ -1013,15 +1014,47 @@ pub const Document = struct {
@intCast(raster.stride),
@intCast(band.y),
@intCast(band.height),
- @intFromBool(transparent_paper),
) != 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.dpi,
+ bounded.minimum_width,
+ bounded.minimum_height,
+ bounded.max_dimension,
+ bounded.display_width,
+ bounded.display_height,
+ 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) };
+ }
+
const BoundedRequest = struct {
dpi: c_int,
minimum_width: c_int,
minimum_height: c_int,
max_dimension: c_int,
+ display_width: c_int,
+ display_height: c_int,
};
fn boundedRequest(
@@ -1045,28 +1078,13 @@ pub const Document = struct {
@as(u32, @intCast(std.math.maxInt(c_int))),
)),
.max_dimension = request.max_dimension,
+ .display_width = clampInt(request.display_width),
+ .display_height = clampInt(request.display_height),
};
}
- fn renderInternal(
- document: *Document,
- gpa: std.mem.Allocator,
- page: usize,
- request: RenderRequest,
- highlights: ?[]const Highlight,
- ) !Render {
- const raster = try document.measureRenderAt(page, request);
- const rgba = try gpa.alloc(u8, raster.len);
- errdefer gpa.free(rgba);
- try document.renderIntoAt(
- page,
- request,
- raster,
- raster.wholePage(),
- highlights orelse &.{},
- rgba,
- );
- return .{ .rgba = rgba, .width = raster.width, .height = raster.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
@@ -1098,7 +1116,7 @@ pub const Document = struct {
const page_number = try document.checkedPage(page);
if (std.mem.indexOfScalar(u8, needle, 0) != null)
return error.InvalidNeedle;
- const needle_z = try gpa.dupeZ(u8, needle);
+ const needle_z = try gpa.dupeSentinel(u8, needle, 0);
defer gpa.free(needle_z);
var found: c.pardes_pdf_search_result =
@@ -1227,7 +1245,7 @@ fn validQuad(quad: Quad) bool {
}
/// The exact shape of the raster a render request produces. `len` is the
-/// packed RGBA byte count a FULL-page `renderIntoAt` demands, so a caller can
+/// 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,
@@ -1285,29 +1303,13 @@ fn expectOpaque(rgba: []const u8) !void {
try std.testing.expectEqual(@as(u8, 0xff), rgba[alpha]);
}
-const generated_pdf_fragment_max = 256;
-
-const PdfBytes = struct {
- storage: ?[]u8 = null,
- len: usize = 0,
-
- fn appendSlice(bytes: *PdfBytes, source: []const u8) !void {
- const end = std.math.add(usize, bytes.len, source.len) catch
- return error.GeneratedPdfTooLarge;
- if (bytes.storage) |storage| {
- if (end > storage.len) return error.GeneratedPdfTooLarge;
- @memcpy(storage[bytes.len..end], source);
- }
- bytes.len = end;
- }
-
- fn print(bytes: *PdfBytes, comptime format: []const u8, args: anytype) !void {
- var fragment: [generated_pdf_fragment_max]u8 = undefined;
- const rendered = std.fmt.bufPrint(&fragment, format, args) catch
- return error.GeneratedPdfFragmentTooLong;
- try bytes.appendSlice(rendered);
- }
-};
+/// 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);
+}
fn allocateGeneratedPdf(
gpa: std.mem.Allocator,
@@ -1316,25 +1318,19 @@ fn allocateGeneratedPdf(
comptime emit: anytype,
) ![]u8 {
@memset(offsets, 0);
- var counter: PdfBytes = .{};
- try emit(&counter, offsets, context);
-
- const result = try gpa.alloc(u8, counter.len);
- errdefer gpa.free(result);
- @memset(offsets, 0);
- var bytes: PdfBytes = .{ .storage = result };
- try emit(&bytes, offsets, context);
- std.debug.assert(bytes.len == result.len);
- return result;
+ var bytes: std.Io.Writer.Allocating = .init(gpa);
+ defer bytes.deinit();
+ try emit(&bytes.writer, offsets, context);
+ return bytes.toOwnedSlice();
}
-fn beginPdfObject(bytes: *PdfBytes, offsets: []usize, number: usize) !void {
- offsets[number] = bytes.len;
+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: *PdfBytes, offsets: []const usize) !void {
- const xref = bytes.len;
+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});
@@ -1344,14 +1340,14 @@ fn finishGeneratedPdf(bytes: *PdfBytes, offsets: []const usize) !void {
);
}
-fn emitOffsetRotatedPdf(bytes: *PdfBytes, offsets: []usize, stream: []const u8) !void {
- try bytes.appendSlice("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
+fn emitOffsetRotatedPdf(bytes: *std.Io.Writer, offsets: []usize, stream: []const u8) !void {
+ try bytes.writeAll("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
try beginPdfObject(bytes, offsets, 1);
- try bytes.appendSlice("<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
try beginPdfObject(bytes, offsets, 2);
- try bytes.appendSlice("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 3);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [100 200 300 400] " ++
+ try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [100 200 300 400] " ++
"/CropBox [120 220 280 370] /Rotate 90 /Resources << >> " ++
"/Contents 4 0 R >>\nendobj\n");
try beginPdfObject(bytes, offsets, 4);
@@ -1365,33 +1361,33 @@ fn makeOffsetRotatedPdf(gpa: std.mem.Allocator) ![]u8 {
return allocateGeneratedPdf(gpa, &offsets, stream, emitOffsetRotatedPdf);
}
-fn emitOutlinePdf(bytes: *PdfBytes, offsets: []usize, _: void) !void {
- try bytes.appendSlice("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
+fn emitOutlinePdf(bytes: *std.Io.Writer, offsets: []usize, _: void) !void {
+ try bytes.writeAll("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
try beginPdfObject(bytes, offsets, 1);
- try bytes.appendSlice("<< /Type /Catalog /Pages 2 0 R /Outlines 7 0 R /PageMode /UseOutlines >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R /Outlines 7 0 R /PageMode /UseOutlines >>\nendobj\n");
try beginPdfObject(bytes, offsets, 2);
- try bytes.appendSlice("<< /Type /Pages /Count 3 /Kids [3 0 R 4 0 R 5 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Pages /Count 3 /Kids [3 0 R 4 0 R 5 0 R] >>\nendobj\n");
for (3..6) |page| {
try beginPdfObject(bytes, offsets, page);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << >> >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << >> >>\nendobj\n");
}
try beginPdfObject(bytes, offsets, 6);
- try bytes.appendSlice("<< >>\nendobj\n");
+ try bytes.writeAll("<< >>\nendobj\n");
try beginPdfObject(bytes, offsets, 7);
- try bytes.appendSlice("<< /Type /Outlines /First 8 0 R /Last 11 0 R /Count 4 >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Outlines /First 8 0 R /Last 11 0 R /Count 4 >>\nendobj\n");
// Destinationless branch with a deliberately missing /Title.
try beginPdfObject(bytes, offsets, 8);
- try bytes.appendSlice("<< /Parent 7 0 R /First 9 0 R /Last 9 0 R /Next 10 0 R /Count 1 >>\nendobj\n");
+ try bytes.writeAll("<< /Parent 7 0 R /First 9 0 R /Last 9 0 R /Next 10 0 R /Count 1 >>\nendobj\n");
// UTF-16BE "Café 子", with bold/italic + color metadata.
try beginPdfObject(bytes, offsets, 9);
- try bytes.appendSlice("<< /Title <FEFF00430061006600E900205B50> /Parent 8 0 R " ++
+ try bytes.writeAll("<< /Title <FEFF00430061006600E900205B50> /Parent 8 0 R " ++
"/Dest [4 0 R /XYZ 12 34 null] /F 3 /C [0.2 0.4 0.6] >>\nendobj\n");
// A present empty title and a destination with only one usable axis.
try beginPdfObject(bytes, offsets, 10);
- try bytes.appendSlice("<< /Title () /Parent 7 0 R /Prev 8 0 R /Next 11 0 R " ++
+ try bytes.writeAll("<< /Title () /Parent 7 0 R /Prev 8 0 R /Next 11 0 R " ++
"/Dest [5 0 R /FitH 70] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 11);
- try bytes.appendSlice("<< /Title (External) /Parent 7 0 R /Prev 10 0 R " ++
+ try bytes.writeAll("<< /Title (External) /Parent 7 0 R /Prev 10 0 R " ++
"/A << /S /URI /URI (https://example.com/manual) >> >>\nendobj\n");
try finishGeneratedPdf(bytes, offsets);
}
@@ -1413,31 +1409,31 @@ pub fn makeNoOutlineTestPdf(gpa: std.mem.Allocator) ![]u8 {
return makeOffsetRotatedPdf(gpa);
}
-fn emitLinksPdf(bytes: *PdfBytes, offsets: []usize, _: void) !void {
+fn emitLinksPdf(bytes: *std.Io.Writer, offsets: []usize, _: void) !void {
const stream = "BT /F1 6 Tf 20 240 Td (target.txt) Tj ET\n" ++
"BT /F1 6 Tf 20 120 Td (https://example.com/same) Tj ET\n" ++
"BT /F1 6 Tf 20 60 Td (label) Tj ET\n";
- try bytes.appendSlice("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
+ try bytes.writeAll("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
try beginPdfObject(bytes, offsets, 1);
- try bytes.appendSlice("<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
try beginPdfObject(bytes, offsets, 2);
- try bytes.appendSlice("<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 3);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << /Font << /F1 5 0 R >> >> /Contents 6 0 R /Annots [7 0 R 8 0 R 9 0 R 10 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << /Font << /F1 5 0 R >> >> /Contents 6 0 R /Annots [7 0 R 8 0 R 9 0 R 10 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 4);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << >> >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Resources << >> >>\nendobj\n");
try beginPdfObject(bytes, offsets, 5);
- try bytes.appendSlice("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n");
try beginPdfObject(bytes, offsets, 6);
try bytes.print("<< /Length {d} >>\nstream\n{s}endstream\nendobj\n", .{ stream.len, stream });
try beginPdfObject(bytes, offsets, 7);
- try bytes.appendSlice("<< /Type /Annot /Subtype /Link /Rect [20 230 120 260] /Border [0 0 0] /A << /S /URI /URI (https://example.com/embedded) >> >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Annot /Subtype /Link /Rect [20 230 120 260] /Border [0 0 0] /A << /S /URI /URI (https://example.com/embedded) >> >>\nendobj\n");
try beginPdfObject(bytes, offsets, 8);
- try bytes.appendSlice("<< /Type /Annot /Subtype /Link /Rect [20 170 120 200] /Border [0 0 0] /Dest [4 0 R /XYZ 12 34 null] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Annot /Subtype /Link /Rect [20 170 120 200] /Border [0 0 0] /Dest [4 0 R /XYZ 12 34 null] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 9);
- try bytes.appendSlice("<< /Type /Annot /Subtype /Link /Rect [20 110 190 140] /Border [0 0 0] /A << /S /URI /URI (https://example.com/same) >> >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Annot /Subtype /Link /Rect [20 110 190 140] /Border [0 0 0] /A << /S /URI /URI (https://example.com/same) >> >>\nendobj\n");
try beginPdfObject(bytes, offsets, 10);
- try bytes.appendSlice("<< /Type /Annot /Subtype /Link /Rect [20 50 120 80] /Border [0 0 0] /A << /S /URI /URI (https://example.com/only) >> >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Annot /Subtype /Link /Rect [20 50 120 80] /Border [0 0 0] /A << /S /URI /URI (https://example.com/only) >> >>\nendobj\n");
try finishGeneratedPdf(bytes, offsets);
}
@@ -1447,6 +1443,94 @@ pub fn makeLinksTestPdf(gpa: std.mem.Allocator) ![]u8 {
return allocateGeneratedPdf(gpa, &offsets, {}, emitLinksPdf);
}
+/// The tall test page: 600 x 9000 pt, fifteen A4 pages' height on one.
+pub const tall_test_page: PageSize = .{ .width = 600, .height = 9000 };
+
+fn emitTallPdf(bytes: *std.Io.Writer, offsets: []usize, _: void) !void {
+ // A labelled row every 100 pt, each with a slanting rule, so a band
+ // edge or a seam between chunks cuts through text and through lines.
+ var storage: [16 * 1024]u8 = undefined;
+ var stream: std.Io.Writer = .fixed(&storage);
+ var row: usize = 0;
+ while (row * 100 + 160 < 9000) : (row += 1) {
+ const y = 9000 - 60 - row * 100;
+ stream.print(
+ "BT /F1 28 Tf 40 {d} Td (Row {d}) Tj ET\n0.2 0.3 0.9 RG 3 w 20 {d} m 580 {d} l S\n",
+ .{ y, row, y - 20, y - 80 },
+ ) catch return error.GeneratedPdfTooLarge;
+ }
+ stream.writeAll("BT /F1 28 Tf 40 40 Td (bottommost) Tj ET\n") catch return error.GeneratedPdfTooLarge;
+ const content = stream.buffered();
+ 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 >>\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 600 9000] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>\nendobj\n");
+ try beginPdfObject(bytes, offsets, 4);
+ try bytes.print("<< /Length {d} >>\nstream\n", .{content.len});
+ try bytes.writeAll(content);
+ try bytes.writeAll("endstream\nendobj\n");
+ try beginPdfObject(bytes, offsets, 5);
+ try bytes.writeAll("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n");
+ try finishGeneratedPdf(bytes, offsets);
+}
+
+/// TEST-ONLY: one page fifteen times as tall as it is wide (`tall_test_page`),
+/// "Row N" every 100 pt from the top and "bottommost" at its foot.
+pub fn makeTallTestPdf(gpa: std.mem.Allocator) ![]u8 {
+ var offsets: [6]usize = undefined;
+ return allocateGeneratedPdf(gpa, &offsets, {}, emitTallPdf);
+}
+
+test "a tall page rasterizes at the size it is shown, however many max_dimensions tall" {
+ const bytes = try makeTallTestPdf(std.testing.allocator);
+ defer std.testing.allocator.free(bytes);
+ var document = try Document.openBytes(bytes);
+ 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);
@@ -1486,14 +1570,14 @@ test "PDF links own URIs across page eviction and preserve internal coordinates"
try std.testing.expect(try document.linkAt(gpa, 0, .{ .x = 0.99, .y = 0.99 }) == null);
}
-fn emitRotatedLinkPdf(bytes: *PdfBytes, offsets: []usize, action: []const u8) !void {
- try bytes.appendSlice("%PDF-1.7\n");
+fn emitRotatedLinkPdf(bytes: *std.Io.Writer, offsets: []usize, action: []const u8) !void {
+ try bytes.writeAll("%PDF-1.7\n");
try beginPdfObject(bytes, offsets, 1);
- try bytes.appendSlice("<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
try beginPdfObject(bytes, offsets, 2);
- try bytes.appendSlice("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 3);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [100 200 300 400] /CropBox [120 220 280 370] /Rotate 90 /Resources << >> /Annots [4 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Page /Parent 2 0 R /MediaBox [100 200 300 400] /CropBox [120 220 280 370] /Rotate 90 /Resources << >> /Annots [4 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 4);
try bytes.print("<< /Type /Annot /Subtype /Link /Rect [120 220 160 270] /Border [0 0 0] {s} >>\nendobj\n", .{action});
try finishGeneratedPdf(bytes, offsets);
@@ -1530,15 +1614,15 @@ test "PDF links normalize cropped rotated annotations and ignore unsupported act
}
}
-fn emitTooDeepOutlinePdf(bytes: *PdfBytes, offsets: []usize, levels: usize) !void {
+fn emitTooDeepOutlinePdf(bytes: *std.Io.Writer, offsets: []usize, levels: usize) !void {
const first_outline_item = 5;
- try bytes.appendSlice("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
+ try bytes.writeAll("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
try beginPdfObject(bytes, offsets, 1);
- try bytes.appendSlice("<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>\nendobj\n");
try beginPdfObject(bytes, offsets, 2);
- try bytes.appendSlice("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 3);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> >>\nendobj\n");
+ 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});
@@ -1556,7 +1640,7 @@ fn emitTooDeepOutlinePdf(bytes: *PdfBytes, offsets: []usize, levels: usize) !voi
levels - level - 1,
});
}
- try bytes.appendSlice(" >>\nendobj\n");
+ try bytes.writeAll(" >>\nendobj\n");
}
try finishGeneratedPdf(bytes, offsets);
}
@@ -1569,15 +1653,15 @@ fn makeTooDeepOutlinePdf(gpa: std.mem.Allocator) ![]u8 {
return allocateGeneratedPdf(gpa, offsets, levels, emitTooDeepOutlinePdf);
}
-fn emitWideOutlinePdf(bytes: *PdfBytes, offsets: []usize, items: usize) !void {
+fn emitWideOutlinePdf(bytes: *std.Io.Writer, offsets: []usize, items: usize) !void {
const first_outline_item = 5;
- try bytes.appendSlice("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
+ try bytes.writeAll("%PDF-1.7\n%\xE2\xE3\xCF\xD3\n");
try beginPdfObject(bytes, offsets, 1);
- try bytes.appendSlice("<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>\nendobj\n");
try beginPdfObject(bytes, offsets, 2);
- try bytes.appendSlice("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
+ try bytes.writeAll("<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
try beginPdfObject(bytes, offsets, 3);
- try bytes.appendSlice("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> >>\nendobj\n");
+ 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,
@@ -1592,7 +1676,7 @@ fn emitWideOutlinePdf(bytes: *PdfBytes, offsets: []usize, items: usize) !void {
try bytes.print(" /Prev {d} 0 R", .{number - 1});
if (ordinal + 1 < items)
try bytes.print(" /Next {d} 0 R", .{number + 1});
- try bytes.appendSlice(" >>\nendobj\n");
+ try bytes.writeAll(" >>\nendobj\n");
}
try finishGeneratedPdf(bytes, offsets);
}
@@ -1606,22 +1690,10 @@ fn makeWideOutlinePdf(gpa: std.mem.Allocator, items: usize) ![]u8 {
}
test "PDF outline is a stable owned DFS view with native destinations" {
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
const fixture = try makeOutlinePdf(std.testing.allocator);
defer std.testing.allocator.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{
- .sub_path = "outline.pdf",
- .data = fixture,
- });
- var path_buffer: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(
- &path_buffer,
- ".zig-cache/tmp/{s}/outline.pdf",
- .{tmp.sub_path},
- );
- var document = try Document.open(path);
+ var document = try Document.openBytes(fixture);
defer document.deinit();
try std.testing.expectEqual(@as(usize, 3), document.pages);
for (0..2) |fail_index| {
@@ -1674,21 +1746,9 @@ test "PDF outline accepts manual-sized trees and rejects item overflow atomicall
const manual_items = 4105;
try std.testing.expect(max_outline_items >= manual_items);
- var manual_tmp = std.testing.tmpDir(.{});
- defer manual_tmp.cleanup();
const manual_fixture = try makeWideOutlinePdf(std.testing.allocator, manual_items);
defer std.testing.allocator.free(manual_fixture);
- try manual_tmp.dir.writeFile(std.testing.io, .{
- .sub_path = "manual-outline.pdf",
- .data = manual_fixture,
- });
- var manual_path_buffer: [256]u8 = undefined;
- const manual_path = try std.fmt.bufPrint(
- &manual_path_buffer,
- ".zig-cache/tmp/{s}/manual-outline.pdf",
- .{manual_tmp.sub_path},
- );
- var manual_document = try Document.open(manual_path);
+ 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);
@@ -1697,21 +1757,9 @@ test "PDF outline accepts manual-sized trees and rejects item overflow atomicall
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);
- var overflow_tmp = std.testing.tmpDir(.{});
- defer overflow_tmp.cleanup();
const overflow_fixture = try makeWideOutlinePdf(std.testing.allocator, max_outline_items + 1);
defer std.testing.allocator.free(overflow_fixture);
- try overflow_tmp.dir.writeFile(std.testing.io, .{
- .sub_path = "overflow-outline.pdf",
- .data = overflow_fixture,
- });
- var overflow_path_buffer: [256]u8 = undefined;
- const overflow_path = try std.fmt.bufPrint(
- &overflow_path_buffer,
- ".zig-cache/tmp/{s}/overflow-outline.pdf",
- .{overflow_tmp.sub_path},
- );
- var overflow_document = try Document.open(overflow_path);
+ 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);
@@ -1727,42 +1775,18 @@ test "PDF outline accepts manual-sized trees and rejects item overflow atomicall
}
test "PDF outline absence and hostile depth are atomic and repeatable" {
- var plain_tmp = std.testing.tmpDir(.{});
- defer plain_tmp.cleanup();
const plain_fixture = try makeOffsetRotatedPdf(std.testing.allocator);
defer std.testing.allocator.free(plain_fixture);
- try plain_tmp.dir.writeFile(std.testing.io, .{
- .sub_path = "no-outline.pdf",
- .data = plain_fixture,
- });
- var plain_path_buffer: [256]u8 = undefined;
- const plain_path = try std.fmt.bufPrint(
- &plain_path_buffer,
- ".zig-cache/tmp/{s}/no-outline.pdf",
- .{plain_tmp.sub_path},
- );
- var plain_document = try Document.open(plain_path);
+ var plain_document = try Document.openBytes(plain_fixture);
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);
- var deep_tmp = std.testing.tmpDir(.{});
- defer deep_tmp.cleanup();
const deep_fixture = try makeTooDeepOutlinePdf(std.testing.allocator);
defer std.testing.allocator.free(deep_fixture);
- try deep_tmp.dir.writeFile(std.testing.io, .{
- .sub_path = "too-deep-outline.pdf",
- .data = deep_fixture,
- });
- var deep_path_buffer: [256]u8 = undefined;
- const deep_path = try std.fmt.bufPrint(
- &deep_path_buffer,
- ".zig-cache/tmp/{s}/too-deep-outline.pdf",
- .{deep_tmp.sub_path},
- );
- var deep_document = try Document.open(deep_path);
+ 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);
@@ -1805,7 +1829,7 @@ test "caller-owned RGBA layout is packed and overflow checked" {
}
test "RGBA allocation and buffer-validation failures leave the document renderable" {
- var document = try Document.open("docs/design.pdf");
+ var document = try openTestFile("docs/design.pdf");
defer document.deinit();
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{
@@ -1813,7 +1837,7 @@ test "RGBA allocation and buffer-validation failures leave the document renderab
});
try std.testing.expectError(
error.OutOfMemory,
- document.render(failing.allocator(), 0),
+ document.render(failing.allocator(), 0, .{}, &.{}),
);
var raw_layout: c.pardes_pdf_raster_layout = std.mem.zeroes(c.pardes_pdf_raster_layout);
@@ -1824,6 +1848,8 @@ test "RGBA allocation and buffer-validation failures leave the document renderab
default_render_request.minimum_width,
default_render_request.minimum_height,
default_render_request.max_dimension,
+ 0,
+ 0,
&raw_layout,
));
const layout = try checkedRasterLayout(raw_layout);
@@ -1838,6 +1864,8 @@ test "RGBA allocation and buffer-validation failures leave the document renderab
default_render_request.minimum_width,
default_render_request.minimum_height,
default_render_request.max_dimension,
+ 0,
+ 0,
null,
0,
scratch.ptr,
@@ -1853,9 +1881,9 @@ test "RGBA allocation and buffer-validation failures leave the document renderab
try std.testing.expectEqual(@as(u8, 0xa5), byte);
}
- const after = try document.render(std.testing.allocator, 0);
+ 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);
+ 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);
@@ -1868,14 +1896,14 @@ test "a band's rows are the full page's rows, and highlights land in them" {
// 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 Document.open("docs/design.pdf");
+ 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.renderIntoAt(0, request, raster, raster.wholePage(), &.{}, 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
@@ -1891,7 +1919,7 @@ test "a band's rows are the full page's rows, and highlights land in them" {
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.renderIntoAt(0, request, raster, band, &.{}, 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);
@@ -1911,11 +1939,11 @@ test "a band's rows are the full page's rows, and highlights land in them" {
}};
const marked_whole = try std.testing.allocator.alloc(u8, raster.len);
defer std.testing.allocator.free(marked_whole);
- try document.renderIntoAt(0, request, raster, raster.wholePage(), &highlights, 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.renderIntoAt(0, request, raster, marked_band, &highlights, 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,
@@ -1938,12 +1966,12 @@ test "a band's rows are the full page's rows, and highlights land in them" {
}
test "MuPDF search returns normalized oriented quads and word selection text" {
- var document = try Document.open("docs/design.pdf");
+ 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.indexOfIgnoreCase(projected, "Pardes") != null);
+ 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) {
@@ -1969,14 +1997,14 @@ test "MuPDF search returns normalized oriented quads and word selection text" {
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.indexOfIgnoreCase(text, "Pardes") != null);
+ try std.testing.expect(std.ascii.findIgnoreCase(text, "Pardes") != null);
}
test "highlighted render changes pixels while plain render stays stable" {
- var document = try Document.open("docs/design.pdf");
+ var document = try openTestFile("docs/design.pdf");
defer document.deinit();
- const plain_before = try document.render(std.testing.allocator, 0);
+ 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 },
@@ -1987,9 +2015,9 @@ test "highlighted render changes pixels while plain render stays stable" {
const highlights = [_]Highlight{
Highlight.init(whole_page, .{ 255, 0, 0, 128 }, .custom),
};
- const marked = try document.renderWithHighlights(std.testing.allocator, 0, &highlights);
+ 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);
+ const plain_after = try document.render(std.testing.allocator, 0, .{}, &.{});
defer std.testing.allocator.free(plain_after.rgba);
try expectOpaque(plain_before.rgba);
@@ -2002,24 +2030,12 @@ test "highlighted render changes pixels while plain render stays stable" {
}
test "offset crop and rotation keep normalized highlights pixel-aligned" {
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
const fixture = try makeOffsetRotatedPdf(std.testing.allocator);
defer std.testing.allocator.free(fixture);
- try tmp.dir.writeFile(std.testing.io, .{
- .sub_path = "offset-rotated.pdf",
- .data = fixture,
- });
- var path_buffer: [256]u8 = undefined;
- const path = try std.fmt.bufPrint(
- &path_buffer,
- ".zig-cache/tmp/{s}/offset-rotated.pdf",
- .{tmp.sub_path},
- );
- var document = try Document.open(path);
+ var document = try Document.openBytes(fixture);
defer document.deinit();
- const plain = try document.render(std.testing.allocator, 0);
+ 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);
@@ -2040,31 +2056,31 @@ test "offset crop and rotation keep normalized highlights pixel-aligned" {
0.001,
);
- const kitty = try document.renderAt(std.testing.allocator, 0, .{
+ 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.renderAt(std.testing.allocator, 0, .{
+ 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.renderAt(std.testing.allocator, 0, .{
+ 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));
@@ -2077,7 +2093,7 @@ test "offset crop and rotation keep normalized highlights pixel-aligned" {
const highlights = [_]Highlight{
Highlight.init(left_half, .{ 0, 0, 255, 255 }, .custom),
};
- const marked = try document.renderWithHighlights(std.testing.allocator, 0, &highlights);
+ 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);
@@ -2092,7 +2108,7 @@ test "offset crop and rotation keep normalized highlights pixel-aligned" {
}
test "transparent PDF paper preserves ink and band coverage" {
- var document = try Document.open("docs/9p.pdf");
+ 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);
@@ -2100,7 +2116,7 @@ test "transparent PDF paper preserves ink and band coverage" {
defer std.testing.allocator.free(flattened);
const content = try std.testing.allocator.alloc(u8, raster.len);
defer std.testing.allocator.free(content);
- try document.renderIntoAt(0, request, raster, raster.wholePage(), &.{}, flattened);
+ 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;