Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

perf(viewer): read each document once and reuse the open PDFium document (#8103)

briosb94bc286b7cc
diff --git a/frontend/editor/src/core/components/viewer/SignatureFieldOverlay.tsx b/frontend/editor/src/core/components/viewer/SignatureFieldOverlay.tsx
index 7f914741f3..ddc41a1e94 100644
--- a/frontend/editor/src/core/components/viewer/SignatureFieldOverlay.tsx
+++ b/frontend/editor/src/core/components/viewer/SignatureFieldOverlay.tsx
@@ -12,6 +12,9 @@
* PDF writer didn't embed one), we fall back to a translucent badge overlay.
*/
import { useStaleBakedFieldNames } from "@app/tools/formFill/FormFillContext";
+import { getDocumentBytes } from "@app/services/documentBytesCache";
+import { documentHasFormFields } from "@app/services/documentFormProbe";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
import React, { useEffect, useMemo, useRef, useState, memo } from "react";
import {
renderSignatureFieldAppearances,
@@ -50,11 +53,14 @@ async function resolveFields(
_cachedSource = source;
_cachePromise = (async () => {
- const buf = await source.arrayBuffer();
- const [appearances, signatures] = await Promise.all([
+ const buf = await getDocumentBytes(source);
+ if (!(await documentHasFormFields(buf, source.size))) return [];
+ // One main-thread scan at a time, so a second full document copy cannot
+ // be opened while this one runs.
+ const appearances = await runPdfiumScan(() =>
renderSignatureFieldAppearances(buf),
- extractSignatures(buf),
- ]);
+ );
+ const signatures = await runPdfiumScan(() => extractSignatures(buf));
return appearances.map((f, i) => {
// Positional correlation is only reliable when both arrays have the same
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.ts b/frontend/editor/src/core/contexts/file/lifecycle.ts
index 41416956c0..6c0eecb0d2 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.ts
@@ -3,6 +3,8 @@
*/
import { FileId } from "@app/types/file";
+import { releaseSharedDocumentWhenIdle } from "@app/services/pdfiumService";
+import { releaseDocumentBytes } from "@app/services/documentBytesCache";
import {
FileContextAction,
FileContextState,
@@ -26,7 +28,7 @@ export class FileLifecycleManager {
private fileGenerations = new Map<string, number>(); // Generation tokens to prevent stale cleanup
constructor(
- private filesRef: React.MutableRefObject<Map<FileId, File>>,
+ private filesRef: React.RefObject<Map<FileId, File>>,
private dispatch: React.Dispatch<FileContextAction>,
) {}
@@ -55,7 +57,7 @@ export class FileLifecycleManager {
*/
cleanupFile = (
fileId: FileId,
- stateRef?: React.MutableRefObject<FileContextState>,
+ stateRef?: React.RefObject<FileContextState>,
): void => {
forgetFile(fileId);
// Use comprehensive cleanup (same as removeFiles)
@@ -84,6 +86,9 @@ export class FileLifecycleManager {
this.cleanupTimers.clear();
this.fileGenerations.clear();
+ // No file survives teardown, so neither should its shared document.
+ releaseSharedDocumentWhenIdle();
+
// Clear files ref
this.filesRef.current.clear();
};
@@ -94,7 +99,7 @@ export class FileLifecycleManager {
scheduleCleanup = (
fileId: FileId,
delay: number = 30000,
- stateRef?: React.MutableRefObject<FileContextState>,
+ stateRef?: React.RefObject<FileContextState>,
): void => {
// Cancel existing timer
const existingTimer = this.cleanupTimers.get(fileId);
@@ -133,7 +138,7 @@ export class FileLifecycleManager {
*/
removeFiles = (
fileIds: FileId[],
- stateRef?: React.MutableRefObject<FileContextState>,
+ stateRef?: React.RefObject<FileContextState>,
): void => {
fileIds.forEach((fileId) => {
forgetFile(fileId);
@@ -150,9 +155,9 @@ export class FileLifecycleManager {
*/
private cleanupAllResourcesForFile = (
fileId: FileId,
- stateRef?: React.MutableRefObject<FileContextState>,
+ stateRef?: React.RefObject<FileContextState>,
): void => {
- // Remove from files ref
+ const file = this.filesRef.current.get(fileId);
this.filesRef.current.delete(fileId);
// Cancel cleanup timer and generation
@@ -163,6 +168,12 @@ export class FileLifecycleManager {
}
this.fileGenerations.delete(fileId);
+ // A scan queued before this removal can still open the document, so the
+ // release runs behind the queue. The byte cache entry is keyed by the file
+ // and cannot be reused once it leaves the workbench.
+ releaseSharedDocumentWhenIdle();
+ if (file) releaseDocumentBytes(file);
+
// Clean up blob URLs from file record if we have access to state
if (stateRef) {
const record = stateRef.current.files.byId[fileId];
@@ -188,7 +199,7 @@ export class FileLifecycleManager {
updateStirlingFileStub = (
fileId: FileId,
updates: Partial<StirlingFileStub>,
- stateRef?: React.MutableRefObject<FileContextState>,
+ stateRef?: React.RefObject<FileContextState>,
): void => {
// Guard against updating removed files (race condition protection)
if (!this.filesRef.current.has(fileId)) {
diff --git a/frontend/editor/src/core/hooks/useMeasurementManager.ts b/frontend/editor/src/core/hooks/useMeasurementManager.ts
index f6f6b9d6b1..2cfd465c65 100644
--- a/frontend/editor/src/core/hooks/useMeasurementManager.ts
+++ b/frontend/editor/src/core/hooks/useMeasurementManager.ts
@@ -228,7 +228,7 @@ export function useMeasurementManager({
useEffect(() => {
const fileBlob = effectiveFile?.file;
- if (!fileBlob || !currentFileKey) {
+ if (!fileBlob || !currentFileKey || !isRulerActive) {
setPageMeasureScales(null);
return;
}
@@ -252,7 +252,7 @@ export function useMeasurementManager({
return () => {
cancelled = true;
};
- }, [currentFileKey, effectiveFile?.file]);
+ }, [currentFileKey, effectiveFile?.file, isRulerActive]);
useEffect(() => {
if (!rulerOverlayRef.current || !currentFileKey) return;
diff --git a/frontend/editor/src/core/hooks/useThumbnailGeneration.ts b/frontend/editor/src/core/hooks/useThumbnailGeneration.ts
index 13710acc1b..cf2393b3f5 100644
--- a/frontend/editor/src/core/hooks/useThumbnailGeneration.ts
+++ b/frontend/editor/src/core/hooks/useThumbnailGeneration.ts
@@ -3,6 +3,7 @@ import {
thumbnailGenerationService,
type ThumbnailResult,
} from "@app/services/thumbnailGenerationService";
+import { getDocumentBytes } from "@app/services/documentBytesCache";
import { createQuickKey } from "@app/types/fileContext";
import { FileId } from "@app/types/file";
@@ -23,9 +24,6 @@ let batchTimer: number | null = null;
// Track active thumbnail requests to prevent duplicates across components
const activeRequests = new Map<string, Promise<string | null>>();
-// Cache ArrayBuffers to avoid reading the same file multiple times
-const fileArrayBufferCache = new Map<File, ArrayBuffer>();
-
// Batch processing configuration
const BATCH_SIZE = 10; // Process thumbnails in batches of 10 for faster initial load
const BATCH_DELAY = 50; // Wait 50ms to collect requests before processing
@@ -77,12 +75,8 @@ async function processRequestQueue() {
try {
const pageNumbers = requests.map((req) => req.pageNumber);
- // Get or create cached ArrayBuffer to avoid reading file multiple times
- let arrayBuffer = fileArrayBufferCache.get(file);
- if (!arrayBuffer) {
- arrayBuffer = await file.arrayBuffer();
- fileArrayBufferCache.set(file, arrayBuffer);
- }
+ // Share the cached buffer instead of minting a second copy.
+ const arrayBuffer = await getDocumentBytes(file);
// Use quickKey for PDF document caching (same metadata, consistent format)
const fileId = createQuickKey(file) as FileId;
@@ -126,10 +120,6 @@ async function processRequestQueue() {
}
} finally {
isProcessingQueue = false;
- // Clean up ArrayBuffer cache when queue is empty
- if (requestQueue.length === 0) {
- fileArrayBufferCache.clear();
- }
}
}
@@ -197,9 +187,6 @@ export function useThumbnailGeneration() {
activeRequests.clear();
isProcessingQueue = false;
- // Clear ArrayBuffer cache
- fileArrayBufferCache.clear();
-
thumbnailGenerationService.destroy();
}, []);
diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsx
index 0019ff4a5e..4c35262e32 100644
--- a/frontend/editor/src/core/pages/HomePage.tsx
+++ b/frontend/editor/src/core/pages/HomePage.tsx
@@ -467,8 +467,16 @@ export default function HomePage() {
};
}, [isMobile, dismissSwipeHint]);
+ // Full-screen tools own the mobile viewport, so opening one selects the
+ // workbench slide. The text editor is included because it manages its own
+ // state instead of going through the startup-navigation heuristic.
useEffect(() => {
- if (isMobile && (readerMode || selectedToolKey === "multiTool")) {
+ if (
+ isMobile &&
+ (readerMode ||
+ selectedToolKey === "multiTool" ||
+ selectedToolKey === "pdfTextEditor")
+ ) {
setActiveMobileView("workbench");
}
}, [isMobile, readerMode, selectedToolKey]);
diff --git a/frontend/editor/src/core/services/documentBytesCache.test.ts b/frontend/editor/src/core/services/documentBytesCache.test.ts
new file mode 100644
index 0000000000..d8a6e7a257
--- /dev/null
+++ b/frontend/editor/src/core/services/documentBytesCache.test.ts
@@ -0,0 +1,120 @@
+/** Contract of the shared document-bytes cache: one read per live Blob (or per
+ * identical File wrapper), concurrent callers share it, a failed read is
+ * retryable, and `releaseDocumentBytes` drops the entry. Each Blob's
+ * `arrayBuffer` is stubbed with the bytes it stands for, so the assertions do
+ * not depend on the global jsdom Blob mock. */
+import { describe, expect, it, vi } from "vitest";
+import {
+ getDocumentBytes,
+ releaseDocumentBytes,
+} from "@app/services/documentBytesCache";
+
+const bytesOf = (bytes: number[]): ArrayBuffer => new Uint8Array(bytes).buffer;
+
+const makeFile = (name: string, bytes: number[], lastModified = 1000) =>
+ new File([new Uint8Array(bytes)], name, {
+ type: "application/pdf",
+ lastModified,
+ });
+
+describe("documentBytesCache", () => {
+ it("serves one read per live Blob and returns the same bytes", async () => {
+ const blob = new Blob([new Uint8Array([1, 2, 3])]);
+ const spy = vi
+ .spyOn(blob, "arrayBuffer")
+ .mockResolvedValue(bytesOf([1, 2, 3]));
+
+ const first = await getDocumentBytes(blob);
+ const second = await getDocumentBytes(blob);
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(second).toBe(first);
+ expect(Array.from(new Uint8Array(first))).toEqual([1, 2, 3]);
+ });
+
+ it("deduplicates concurrent reads", async () => {
+ const blob = new Blob([new Uint8Array([9])]);
+ const spy = vi.spyOn(blob, "arrayBuffer").mockResolvedValue(bytesOf([9]));
+
+ const [a, b] = await Promise.all([
+ getDocumentBytes(blob),
+ getDocumentBytes(blob),
+ ]);
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(a).toBe(b);
+ });
+
+ it("shares one read across File wrappers with identical metadata", async () => {
+ const first = makeFile("wrapped-once.pdf", [1, 2, 3]);
+ const second = makeFile("wrapped-once.pdf", [1, 2, 3]);
+ const firstSpy = vi
+ .spyOn(first, "arrayBuffer")
+ .mockResolvedValue(bytesOf([1, 2, 3]));
+ const secondSpy = vi
+ .spyOn(second, "arrayBuffer")
+ .mockResolvedValue(bytesOf([1, 2, 3]));
+
+ const [a, b] = await Promise.all([
+ getDocumentBytes(first),
+ getDocumentBytes(second),
+ ]);
+
+ expect(a).toBe(b);
+ expect(firstSpy.mock.calls.length + secondSpy.mock.calls.length).toBe(1);
+ });
+
+ it("re-reads when a File's metadata changes", async () => {
+ const original = makeFile("mtime.pdf", [1, 2, 3], 1000);
+ const edited = makeFile("mtime.pdf", [4, 5, 6], 2000);
+ vi.spyOn(original, "arrayBuffer").mockResolvedValue(bytesOf([1, 2, 3]));
+ vi.spyOn(edited, "arrayBuffer").mockResolvedValue(bytesOf([4, 5, 6]));
+
+ const a = await getDocumentBytes(original);
+ const b = await getDocumentBytes(edited);
+
+ expect(b).not.toBe(a);
+ expect(Array.from(new Uint8Array(b))).toEqual([4, 5, 6]);
+ });
+
+ it("keeps bare Blobs identity-keyed (size alone must not share)", async () => {
+ const a = new Blob([new Uint8Array([1, 2, 3])]);
+ const b = new Blob([new Uint8Array([4, 5, 6])]);
+ vi.spyOn(a, "arrayBuffer").mockResolvedValue(bytesOf([1, 2, 3]));
+ vi.spyOn(b, "arrayBuffer").mockResolvedValue(bytesOf([4, 5, 6]));
+
+ const first = await getDocumentBytes(a);
+ const second = await getDocumentBytes(b);
+
+ expect(second).not.toBe(first);
+ expect(Array.from(new Uint8Array(second))).toEqual([4, 5, 6]);
+ });
+
+ it("re-reads after releaseDocumentBytes", async () => {
+ const file = makeFile("released.pdf", [7, 8, 9]);
+ const spy = vi
+ .spyOn(file, "arrayBuffer")
+ .mockImplementation(() => Promise.resolve(bytesOf([7, 8, 9])));
+
+ const first = await getDocumentBytes(file);
+ releaseDocumentBytes(file);
+ const second = await getDocumentBytes(file);
+
+ expect(spy).toHaveBeenCalledTimes(2);
+ expect(Array.from(new Uint8Array(second))).toEqual([7, 8, 9]);
+ expect(second).not.toBe(first);
+ });
+
+ it("does not cache a failed read, so a retry re-reads", async () => {
+ const blob = new Blob([new Uint8Array([1])]);
+ const spy = vi
+ .spyOn(blob, "arrayBuffer")
+ .mockRejectedValueOnce(new Error("nope"))
+ .mockResolvedValue(bytesOf([1]));
+
+ await expect(getDocumentBytes(blob)).rejects.toThrow("nope");
+ const buffer = await getDocumentBytes(blob);
+ expect(buffer.byteLength).toBe(1);
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/editor/src/core/services/documentBytesCache.ts b/frontend/editor/src/core/services/documentBytesCache.ts
new file mode 100644
index 0000000000..838e3dbdc3
--- /dev/null
+++ b/frontend/editor/src/core/services/documentBytesCache.ts
@@ -0,0 +1,93 @@
+/**
+ * One ArrayBuffer per document, shared by the viewer's scans (form fields,
+ * signature/button appearances, measurement scales).
+ *
+ * Callers must not detach the returned buffer: pdf.js transfers whatever it is
+ * given, so anything that hands bytes to pdf.js has to pass a URL instead.
+ *
+ * The buffer is held weakly: a File record pinned by unrelated state (stale
+ * React fibers, sidebar metadata) must not keep the whole document resident.
+ * Callers that need the bytes hold the buffer they were handed; once nothing
+ * does, the next call re-reads the Blob.
+ *
+ * Files are also keyed by name/size/type/mtime: the add path re-wraps the same
+ * bytes as fresh `File` objects, so identity alone would read every document
+ * once per wrapper. Bare Blobs stay identity-keyed, since they carry no metadata.
+ */
+const resolved = new WeakMap<Blob, WeakRef<ArrayBuffer>>();
+const pending = new WeakMap<Blob, Promise<ArrayBuffer>>();
+const FILE_KEY_CACHE_LIMIT = 64;
+const resolvedByFileKey = new Map<
+ string,
+ { ref: WeakRef<ArrayBuffer>; size: number }
+>();
+const pendingByFileKey = new Map<string, Promise<ArrayBuffer>>();
+
+function fileKey(blob: Blob): string | null {
+ if (!(blob instanceof File)) return null;
+ return `${blob.name}\u0000${blob.size}\u0000${blob.type}\u0000${blob.lastModified}`;
+}
+
+function rememberFileKey(key: string, buffer: ArrayBuffer): void {
+ resolvedByFileKey.delete(key);
+ resolvedByFileKey.set(key, {
+ ref: new WeakRef(buffer),
+ size: buffer.byteLength,
+ });
+ while (resolvedByFileKey.size > FILE_KEY_CACHE_LIMIT) {
+ const oldest = resolvedByFileKey.keys().next().value;
+ if (oldest === undefined) break;
+ resolvedByFileKey.delete(oldest);
+ }
+}
+
+/** Drops the cached entry, e.g. for a large document whose worker copy is up. */
+export function releaseDocumentBytes(blob: Blob): void {
+ resolved.delete(blob);
+ pending.delete(blob);
+ const key = fileKey(blob);
+ if (key) {
+ resolvedByFileKey.delete(key);
+ pendingByFileKey.delete(key);
+ }
+}
+
+export function getDocumentBytes(blob: Blob): Promise<ArrayBuffer> {
+ const alive = resolved.get(blob)?.deref();
+ if (alive) return Promise.resolve(alive);
+
+ const key = fileKey(blob);
+ if (key) {
+ const shared = resolvedByFileKey.get(key);
+ if (shared && shared.size === blob.size) {
+ const buffer = shared.ref.deref();
+ if (buffer) return Promise.resolve(buffer);
+ resolvedByFileKey.delete(key);
+ }
+ const inFlight = pendingByFileKey.get(key);
+ if (inFlight) return inFlight;
+ }
+
+ const inFlight = pending.get(blob);
+ if (inFlight) return inFlight;
+
+ const reading = blob.arrayBuffer().then(
+ (buffer) => {
+ resolved.set(blob, new WeakRef(buffer));
+ if (key) {
+ rememberFileKey(key, buffer);
+ pendingByFileKey.delete(key);
+ }
+ pending.delete(blob);
+ return buffer;
+ },
+ (error: unknown) => {
+ pending.delete(blob);
+ if (key) pendingByFileKey.delete(key);
+ throw error;
+ },
+ );
+ pending.set(blob, reading);
+ if (key) pendingByFileKey.set(key, reading);
+ return reading;
+}
diff --git a/frontend/editor/src/core/services/documentFormProbe.test.ts b/frontend/editor/src/core/services/documentFormProbe.test.ts
new file mode 100644
index 0000000000..7f5db049e2
--- /dev/null
+++ b/frontend/editor/src/core/services/documentFormProbe.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import type { Mock } from "vitest";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+
+vi.mock("@app/services/pdfiumScanQueue", () => ({
+ runPdfiumScan: (task: () => Promise<unknown>) => task(),
+}));
+
+vi.mock("@app/services/pdfiumService", () => ({
+ readRawFormType: vi.fn(async () => 0),
+}));
+
+import { documentHasFormFields } from "@app/services/documentFormProbe";
+import { readRawFormType } from "@app/services/pdfiumService";
+import { hasAcroForm } from "@app/utils/asciiBytes";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
+
+// Copy into a jsdom-realm ArrayBuffer; pdf-lib rejects a Node-realm one.
+const fixtureBytes = (name: string): ArrayBuffer =>
+ new Uint8Array(
+ readFileSync(
+ path.join(import.meta.dirname, "../tests/test-fixtures", name),
+ ),
+ ).buffer;
+
+describe("documentHasFormFields", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (readRawFormType as Mock).mockResolvedValue(0);
+ });
+
+ it("finds a compressed-catalog form the literal scan misses", async () => {
+ const bytes = fixtureBytes("form-compressed-catalog.pdf");
+ expect(hasAcroForm(new Uint8Array(bytes))).toBe(false);
+
+ expect(await documentHasFormFields(bytes)).toBe(true);
+ });
+
+ it("returns false for a form-less document", async () => {
+ expect(await documentHasFormFields(fixtureBytes("big-sample.pdf"))).toBe(
+ false,
+ );
+ });
+
+ it("falls back to PDFium when pdf-lib cannot parse the file", async () => {
+ const pdfLib = await import("@cantoo/pdf-lib");
+ const load = vi
+ .spyOn(pdfLib.PDFDocument, "load")
+ .mockRejectedValueOnce(new Error("unparseable"));
+ const bytes = new TextEncoder().encode("%PDF-1.7").buffer;
+ (readRawFormType as Mock).mockResolvedValue(1);
+
+ expect(await documentHasFormFields(bytes)).toBe(true);
+ expect(readRawFormType).toHaveBeenCalledTimes(1);
+ load.mockRestore();
+ });
+
+ it("treats an unknown form type as a possible form", async () => {
+ const pdfLib = await import("@cantoo/pdf-lib");
+ const load = vi
+ .spyOn(pdfLib.PDFDocument, "load")
+ .mockRejectedValueOnce(new Error("unparseable"));
+ const bytes = new TextEncoder().encode("%PDF-1.7").buffer;
+ (readRawFormType as Mock).mockResolvedValue(null);
+
+ expect(await documentHasFormFields(bytes)).toBe(true);
+ load.mockRestore();
+ });
+
+ it("does not open a large unparseable file in PDFium", async () => {
+ const pdfLib = await import("@cantoo/pdf-lib");
+ const load = vi
+ .spyOn(pdfLib.PDFDocument, "load")
+ .mockRejectedValueOnce(new Error("unparseable"));
+ const bytes = new TextEncoder().encode("%PDF-1.7").buffer;
+
+ expect(await documentHasFormFields(bytes, LARGE_PDF_PARSE_LIMIT)).toBe(
+ false,
+ );
+ expect(readRawFormType).not.toHaveBeenCalled();
+ load.mockRestore();
+ });
+});
diff --git a/frontend/editor/src/core/services/documentFormProbe.ts b/frontend/editor/src/core/services/documentFormProbe.ts
new file mode 100644
index 0000000000..1d3a257068
--- /dev/null
+++ b/frontend/editor/src/core/services/documentFormProbe.ts
@@ -0,0 +1,38 @@
+import { hasAcroForm } from "@app/utils/asciiBytes";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
+import { readRawFormType } from "@app/services/pdfiumService";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
+
+/**
+ * True when the document may contain interactive form fields.
+ *
+ * The literal byte scan is a hint, not proof: /AcroForm can live inside a
+ * compressed object stream, which the raw bytes never spell out. pdf-lib parses
+ * the xref and catalog (object streams included) without copying the file into
+ * wasm, and measured flat memory at 6 ms on a 155 MB file, so it confirms every
+ * size. pdf-lib rejects some shapes PDFium opens, so those fall back to PDFium's
+ * catalog probe when the file is small enough to open on the main thread. A file
+ * neither can parse has no form UI to show either way.
+ */
+export async function documentHasFormFields(
+ bytes: ArrayBuffer,
+ byteLength: number = bytes.byteLength,
+): Promise<boolean> {
+ if (hasAcroForm(new Uint8Array(bytes))) return true;
+ try {
+ const { PDFDocument, PDFName } = await import("@cantoo/pdf-lib");
+ const doc = await PDFDocument.load(bytes, {
+ ignoreEncryption: true,
+ updateMetadata: false,
+ });
+ return doc.catalog.get(PDFName.of("AcroForm")) !== undefined;
+ } catch {
+ if (byteLength >= LARGE_PDF_PARSE_LIMIT) return false;
+ try {
+ const formType = await runPdfiumScan(() => readRawFormType(bytes));
+ return formType === null ? true : formType !== 0;
+ } catch {
+ return false;
+ }
+ }
+}
diff --git a/frontend/editor/src/core/services/pdfiumScanQueue.test.ts b/frontend/editor/src/core/services/pdfiumScanQueue.test.ts
new file mode 100644
index 0000000000..1d5646405a
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfiumScanQueue.test.ts
@@ -0,0 +1,46 @@
+/**
+ * Serialization contract of the main-thread PDFium scan queue: scans run in
+ * submission order and one failing scan does not wedge the queue.
+ */
+import { describe, expect, it } from "vitest";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
+
+describe("pdfiumScanQueue", () => {
+ it("runs queued scans in submission order", async () => {
+ const order: string[] = [];
+ const a = runPdfiumScan(async () => {
+ await Promise.resolve();
+ order.push("a");
+ });
+ const b = runPdfiumScan(async () => {
+ order.push("b");
+ });
+ await Promise.all([a, b]);
+ expect(order).toEqual(["a", "b"]);
+ });
+
+ it("runs the next scan after a failure and surfaces the failure to its caller", async () => {
+ const order: string[] = [];
+ let rejectFirst!: (reason?: unknown) => void;
+ const failing = runPdfiumScan(
+ () =>
+ new Promise<void>((_resolve, reject) => {
+ rejectFirst = reject;
+ order.push("a");
+ }),
+ );
+ const next = runPdfiumScan(async () => {
+ order.push("b");
+ });
+
+ // Flush every pending microtask: a queue that starts the next scan before
+ // the failing one settles would have pushed "b" by now.
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(order).toEqual(["a"]);
+ rejectFirst(new Error("boom"));
+
+ await expect(failing).rejects.toThrow("boom");
+ await next;
+ expect(order).toEqual(["a", "b"]);
+ });
+});
diff --git a/frontend/editor/src/core/services/pdfiumScanQueue.ts b/frontend/editor/src/core/services/pdfiumScanQueue.ts
new file mode 100644
index 0000000000..84443b4c8b
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfiumScanQueue.ts
@@ -0,0 +1,14 @@
+/**
+ * Serializes main-thread PDFium scans.
+ *
+ * PDFium is single-threaded and wasm memory never shrinks. Two scans of
+ * different documents would each open a full copy in the heap and leave the
+ * sum as the high-water mark, so scans run in submission order.
+ */
+let tail: Promise<unknown> = Promise.resolve();
+
+export function runPdfiumScan<T>(task: () => Promise<T>): Promise<T> {
+ const run = tail.then(task, task);
+ tail = run.catch(() => undefined);
+ return run;
+}
diff --git a/frontend/editor/src/core/services/pdfiumService.sharedDocument.test.ts b/frontend/editor/src/core/services/pdfiumService.sharedDocument.test.ts
new file mode 100644
index 0000000000..b48a7945b8
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfiumService.sharedDocument.test.ts
@@ -0,0 +1,196 @@
+/**
+ * Shared main-thread document lifecycle (openRawDocument / closeDocAndFreeBuffer /
+ * releaseSharedDocument / resetPdfiumModule), exercised against a fake
+ * @embedpdf/pdfium module so the pointer state machine is covered without WASM.
+ */
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+
+const pdfium = vi.hoisted(() => {
+ const state = {
+ module: null as Record<string, unknown> | null,
+ closeCalls: [] as number[],
+ freeCalls: [] as number[],
+ allocationOrder: [] as string[],
+ nextDocPtr: 1000,
+ nextDataPtr: 5000,
+ };
+ const makeModule = () => {
+ const heap = new Uint8Array(1 << 20);
+ state.closeCalls = [];
+ state.freeCalls = [];
+ state.allocationOrder = [];
+ const module = {
+ PDFiumExt_Init: vi.fn(),
+ FPDF_LoadMemDocument: vi.fn(() => ++state.nextDocPtr),
+ FPDF_CloseDocument: vi.fn((p: number) => state.closeCalls.push(p)),
+ FPDF_GetLastError: vi.fn(() => 0),
+ pdfium: {
+ wasmExports: {
+ malloc: vi.fn(() => {
+ state.allocationOrder.push("malloc");
+ return (state.nextDataPtr += 1 << 16);
+ }),
+ free: vi.fn((p: number) => {
+ state.allocationOrder.push("free");
+ state.freeCalls.push(p);
+ }),
+ },
+ HEAPU8: heap,
+ },
+ };
+ state.module = module;
+ return module;
+ };
+ makeModule();
+ return { state, makeModule };
+});
+
+vi.mock("@embedpdf/pdfium", () => ({
+ init: vi.fn(async () => pdfium.makeModule()),
+}));
+
+vi.mock("@app/services/wasmPrecompiler", () => ({
+ pdfiumWasmModulePromise: Promise.resolve(null),
+ startEagerWasmCompilation: vi.fn(),
+ pdfiumWasmUrl: "mem://pdfium-test.wasm",
+}));
+
+import {
+ closeDocAndFreeBuffer,
+ getPdfiumModule,
+ openRawDocumentSafe,
+ releaseSharedDocument,
+ releaseSharedDocumentWhenIdle,
+ resetPdfiumModule,
+} from "@app/services/pdfiumService";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
+
+const closeCalls = () => pdfium.state.closeCalls;
+const freeCalls = () => pdfium.state.freeCalls;
+
+describe("shared document lifecycle", () => {
+ beforeEach(async () => {
+ pdfium.makeModule();
+ resetPdfiumModule();
+ await getPdfiumModule();
+ });
+
+ afterEach(() => {
+ resetPdfiumModule();
+ });
+
+ it("shares one open across readers; the handle lingers at zero refs until release", async () => {
+ const data = new ArrayBuffer(16);
+ const doc1 = await openRawDocumentSafe(data);
+ const doc2 = await openRawDocumentSafe(data);
+ expect(doc2).toBe(doc1);
+
+ const m = await getPdfiumModule();
+ closeDocAndFreeBuffer(m, doc2);
+ closeDocAndFreeBuffer(m, doc1);
+ expect(closeCalls()).toEqual([]);
+
+ releaseSharedDocument();
+ expect(closeCalls()).toEqual([doc1]);
+ expect(freeCalls().length).toBe(1);
+ });
+
+ it("release with an active reader defers the close to the last reader", async () => {
+ const data = new ArrayBuffer(16);
+ const doc = await openRawDocumentSafe(data);
+ await openRawDocumentSafe(data);
+
+ releaseSharedDocument();
+ expect(closeCalls()).toEqual([]);
+
+ const m = await getPdfiumModule();
+ closeDocAndFreeBuffer(m, doc);
+ expect(closeCalls()).toEqual([]);
+
+ closeDocAndFreeBuffer(m, doc);
+ expect(closeCalls()).toEqual([doc]);
+ });
+
+ it("release with no readers closes immediately", async () => {
+ const data = new ArrayBuffer(16);
+ const doc = await openRawDocumentSafe(data);
+ const m = await getPdfiumModule();
+ closeDocAndFreeBuffer(m, doc);
+ expect(closeCalls()).toEqual([]);
+
+ releaseSharedDocument();
+ expect(closeCalls()).toEqual([doc]);
+ });
+
+ it("a stale close on a lingering zero-ref handle does not double-close", async () => {
+ const data = new ArrayBuffer(16);
+ const doc = await openRawDocumentSafe(data);
+ const m = await getPdfiumModule();
+ closeDocAndFreeBuffer(m, doc);
+ expect(closeCalls()).toEqual([]);
+
+ closeDocAndFreeBuffer(m, doc);
+ expect(closeCalls()).toEqual([]);
+ expect(freeCalls().length).toBe(0);
+
+ // The lingering handle still serves the next same-bytes open.
+ const doc2 = await openRawDocumentSafe(data);
+ expect(doc2).toBe(doc);
+ });
+
+ it("reset with an active reader drops the handle and the reader's close closes once", async () => {
+ const data = new ArrayBuffer(16);
+ const doc = await openRawDocumentSafe(data);
+
+ resetPdfiumModule();
+ expect(closeCalls()).toEqual([]);
+
+ closeDocAndFreeBuffer(await getPdfiumModule(), doc);
+ expect(closeCalls()).toEqual([doc]);
+ // The reader re-fetches the module after the reset, so the close must
+ // still free the buffer in the heap that allocated it.
+ expect(freeCalls()).toHaveLength(1);
+ });
+
+ it("closes an idle shared handle before allocating its replacement", async () => {
+ const dataA = new ArrayBuffer(16);
+ const dataB = new ArrayBuffer(24);
+ const docA = await openRawDocumentSafe(dataA);
+ closeDocAndFreeBuffer(await getPdfiumModule(), docA);
+ pdfium.state.allocationOrder = [];
+
+ await openRawDocumentSafe(dataB);
+
+ // A's buffer is freed before B's allocation, so the two never coexist.
+ expect(pdfium.state.allocationOrder).toEqual(["free", "malloc"]);
+ });
+
+ it("queues the release behind a scan so a late open cannot linger", async () => {
+ const data = new ArrayBuffer(16);
+ const scan = runPdfiumScan(async () => {
+ const doc = await openRawDocumentSafe(data);
+ await Promise.resolve();
+ closeDocAndFreeBuffer(await getPdfiumModule(), doc);
+ });
+ // The file left the workbench while the scan was queued.
+ releaseSharedDocumentWhenIdle();
+ await scan;
+ await runPdfiumScan(async () => undefined);
+
+ expect(closeCalls()).toHaveLength(1);
+ });
+
+ it("open with different bytes closes a zero-ref shared handle and clears a pending release", async () => {
+ const dataA = new ArrayBuffer(16);
+ const dataB = new ArrayBuffer(24);
+ const docA = await openRawDocumentSafe(dataA);
+ const m = await getPdfiumModule();
+ closeDocAndFreeBuffer(m, docA);
+
+ await openRawDocumentSafe(dataB);
+ expect(closeCalls()).toEqual([docA]);
+
+ await openRawDocumentSafe(dataA);
+ expect(closeCalls()).toEqual([docA]);
+ });
+});
diff --git a/frontend/editor/src/core/services/pdfiumService.ts b/frontend/editor/src/core/services/pdfiumService.ts
index 01ecbbca10..de289cf8f7 100644
--- a/frontend/editor/src/core/services/pdfiumService.ts
+++ b/frontend/editor/src/core/services/pdfiumService.ts
@@ -22,6 +22,7 @@ import {
startEagerWasmCompilation,
pdfiumWasmUrl,
} from "@app/services/wasmPrecompiler";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
import type { FormField, WidgetCoordinates } from "@app/tools/formFill/types";
export interface ExtendedPdfiumRuntime {
@@ -143,17 +144,34 @@ export async function getPdfiumModule(): Promise<WrappedPdfiumModule> {
* Next call to getPdfiumModule() will create a fresh instance.
*/
export function resetPdfiumModule(): void {
+ // The module is discarded here, so a handle no reader holds is closed now.
+ // A handle a reader still holds is left to that reader: its close frees the
+ // data buffer against the module it captured.
+ try {
+ if (sharedDocument && sharedDocument.refs <= 0 && _module) {
+ closeDocumentNow(_module, sharedDocument.docPtr);
+ }
+ } catch {
+ // Module already unusable; dropping the references is the cleanup.
+ }
+ sharedDocument = null;
+ sharedReleasePending = false;
_module = null;
_initPromise = null;
- _docDataPtrs.clear();
}
/**
- * Map of document pointer → WASM data buffer pointer.
+ * Map of document pointer → its WASM data buffer and the module that owns it.
* FPDF_LoadMemDocument does NOT copy the data — it keeps a reference, so the
- * buffer must stay alive until FPDF_CloseDocument is called.
+ * buffer must stay alive until FPDF_CloseDocument is called. The owning module
+ * is recorded because a reset discards the module while readers may still close
+ * their documents: both the close and the free must go to the old instance, not
+ * to whichever module the caller re-fetched.
*/
-const _docDataPtrs = new Map<number, number>();
+const _docDataPtrs = new Map<
+ number,
+ { module: WrappedPdfiumModule; ptr: number }
+>();
/**
* Read an annotation rectangle using the CropBox-adjusted `EPDFAnnot_GetRect`
@@ -324,6 +342,32 @@ export class PdfiumOpenError extends Error {
}
}
+/**
+ * One open document shared by every scan of the same bytes. Each reopen copies
+ * the file into the WASM heap again and leaves PDFium caches behind, growing
+ * the heap high-water per scan. Password opens are never shared.
+ *
+ * A document released while scans still hold it is closed by the last reader:
+ * `releaseSharedDocument()` only arms `sharedReleasePending` when refs are
+ * outstanding, so the handle is never closed under an active reader.
+ */
+interface SharedDocument {
+ bytes: ArrayBuffer | Uint8Array;
+ docPtr: number;
+ refs: number;
+}
+let sharedDocument: SharedDocument | null = null;
+let sharedReleasePending = false;
+
+function closeDocumentNow(m: WrappedPdfiumModule, docPtr: number): void {
+ const entry = _docDataPtrs.get(docPtr);
+ (entry?.module ?? m).FPDF_CloseDocument(docPtr);
+ if (entry) {
+ _docDataPtrs.delete(docPtr);
+ entry.module.pdfium.wasmExports.free(entry.ptr);
+ }
+}
+
/**
* Load a PDF into PDFium memory and return the document pointer.
* Caller MUST call `closeRawDocument(docPtr)` when finished.
@@ -333,6 +377,21 @@ export async function openRawDocument(
password?: string,
): Promise<number> {
const m = await getPdfiumModule();
+
+ if (!password && sharedDocument && sharedDocument.bytes === data) {
+ sharedDocument.refs++;
+ return sharedDocument.docPtr;
+ }
+
+ // A different document is being opened, so an idle shared one goes before the
+ // new buffer is allocated: two large copies must not sit in the heap at once.
+ // With readers outstanding the close stays deferred to the last reader.
+ if (!password && sharedDocument && sharedDocument.refs <= 0) {
+ closeDocumentNow(m, sharedDocument.docPtr);
+ sharedDocument = null;
+ sharedReleasePending = false;
+ }
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
const len = bytes.length;
const ptr = m.pdfium.wasmExports.malloc(len);
@@ -343,8 +402,15 @@ export async function openRawDocument(
m.pdfium.wasmExports.free(ptr);
throw new PdfiumOpenError(m.FPDF_GetLastError());
}
- // Keep the buffer alive — freed in closeRawDocument()
- _docDataPtrs.set(docPtr, ptr);
+ // Keep the buffer alive; freed by closeDocumentNow()
+ _docDataPtrs.set(docPtr, { module: m, ptr });
+
+ if (!password && !sharedDocument) {
+ // A scan still reading the previous document keeps it open; only adopt the
+ // new one once its refs drop to zero.
+ sharedDocument = { bytes: data, docPtr, refs: 1 };
+ }
+
return docPtr;
}
@@ -360,7 +426,8 @@ export async function openRawDocumentSafe(
}
/**
- * Close a raw document pointer and free its backing data buffer.
+ * Close a raw document pointer. Shared documents only lose a reference; the
+ * handle stays open for the next scan of the same bytes.
*/
export async function closeRawDocument(docPtr: number): Promise<void> {
const m = await getPdfiumModule();
@@ -368,19 +435,58 @@ export async function closeRawDocument(docPtr: number): Promise<void> {
}
/**
- * Synchronous close + buffer free — for use inside `finally` blocks that
- * already have the module reference.
+ * Synchronous release, for use inside `finally` blocks that already have the
+ * module reference.
*/
export function closeDocAndFreeBuffer(
m: WrappedPdfiumModule,
docPtr: number,
): void {
- m.FPDF_CloseDocument(docPtr);
- const dataPtr = _docDataPtrs.get(docPtr);
- if (dataPtr) {
- m.pdfium.wasmExports.free(dataPtr);
- _docDataPtrs.delete(docPtr);
+ if (sharedDocument && sharedDocument.docPtr === docPtr) {
+ if (sharedDocument.refs > 0) {
+ sharedDocument.refs--;
+ }
+ if (sharedDocument.refs === 0 && sharedReleasePending) {
+ closeDocumentNow(m, docPtr);
+ sharedDocument = null;
+ sharedReleasePending = false;
+ return;
+ }
+ // No release pending: the handle lingers for the next same-bytes scan.
+ // Not falling through to closeDocumentNow on purpose: that would
+ // double-close it and leave `sharedDocument` dangling.
+ return;
+ }
+ closeDocumentNow(m, docPtr);
+}
+
+/**
+ * Drop the shared document, e.g. when its file leaves the workbench. With
+ * readers outstanding the close is deferred to the last `closeDocAndFreeBuffer`.
+ */
+export function releaseSharedDocument(): void {
+ if (!sharedDocument) {
+ sharedReleasePending = false;
+ return;
}
+ if (sharedDocument.refs > 0) {
+ sharedReleasePending = true;
+ return;
+ }
+ const session = sharedDocument;
+ sharedDocument = null;
+ sharedReleasePending = false;
+ if (_module) {
+ closeDocumentNow(_module, session.docPtr);
+ }
+}
+
+/**
+ * Close the shared document once every queued scan has finished. A scan queued
+ * before the file left can still open it, so the release runs behind the queue.
+ */
+export function releaseSharedDocumentWhenIdle(): void {
+ void runPdfiumScan(async () => releaseSharedDocument());
}
/**
@@ -391,6 +497,24 @@ export async function getRawPageCount(docPtr: number): Promise<number> {
return m.FPDF_GetPageCount(docPtr);
}
+/**
+ * Catalog form type without loading pages: 0 none, 1 AcroForm, 2/3 XFA, or
+ * null when the pinned build cannot answer (callers then extract rather than
+ * read "unknown" as "no form").
+ */
+export async function readRawFormType(
+ data: ArrayBuffer | Uint8Array,
+): Promise<number | null> {
+ const m = await getPdfiumModule();
+ if (typeof m.FPDF_GetFormType !== "function") return null;
+ const docPtr = await openRawDocumentSafe(data);
+ try {
+ return m.FPDF_GetFormType(docPtr);
+ } finally {
+ closeDocAndFreeBuffer(m, docPtr);
+ }
+}
+
/**
* Get raw page dimensions { width, height } for a page.
*/
@@ -443,6 +567,7 @@ export interface PdfiumFormField {
flags: number;
options: Array<{ label: string; isSelected: boolean }>;
widgets: PdfiumWidgetRect[];
+ tooltip?: string | null;
}
export interface PdfiumWidgetRect {
@@ -458,7 +583,7 @@ export interface PdfiumWidgetRect {
}
/**
- * Extract all form fields (Widget annotations) from every page of a document.
+ * Extract form fields (Widget annotations) from specified or all pages of a document.
*
* Returns an array of parsed form fields with their widget rectangles already
* converted to CSS coordinate space (upper-left origin).
@@ -466,6 +591,7 @@ export interface PdfiumWidgetRect {
export async function extractFormFields(
data: ArrayBuffer | Uint8Array,
password?: string,
+ pageIndices?: number[],
): Promise<PdfiumFormField[]> {
const m = await getPdfiumModule();
let docPtr: number;
@@ -493,7 +619,16 @@ export async function extractFormFields(
// Map: fieldName → PdfiumFormField (to merge widgets across pages)
const fieldMap = new Map<string, PdfiumFormField>();
- for (let pageIdx = 0; pageIdx < pageCount; pageIdx++) {
+ const targetPages: number[] = [];
+ if (Array.isArray(pageIndices) && pageIndices.length > 0) {
+ for (const idx of pageIndices) {
+ if (idx >= 0 && idx < pageCount) targetPages.push(idx);
+ }
+ } else {
+ for (let i = 0; i < pageCount; i++) targetPages.push(i);
+ }
+
+ for (const pageIdx of targetPages) {
let pagePtr: number;
try {
pagePtr = m.FPDF_LoadPage(docPtr, pageIdx);
@@ -841,11 +976,38 @@ function this_extractAnnotation(
}
}
+ // Tooltip (TU), read here so the tooltip pass does not walk every page again.
+ let tooltip: string | null = null;
+ if (formEnvPtr) {
+ try {
+ const altLen = m.FPDFAnnot_GetFormFieldAlternateName(
+ formEnvPtr,
+ annotPtr,
+ 0,
+ 0,
+ );
+ if (altLen > 0) {
+ const altBuf = m.pdfium.wasmExports.malloc(altLen);
+ m.FPDFAnnot_GetFormFieldAlternateName(
+ formEnvPtr,
+ annotPtr,
+ altBuf,
+ altLen,
+ );
+ tooltip = readUtf16(m, altBuf, altLen) || null;
+ m.pdfium.wasmExports.free(altBuf);
+ }
+ } catch {
+ // Alternate name extraction non-critical
+ }
+ }
+
// Merge into field map (multiple widgets can share a field name)
if (fieldName) {
const existing = fieldMap.get(fieldName);
if (existing) {
if (widgetRect) existing.widgets.push(widgetRect);
+ if (tooltip && !existing.tooltip) existing.tooltip = tooltip;
} else {
fieldMap.set(fieldName, {
name: fieldName,
@@ -857,6 +1019,7 @@ function this_extractAnnotation(
flags: fieldFlags,
options,
widgets: widgetRect ? [widgetRect] : [],
+ tooltip,
});
}
}
@@ -1569,6 +1732,7 @@ async function renderWidgetAppearance(
export async function renderSignatureFieldAppearances(
data: ArrayBuffer | Uint8Array,
password?: string,
+ pageIndexes?: number[],
): Promise<SignatureFieldAppearance[]> {
const m = await getPdfiumModule();
const docPtr = await openRawDocumentSafe(data, password);
@@ -1578,8 +1742,10 @@ export async function renderSignatureFieldAppearances(
const formEnvPtr = m.PDFiumExt_InitFormFillEnvironment(docPtr, formInfoPtr);
const pageCount = m.FPDF_GetPageCount(docPtr);
const results: SignatureFieldAppearance[] = [];
+ const pages = pageIndexes ?? Array.from({ length: pageCount }, (_, i) => i);
- for (let pageIdx = 0; pageIdx < pageCount; pageIdx++) {
+ for (const pageIdx of pages) {
+ if (pageIdx < 0 || pageIdx >= pageCount) continue;
const pagePtr = m.FPDF_LoadPage(docPtr, pageIdx);
if (!pagePtr) continue;
if (formEnvPtr) m.FORM_OnAfterLoadPage(pagePtr, formEnvPtr);
@@ -1833,6 +1999,7 @@ export async function renderSignatureFieldAppearances(
export async function renderButtonFieldAppearances(
data: ArrayBuffer | Uint8Array,
password?: string,
+ pageIndexes?: number[],
): Promise<SignatureFieldAppearance[]> {
const m = await getPdfiumModule();
const docPtr = await openRawDocumentSafe(data, password);
@@ -1842,8 +2009,10 @@ export async function renderButtonFieldAppearances(
const formEnvPtr = m.PDFiumExt_InitFormFillEnvironment(docPtr, formInfoPtr);
const pageCount = m.FPDF_GetPageCount(docPtr);
const buttonResults: SignatureFieldAppearance[] = [];
+ const pages = pageIndexes ?? Array.from({ length: pageCount }, (_, i) => i);
- for (let pageIdx = 0; pageIdx < pageCount; pageIdx++) {
+ for (const pageIdx of pages) {
+ if (pageIdx < 0 || pageIdx >= pageCount) continue;
const pagePtr = m.FPDF_LoadPage(docPtr, pageIdx);
if (!pagePtr) continue;
if (formEnvPtr) m.FORM_OnAfterLoadPage(pagePtr, formEnvPtr);
diff --git a/frontend/editor/src/core/tests/stubbed/form-compressed-catalog.spec.ts b/frontend/editor/src/core/tests/stubbed/form-compressed-catalog.spec.ts
new file mode 100644
index 0000000000..904ea971ea
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/form-compressed-catalog.spec.ts
@@ -0,0 +1,25 @@
+// A signed form whose /AcroForm lives in a compressed object stream has no
+// literal marker in its bytes, so the signature overlay must confirm the
+// catalog before deciding the document has nothing to render.
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import { uploadFiles } from "@app/tests/helpers/ui-helpers";
+import path from "node:path";
+
+const FIXTURE = path.join(
+ import.meta.dirname,
+ "../test-fixtures/signed-compressed-catalog.pdf",
+);
+
+test("a compressed-catalog signature still renders its overlay", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await page.goto("/editor", { waitUntil: "domcontentloaded" });
+ await uploadFiles(page, FIXTURE);
+ await page.locator('[data-page-index="0"]').first().waitFor({
+ timeout: 60_000,
+ });
+ await expect(page.locator('[data-signature-overlay-page="0"]')).toBeVisible({
+ timeout: 30_000,
+ });
+});
diff --git a/frontend/editor/src/core/tests/test-fixtures/form-compressed-catalog.pdf b/frontend/editor/src/core/tests/test-fixtures/form-compressed-catalog.pdf
new file mode 100644
index 0000000000..2cfa23c901
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/form-compressed-catalog.pdf differ
diff --git a/frontend/editor/src/core/tests/test-fixtures/signed-compressed-catalog.pdf b/frontend/editor/src/core/tests/test-fixtures/signed-compressed-catalog.pdf
new file mode 100644
index 0000000000..4284d7c61d
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/signed-compressed-catalog.pdf differ
diff --git a/frontend/editor/src/core/tools/formFill/ButtonAppearanceOverlay.tsx b/frontend/editor/src/core/tools/formFill/ButtonAppearanceOverlay.tsx
index 525f714ddf..d37ccc0a32 100644
--- a/frontend/editor/src/core/tools/formFill/ButtonAppearanceOverlay.tsx
+++ b/frontend/editor/src/core/tools/formFill/ButtonAppearanceOverlay.tsx
@@ -14,6 +14,9 @@ import {
renderButtonFieldAppearances,
type SignatureFieldAppearance,
} from "@app/services/pdfiumService";
+import { getDocumentBytes } from "@app/services/documentBytesCache";
+import { documentHasFormFields } from "@app/services/documentFormProbe";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
interface ButtonAppearanceOverlayProps {
pageIndex: number;
@@ -29,9 +32,10 @@ async function resolveButtonAppearances(
): Promise<SignatureFieldAppearance[]> {
if (source === _cachedSource && _cachePromise) return _cachePromise;
_cachedSource = source;
- _cachePromise = source
- .arrayBuffer()
- .then((buf) => renderButtonFieldAppearances(buf));
+ _cachePromise = getDocumentBytes(source).then(async (buf) => {
+ if (!(await documentHasFormFields(buf, source.size))) return [];
+ return runPdfiumScan(() => renderButtonFieldAppearances(buf));
+ });
return _cachePromise;
}
function ButtonBitmapCanvas({
diff --git a/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.test.ts b/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.test.ts
new file mode 100644
index 0000000000..23a9ebb402
--- /dev/null
+++ b/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import type { Mock } from "vitest";
+
+vi.mock("@app/services/documentBytesCache", () => ({
+ getDocumentBytes: vi.fn(),
+}));
+
+vi.mock("@app/services/pdfiumScanQueue", () => ({
+ runPdfiumScan: (task: () => Promise<unknown>) => task(),
+}));
+
+vi.mock("@app/services/documentFormProbe", () => ({
+ documentHasFormFields: vi.fn(async () => false),
+}));
+
+vi.mock("@app/services/pdfiumService", () => ({
+ PDF_FORM_FIELD_TYPE: new Proxy({}, { get: (_target, prop) => String(prop) }),
+ extractFormFields: vi.fn(async () => []),
+ openRawDocumentSafe: vi.fn(async () => 1),
+ closeDocAndFreeBuffer: vi.fn(),
+ getPdfiumModule: vi.fn(async () => ({
+ FPDF_CloseDocument: vi.fn(),
+ PDFiumExt_OpenFormFillInfo: vi.fn(() => 1),
+ PDFiumExt_InitFormFillEnvironment: vi.fn(() => 0),
+ })),
+}));
+
+import { allowConsole } from "@app/tests/failOnConsole";
+
+import { getDocumentBytes } from "@app/services/documentBytesCache";
+import { documentHasFormFields } from "@app/services/documentFormProbe";
+import { extractFormFields } from "@app/services/pdfiumService";
+import { PdfiumFormProvider } from "@app/tools/formFill/providers/PdfiumFormProvider";
+
+describe("PdfiumFormProvider", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (documentHasFormFields as Mock).mockResolvedValue(false);
+ });
+
+ it("returns [] and skips extraction when the document has no form", async () => {
+ (getDocumentBytes as Mock).mockResolvedValue(new ArrayBuffer(16));
+
+ const provider = new PdfiumFormProvider();
+ const fields = await provider.fetchFields(new Blob([]));
+
+ expect(fields).toEqual([]);
+ expect(extractFormFields).not.toHaveBeenCalled();
+ });
+
+ it("extracts when the probe finds a form the literal scan missed", async () => {
+ // qpdf --object-streams=generate hides the catalog, so the byte scan is
+ // not proof of absence; the catalog probe is.
+ (getDocumentBytes as Mock).mockResolvedValue(new ArrayBuffer(16));
+ (documentHasFormFields as Mock).mockResolvedValue(true);
+
+ const provider = new PdfiumFormProvider();
+ await provider.fetchFields(new Blob([]));
+
+ expect(extractFormFields).toHaveBeenCalledTimes(1);
+ });
+
+ it("characterizes field mapping: transforms PdfiumFormField into FormField model", async () => {
+ const bytes = new TextEncoder().encode("/AcroForm");
+ (documentHasFormFields as Mock).mockResolvedValue(true);
+ (getDocumentBytes as Mock).mockResolvedValue(bytes.buffer);
+ (extractFormFields as Mock).mockResolvedValue([
+ {
+ name: "form.text1",
+ type: "TEXTFIELD",
+ value: "sample text",
+ isChecked: false,
+ isReadOnly: false,
+ isRequired: true,
+ flags: 0x1000, // multiline bit
+ options: [],
+ widgets: [
+ { pageIndex: 0, x: 50, y: 100, width: 200, height: 30, fontSize: 12 },
+ ],
+ },
+ {
+ name: "form.check1",
+ type: "CHECKBOX",
+ value: "",
+ isChecked: true,
+ isReadOnly: true,
+ isRequired: false,
+ flags: 0,
+ options: [],
+ widgets: [
+ {
+ pageIndex: 0,
+ x: 50,
+ y: 150,
+ width: 15,
+ height: 15,
+ exportValue: "CustomVal",
+ },
+ ],
+ },
+ {
+ name: "form.empty_no_widgets",
+ type: "TEXTFIELD",
+ value: "",
+ isChecked: false,
+ isReadOnly: false,
+ isRequired: false,
+ flags: 0,
+ options: [],
+ widgets: [],
+ },
+ ]);
+
+ const provider = new PdfiumFormProvider();
+ const fields = await provider.fetchFields(new Blob([bytes]));
+
+ expect(fields).toHaveLength(2); // empty widgets field filtered out
+ expect(fields[0]).toMatchObject({
+ name: "form.text1",
+ label: "text1",
+ type: "text",
+ value: "sample text",
+ required: true,
+ readOnly: false,
+ multiline: true,
+ widgets: [
+ { pageIndex: 0, x: 50, y: 100, width: 200, height: 30, fontSize: 12 },
+ ],
+ });
+ expect(fields[1]).toMatchObject({
+ name: "form.check1",
+ label: "check1",
+ type: "checkbox",
+ value: "CustomVal",
+ required: false,
+ readOnly: true,
+ multiline: false,
+ widgets: [
+ {
+ pageIndex: 0,
+ x: 50,
+ y: 150,
+ width: 15,
+ height: 15,
+ exportValue: "CustomVal",
+ },
+ ],
+ });
+ });
+
+ it("returns empty array and does not throw when getDocumentBytes fails", async () => {
+ allowConsole.warn(/Failed to extract form fields/);
+ (getDocumentBytes as Mock).mockRejectedValue(new Error("Disk error"));
+
+ const provider = new PdfiumFormProvider();
+ const fields = await provider.fetchFields(new Blob([]));
+ expect(fields).toEqual([]);
+ });
+});
diff --git a/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.ts b/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.ts
index 471bba5e43..f47b5d25c5 100644
--- a/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.ts
+++ b/frontend/editor/src/core/tools/formFill/providers/PdfiumFormProvider.ts
@@ -14,6 +14,9 @@
* for both providers.
*/
import { PDF_FORM_FIELD_TYPE } from "@app/services/pdfiumService";
+import { getDocumentBytes } from "@app/services/documentBytesCache";
+import { documentHasFormFields } from "@app/services/documentFormProbe";
+import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
import { FPDF_ANNOT_WIDGET, FLAT_PRINT } from "@app/utils/pdfiumBitmapUtils";
import type {
FormField,
@@ -71,7 +74,7 @@ function mapFieldType(t: PDF_FORM_FIELD_TYPE): FormFieldType {
* @param buttonInfo When provided, sets buttonLabel and buttonAction for push buttons.
*/
function toFormField(
- f: PdfiumFormField & { _tooltip?: string | null },
+ f: PdfiumFormField,
optInfo?: { exportValues: string[]; displayValues: string[] } | null,
buttonInfo?: { label?: string; action?: ButtonAction } | null,
): FormField {
@@ -125,7 +128,7 @@ function toFormField(
readOnly: f.isReadOnly,
multiSelect: f.type === PDF_FORM_FIELD_TYPE.LISTBOX,
multiline: type === "text" && (f.flags & 0x1000) !== 0, // bit 13 = Multiline
- tooltip: f._tooltip ?? null,
+ tooltip: f.tooltip ?? null,
widgets,
buttonLabel: buttonInfo?.label ?? null,
buttonAction: buttonInfo?.action ?? null,
@@ -144,11 +147,11 @@ export class PdfiumFormProvider implements IFormDataProvider {
async fetchFields(file: File | Blob): Promise<FormField[]> {
try {
- const arrayBuffer = await file.arrayBuffer();
- const pdfiumFields = await extractFormFields(arrayBuffer);
-
- // Enrich with alternate names (tooltips)
- await this.enrichWithAlternateNames(arrayBuffer, pdfiumFields);
+ const arrayBuffer = await getDocumentBytes(file);
+ if (!(await documentHasFormFields(arrayBuffer, file.size))) return [];
+ const pdfiumFields = await runPdfiumScan(() =>
+ extractFormFields(arrayBuffer),
+ );
// Enrich combo/listbox fields with export/display values from pdf-lib
const optMap = await this.extractDisplayOptions(
@@ -177,102 +180,6 @@ export class PdfiumFormProvider implements IFormDataProvider {
}
}
- /**
- * Enrich fields with alternate names (tooltip / TU entry) via PDFium.
- */
- private async enrichWithAlternateNames(
- data: ArrayBuffer,
- fields: PdfiumFormField[],
- ): Promise<void> {
- try {
- const m = await getPdfiumModule();
- const docPtr = await openRawDocumentSafe(data);
- try {
- const formInfoPtr = m.PDFiumExt_OpenFormFillInfo();
- const formEnvPtr = m.PDFiumExt_InitFormFillEnvironment(
- docPtr,
- formInfoPtr,
- );
- if (!formEnvPtr) return;
-
- const pageCount = m.FPDF_GetPageCount(docPtr);
- const nameToField = new Map(fields.map((f) => [f.name, f]));
- const enriched = new Set<string>();
-
- for (
- let pageIdx = 0;
- pageIdx < pageCount && enriched.size < nameToField.size;
- pageIdx++
- ) {
- const pagePtr = m.FPDF_LoadPage(docPtr, pageIdx);
- if (!pagePtr) continue;
- m.FORM_OnAfterLoadPage(pagePtr, formEnvPtr);
-
- const annotCount = m.FPDFPage_GetAnnotCount(pagePtr);
- for (
- let ai = 0;
- ai < annotCount && enriched.size < nameToField.size;
- ai++
- ) {
- const annotPtr = m.FPDFPage_GetAnnot(pagePtr, ai);
- if (!annotPtr) continue;
- if (m.FPDFAnnot_GetSubtype(annotPtr) !== FPDF_ANNOT_WIDGET) {
- m.FPDFPage_CloseAnnot(annotPtr);
- continue;
- }
-
- const nl = m.FPDFAnnot_GetFormFieldName(formEnvPtr, annotPtr, 0, 0);
- let name = "";
- if (nl > 0) {
- const nb = m.pdfium.wasmExports.malloc(nl);
- m.FPDFAnnot_GetFormFieldName(formEnvPtr, annotPtr, nb, nl);
- name = readUtf16(m, nb, nl);
- m.pdfium.wasmExports.free(nb);
- }
-
- if (name && nameToField.has(name) && !enriched.has(name)) {
- const altLen = m.FPDFAnnot_GetFormFieldAlternateName(
- formEnvPtr,
- annotPtr,
- 0,
- 0,
- );
- if (altLen > 0) {
- const altBuf = m.pdfium.wasmExports.malloc(altLen);
- m.FPDFAnnot_GetFormFieldAlternateName(
- formEnvPtr,
- annotPtr,
- altBuf,
- altLen,
- );
- const altName = readUtf16(m, altBuf, altLen);
- m.pdfium.wasmExports.free(altBuf);
- (
- nameToField.get(name) as PdfiumFormField & {
- _tooltip?: string | null;
- }
- )._tooltip = altName || null;
- }
- enriched.add(name);
- }
-
- m.FPDFPage_CloseAnnot(annotPtr);
- }
-
- m.FORM_OnBeforeClosePage(pagePtr, formEnvPtr);
- m.FPDF_ClosePage(pagePtr);
- }
-
- m.PDFiumExt_ExitFormFillEnvironment(formEnvPtr);
- m.PDFiumExt_CloseFormFillInfo(formInfoPtr);
- } finally {
- closeDocAndFreeBuffer(m, docPtr);
- }
- } catch (e) {
- console.warn("[PdfiumFormProvider] Failed to enrich alternate names:", e);
- }
- }
-
/**
* Use pdf-lib to read /Opt arrays for combo/listbox fields.
* Returns a map of fieldName → { exportValues, displayValues }.
diff --git a/frontend/editor/src/core/utils/asciiBytes.test.ts b/frontend/editor/src/core/utils/asciiBytes.test.ts
new file mode 100644
index 0000000000..f26fd166e5
--- /dev/null
+++ b/frontend/editor/src/core/utils/asciiBytes.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { hasAcroForm } from "@app/utils/asciiBytes";
+
+const bytes = (text: string) => new TextEncoder().encode(text);
+
+describe("hasAcroForm", () => {
+ it("matches a whole name token", () => {
+ expect(hasAcroForm(bytes("<</AcroForm 1 0 R>>"))).toBe(true);
+ expect(hasAcroForm(bytes("/AcroForm/Fields"))).toBe(true);
+ expect(hasAcroForm(bytes("/AcroForm"))).toBe(true);
+ });
+
+ it("ignores a longer name that starts with the token", () => {
+ expect(hasAcroForm(bytes("/AcroFormExtra"))).toBe(false);
+ expect(hasAcroForm(bytes("/AcroForm2"))).toBe(false);
+ });
+
+ it("returns false when the token is absent", () => {
+ expect(hasAcroForm(bytes("%PDF-1.7\n1 0 obj"))).toBe(false);
+ });
+
+ it("keys the memoised result by view offset and length", () => {
+ const buffer = bytes("/AcroForm").buffer;
+ const full = new Uint8Array(buffer);
+ const tail = new Uint8Array(buffer, 1, 4);
+
+ expect(hasAcroForm(full)).toBe(true);
+ expect(hasAcroForm(tail)).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/utils/asciiBytes.ts b/frontend/editor/src/core/utils/asciiBytes.ts
new file mode 100644
index 0000000000..e3676454dd
--- /dev/null
+++ b/frontend/editor/src/core/utils/asciiBytes.ts
@@ -0,0 +1,69 @@
+/**
+ * Byte-level PDF probes for the viewer.
+ *
+ * Latin-1 decoding is byte-for-byte, so a byte scan answers "does this PDF
+ * contain /X" without materialising a multi-megabyte string. Results for
+ * /AcroForm are memoised per buffer because the form, signature and button
+ * scanners all ask the same question about the same document.
+ */
+// ISO 32000-1, 7.2.3: whitespace and the delimiters that end a name token.
+const NAME_DELIMITER = new Set([
+ 0x00, 0x09, 0x0a, 0x0c, 0x0d, 0x20, 0x28, 0x29, 0x3c, 0x3e, 0x5b, 0x5d, 0x7b,
+ 0x7d, 0x2f, 0x25,
+]);
+
+/**
+ * True when `name` appears as a whole PDF name token. Matching the raw bytes
+ * alone would treat `/AcroFormExtra` or a name inside a content stream as a hit
+ * and send a form-less file down the expensive path.
+ */
+function containsPdfName(bytes: Uint8Array, name: string): boolean {
+ const first = name.charCodeAt(0);
+ let from = 0;
+ while (from <= bytes.length - name.length) {
+ const idx = bytes.indexOf(first, from);
+ if (idx === -1 || idx > bytes.length - name.length) return false;
+ let match = true;
+ for (let j = 1; j < name.length; j++) {
+ if (bytes[idx + j] !== name.charCodeAt(j)) {
+ match = false;
+ break;
+ }
+ }
+ const after = idx + name.length;
+ if (match && (after === bytes.length || NAME_DELIMITER.has(bytes[after]))) {
+ return true;
+ }
+ from = idx + 1;
+ }
+ return false;
+}
+
+const acroFormResults = new WeakMap<
+ ArrayBuffer,
+ { offset: number; length: number; result: boolean }
+>();
+
+/**
+ * True when the bytes contain a literal /AcroForm name. This is a hint only:
+ * the name can live inside a compressed object stream, and it can appear in a
+ * stream or comment. `documentHasFormFields` confirms the catalog.
+ */
+export function hasAcroForm(bytes: Uint8Array): boolean {
+ const key = bytes.buffer as ArrayBuffer;
+ const cached = acroFormResults.get(key);
+ if (
+ cached &&
+ cached.offset === bytes.byteOffset &&
+ cached.length === bytes.byteLength
+ ) {
+ return cached.result;
+ }
+ const result = containsPdfName(bytes, "/AcroForm");
+ acroFormResults.set(key, {
+ offset: bytes.byteOffset,
+ length: bytes.byteLength,
+ result,
+ });
+ return result;
+}
diff --git a/frontend/editor/src/core/utils/pdfMeasurementExtraction.ts b/frontend/editor/src/core/utils/pdfMeasurementExtraction.ts
index 3c40e3209f..ac60050c72 100644
--- a/frontend/editor/src/core/utils/pdfMeasurementExtraction.ts
+++ b/frontend/editor/src/core/utils/pdfMeasurementExtraction.ts
@@ -13,6 +13,7 @@ import type {
ViewportScale,
} from "@app/utils/measurementTypes";
import { getUnitFactor } from "@app/utils/measurementUtils";
+import { getDocumentBytes } from "@app/services/documentBytesCache";
type PdfMeasurementObjects = Pick<
typeof import("@cantoo/pdf-lib"),
@@ -162,7 +163,7 @@ export async function extractPageMeasureScales(
try {
const pdfLib = await import("@cantoo/pdf-lib");
const { PDFDocument, PDFArray, PDFDict, PDFName } = pdfLib;
- const pdfDoc = await PDFDocument.load(await file.arrayBuffer(), {
+ const pdfDoc = await PDFDocument.load(await getDocumentBytes(file), {
ignoreEncryption: true,
});
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.ts
index b1ed65fb99..df5e978422 100644
--- a/frontend/editor/src/core/utils/thumbnailUtils.ts
+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts
@@ -9,6 +9,7 @@ import {
renderPdfiumPageDataUrl,
readPdfiumPageMetadata,
} from "@app/utils/pdfiumPageRender";
+import { getDocumentBytes } from "@app/services/documentBytesCache";
export interface ThumbnailWithMetadata {
thumbnail: string; // Always returns a thumbnail (placeholder if needed)
@@ -258,7 +259,7 @@ export async function generateThumbnailForFile(file: File): Promise<string> {
// chunk can fail to open for PDFs larger than that. Retry with the
// full buffer before falling back to an empty thumbnail.
try {
- const fullArrayBuffer = await file.arrayBuffer();
+ const fullArrayBuffer = await getDocumentBytes(file);
return await generatePDFThumbnail(fullArrayBuffer, scale);
} catch (error) {
reportThumbnailFailure(file, error);
@@ -320,7 +321,7 @@ export async function generateThumbnailWithMetadata(
}
try {
- const arrayBuffer = await file.arrayBuffer();
+ const arrayBuffer = await getDocumentBytes(file);
// Always read per-page rotation: PageEditor renders thumbnails upright and
// uses this as the rotation baseline, so skipping it corrupts saves.
const result = await renderPdfThumbnailPdfium(
@@ -374,7 +375,7 @@ export async function generateThumbnailPairWithMetadata(file: File): Promise<{
}
const buffer = isLarge
? await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer()
- : await file.arrayBuffer();
+ : await getDocumentBytes(file);
const pair = await renderPdfThumbnailPairPdfium(buffer, scale, !isLarge);
const toPublic = (r: PdfiumRenderResult): ThumbnailWithMetadata =>
diff --git a/frontend/editor/src/portal/components/users/InviteMemberModal.tsx b/frontend/editor/src/portal/components/users/InviteMemberModal.tsx
index 1954d1beb1..570fa79b48 100644
--- a/frontend/editor/src/portal/components/users/InviteMemberModal.tsx
+++ b/frontend/editor/src/portal/components/users/InviteMemberModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button, Checkbox, FormField, Input, Modal, Select } from "@app/ui";
import {
@@ -192,9 +192,21 @@ export function InviteMemberModal({
setTouched((current) => ({ ...current, [field]: true }));
}
+ const resetTimerRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (resetTimerRef.current !== null) {
+ window.clearTimeout(resetTimerRef.current);
+ }
+ };
+ }, []);
+
function close() {
onClose();
- setTimeout(() => {
+ // The form resets after the close animation; if the modal unmounts first,
+ // the timer must not outlive it.
+ resetTimerRef.current = window.setTimeout(() => {
setEmail("");
setUsername("");
setPassword("");