Skip to content

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

perf(viewer): optimize PDF text editor WASM memory management with reusable scratch buffers (#8099)

brios487cda522d5d
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/embeddedFace.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/embeddedFace.test.ts
index 49d5593317..a9e4b1142a 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/embeddedFace.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/embeddedFace.test.ts
@@ -56,21 +56,34 @@ function makeModule(
): PdfiumModule {
const memory = { buffer: new ArrayBuffer(heapBytes) };
let next = 8; // pointer 0 means "absent" to the code under test
- let live = 0;
+ // Pooled scratch buffers outlive a free() of a neighbouring block, so free()
+ // returns the range to a list instead of resetting the bump pointer.
+ const blocks = new Map<number, number>();
+ const freeList: Array<{ ptr: number; size: number }> = [];
const view = () => new DataView(memory.buffer);
const fake = {
pdfium: {
wasmExports: {
memory,
malloc(n: number): number {
+ const aligned = (n + 7) & ~7;
+ const slot = freeList.findIndex((b) => b.size >= aligned);
+ if (slot !== -1) {
+ const { ptr } = freeList.splice(slot, 1)[0];
+ blocks.set(ptr, aligned);
+ return ptr;
+ }
const ptr = next;
- next += (n + 7) & ~7;
+ next += aligned;
if (next > heapBytes) throw new Error("fake heap exhausted");
- live++;
+ blocks.set(ptr, aligned);
return ptr;
},
- free(): void {
- if (--live === 0) next = 8;
+ free(ptr: number): void {
+ const size = blocks.get(ptr);
+ if (size === undefined) return;
+ blocks.delete(ptr);
+ freeList.push({ ptr, size });
},
},
getValue(ptr: number): number {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/wasmAllocationCounts.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/wasmAllocationCounts.test.ts
new file mode 100644
index 0000000000..48ee45e846
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/wasmAllocationCounts.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from "vitest";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ measureObjRightEdgePt,
+ measureObjSpanPt,
+} from "@app/tools/pdfTextEditor/commands/editTextHelpers";
+import { setCharcodesOn } from "@app/tools/pdfTextEditor/charcode/charcodeRegistry";
+
+interface Bounds {
+ left: number;
+ right: number;
+}
+
+// Byte-addressed stub over a Float32 heap, mirroring the DisplayTransform
+// test's module stub so pointer arithmetic is exercised, not bypassed.
+function stubModule(boundsByPtr: Map<number, Bounds>) {
+ const heapBuf = new ArrayBuffer(1024);
+ const heapF32 = new Float32Array(heapBuf);
+ const heapU8 = new Uint8Array(heapBuf);
+ let next = 4;
+ let mallocs = 0;
+ let frees = 0;
+ const mod: Record<string, unknown> = {
+ pdfium: {
+ HEAPU8: heapU8,
+ wasmExports: {
+ malloc: (n: number): number => {
+ mallocs += 1;
+ const p = next;
+ next += n;
+ return p;
+ },
+ free: (): void => {
+ frees += 1;
+ },
+ },
+ getValue: (ptr: number, type: string): number =>
+ type === "float" ? heapF32[ptr >> 2] : 0,
+ },
+ FPDFText_SetCharcodes: (): boolean => true,
+ FPDFPageObj_GetBounds: (
+ ptr: number,
+ l: number,
+ b: number,
+ r: number,
+ t: number,
+ ): number => {
+ const box = boundsByPtr.get(ptr);
+ if (!box) return 0;
+ heapF32[l >> 2] = box.left;
+ heapF32[b >> 2] = 0;
+ heapF32[r >> 2] = box.right;
+ heapF32[t >> 2] = 0;
+ return 1;
+ },
+ };
+ return {
+ module: mod as unknown as WrappedPdfiumModule,
+ mallocs: () => mallocs,
+ frees: () => frees,
+ };
+}
+
+describe("edit-path wasm scratch allocations", () => {
+ it("measureObjRightEdgePt allocates its scratch block once and reuses it", () => {
+ const stub = stubModule(new Map([[7, { left: 1, right: 42 }]]));
+ expect(measureObjRightEdgePt(stub.module, 7)).toBe(42);
+ const afterFirst = stub.mallocs();
+ expect(measureObjRightEdgePt(stub.module, 7)).toBe(42);
+ // The whole point of the pool: the second call allocates nothing.
+ expect(stub.mallocs()).toBe(afterFirst);
+ expect(stub.frees()).toBe(0);
+ });
+
+ it("measureObjSpanPt reuses one block across every pointer and every call", () => {
+ const stub = stubModule(
+ new Map([
+ [1, { left: 5, right: 10 }],
+ [2, { left: 2, right: 20 }],
+ [3, { left: 7, right: 12 }],
+ ]),
+ );
+ expect(measureObjSpanPt(stub.module, [1, 2, 3])).toEqual({
+ left: 2,
+ right: 20,
+ });
+ const afterFirst = stub.mallocs();
+ expect(measureObjSpanPt(stub.module, [1, 2, 3])).toEqual({
+ left: 2,
+ right: 20,
+ });
+ expect(stub.mallocs()).toBe(afterFirst);
+ expect(stub.frees()).toBe(0);
+ });
+
+ it("measureObjRightEdgePt reports 0 for an unreadable object without freeing", () => {
+ const stub = stubModule(new Map());
+ expect(measureObjRightEdgePt(stub.module, 9)).toBe(0);
+ expect(stub.mallocs()).toBe(1);
+ expect(stub.frees()).toBe(0);
+ });
+
+ it("measureObjSpanPt returns null when nothing is measurable", () => {
+ const stub = stubModule(new Map());
+ expect(measureObjSpanPt(stub.module, [1, 2])).toBeNull();
+ expect(stub.mallocs()).toBe(1);
+ expect(stub.frees()).toBe(0);
+ });
+
+ it("setCharcodesOn allocates its scratch block once and reuses it across calls", () => {
+ const stub = stubModule(new Map());
+ expect(setCharcodesOn(stub.module, 1, [65, 66])).toBe(true);
+ const afterFirst = stub.mallocs();
+ expect(setCharcodesOn(stub.module, 1, [67, 68])).toBe(true);
+ expect(stub.mallocs()).toBe(afterFirst);
+ expect(stub.frees()).toBe(0);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/charcode/BackendResolver.ts b/frontend/editor/src/core/tools/pdfTextEditor/charcode/BackendResolver.ts
index 9192d7c064..3d290ff1ac 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/charcode/BackendResolver.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/charcode/BackendResolver.ts
@@ -6,6 +6,7 @@ import type {
} from "@app/tools/pdfTextEditor/charcode/CharcodeStrategy";
import { getActiveCharcodeStrategy } from "@app/tools/pdfTextEditor/charcode/CharcodeStrategy";
import { getCachedFontProgramSha256 } from "@app/tools/pdfTextEditor/charcode/CmapResolver";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Strategy 3: ask the Spring backend (PDFBox) to encode chars. */
@@ -368,14 +369,12 @@ export function fontIsReusable(
// program. PDFium still answers "true" for it, but reports a length of 0 -
// the length is the part that distinguishes a real face.
let ok = false;
- const out = m.pdfium.wasmExports.malloc(4);
+ const out = scratchPtr(m, SCRATCH.backendOut, 4);
try {
m.pdfium.setValue(out, 0, "i32");
ok = getData(fontPtr, 0, 0, out) && m.pdfium.getValue(out, "i32") > 0;
} catch {
ok = false;
- } finally {
- m.pdfium.wasmExports.free(out);
}
reusableFontCache.set(fontPtr, ok);
return ok;
@@ -529,13 +528,9 @@ function loadFontName(
try {
const len = fn(fontPtr, 0, 0);
if (len <= 1) return undefined;
- const buf = m.pdfium.wasmExports.malloc(len);
- try {
- fn(fontPtr, buf, len);
- return m.pdfium.UTF8ToString(buf) || undefined;
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.readerReadTextB, len);
+ fn(fontPtr, buf, len);
+ return m.pdfium.UTF8ToString(buf) || undefined;
} catch {
return undefined;
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/charcode/CmapResolver.ts b/frontend/editor/src/core/tools/pdfTextEditor/charcode/CmapResolver.ts
index cb04944c70..188e1b29bf 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/charcode/CmapResolver.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/charcode/CmapResolver.ts
@@ -4,6 +4,7 @@ import type {
ResolverContext,
} from "@app/tools/pdfTextEditor/charcode/CharcodeStrategy";
import { sha256Hex } from "@app/tools/pdfTextEditor/util/sha256";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Strategy 1: parse the embedded font's cmap table. */
@@ -127,24 +128,26 @@ function readFontData(
if (!fontMod.FPDFFont_GetFontData) return null;
// First call: ask for the buffer size (pass length=0, read outSize).
- const sizePtr = m.pdfium.wasmExports.malloc(4);
+ let dataPtr = 0;
try {
+ const sizePtr = scratchPtr(m, SCRATCH.cmapSize, 4);
const ok = fontMod.FPDFFont_GetFontData(font, 0, 0, sizePtr);
if (!ok) return null;
const size = m.pdfium.getValue(sizePtr, "i32");
if (size <= 0) return null;
- const dataPtr = m.pdfium.wasmExports.malloc(size);
- try {
- const ok2 = fontMod.FPDFFont_GetFontData(font, dataPtr, size, sizePtr);
- if (!ok2) return null;
- // Slice() copies out of the WASM heap so we own the bytes.
- const heapU8 = (m.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;
- return new Uint8Array(heapU8.buffer, dataPtr, size).slice();
- } finally {
- m.pdfium.wasmExports.free(dataPtr);
- }
+ dataPtr = m.pdfium.wasmExports.malloc(size);
+ if (!dataPtr) return null;
+ const ok2 = fontMod.FPDFFont_GetFontData(font, dataPtr, size, sizePtr);
+ if (!ok2) return null;
+ // Slice() copies out of the WASM heap so we own the bytes.
+ const heapU8 = (m.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;
+ return new Uint8Array(heapU8.buffer, dataPtr, size).slice();
+ } catch {
+ // A failed scratch/font allocation drops this cmap strategy; returning null
+ // lets the caller try the next one instead of aborting the page walk.
+ return null;
} finally {
- m.pdfium.wasmExports.free(sizePtr);
+ if (dataPtr) m.pdfium.wasmExports.free(dataPtr);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts b/frontend/editor/src/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts
index ab93eccbf5..0cb8f352c2 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts
@@ -21,6 +21,7 @@ import {
} from "@app/tools/pdfTextEditor/charcode/CharcodeStrategy";
import { CmapResolver } from "@app/tools/pdfTextEditor/charcode/CmapResolver";
import { ContentStreamResolver } from "@app/tools/pdfTextEditor/charcode/ContentStreamResolver";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Per-emit telemetry. */
export interface CharcodeEvent {
@@ -132,7 +133,7 @@ export function setCharcodesOn(
if (!ccMod.FPDFText_SetCharcodes || charcodes.length === 0) return false;
// Allocate a uint32 buffer in the WASM heap.
const bufSize = charcodes.length * 4;
- const buf = m.pdfium.wasmExports.malloc(bufSize);
+ const buf = scratchPtr(m, SCRATCH.charcodes, bufSize);
try {
const heapU8 = (m.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;
const view = new Uint32Array(heapU8.buffer, buf, charcodes.length);
@@ -140,8 +141,6 @@ export function setCharcodesOn(
return !!ccMod.FPDFText_SetCharcodes(textObj, buf, charcodes.length);
} catch {
return false;
- } finally {
- m.pdfium.wasmExports.free(buf);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
index 8234214633..0bf61431d9 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
@@ -5,6 +5,7 @@ import type { Page } from "@app/tools/pdfTextEditor/model/Page";
import type { ShapeObject } from "@app/tools/pdfTextEditor/model/ShapeObject";
import type { PageRuleSnapshot } from "@app/tools/pdfTextEditor/types";
import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
interface PageInsertModule {
FPDFPage_InsertObjectAtIndex?: (
@@ -148,18 +149,12 @@ function insertOnPage(
}
function readDrawMode(m: WrappedPdfiumModule, objPtr: number): DrawMode | null {
- const fillModePtr = m.pdfium.wasmExports.malloc(4);
- const strokePtr = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPath_GetDrawMode(objPtr, fillModePtr, strokePtr)) return null;
- return {
- fillMode: m.pdfium.getValue(fillModePtr, "i32"),
- stroke: m.pdfium.getValue(strokePtr, "i32") !== 0,
- };
- } finally {
- m.pdfium.wasmExports.free(fillModePtr);
- m.pdfium.wasmExports.free(strokePtr);
- }
+ const buf = scratchPtr(m, SCRATCH.shapeDrawMode, 8);
+ if (!m.FPDFPath_GetDrawMode(objPtr, buf, buf + 4)) return null;
+ return {
+ fillMode: m.pdfium.getValue(buf, "i32"),
+ stroke: m.pdfium.getValue(buf + 4, "i32") !== 0,
+ };
}
function indexOnPage(
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts
index b7ea1bceae..cf23cc59df 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/EditTextCommand.ts
@@ -42,6 +42,7 @@ import type {
TextRun,
} from "@app/tools/pdfTextEditor/model/TextRun";
import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
import {
captureScanEdit,
isScanRun,
@@ -1496,24 +1497,14 @@ function boundsFromPtr(
ptr: number,
fallbackX: number,
): { x: number; right: number } {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetBounds(ptr, l, b, r, t)) {
- return { x: fallbackX, right: fallbackX };
- }
- return {
- x: m.pdfium.getValue(l, "float"),
- right: m.pdfium.getValue(r, "float"),
- };
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
+ const buf = scratchPtr(m, SCRATCH.editBbox, 16);
+ if (!m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) {
+ return { x: fallbackX, right: fallbackX };
}
+ return {
+ x: m.pdfium.getValue(buf, "float"),
+ right: m.pdfium.getValue(buf + 8, "float"),
+ };
}
function keptLeadingBaselines(
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertImageCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertImageCommand.ts
index babe778bdb..298b2b9520 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertImageCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertImageCommand.ts
@@ -12,6 +12,7 @@ import {
embedBitmapImageOnPage,
embedJpegImageOnPage,
} from "@app/utils/pdfiumBitmapUtils";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
// Insert a decoded raster image onto a page at the given lower-left coordinate,
// scaled to `(width, height)` PDF points.
@@ -185,19 +186,15 @@ export class InsertImageCommand implements Command {
/** Read an object's current matrix so the model stays in lock-step with PDFium. */
function readMatrix(m: WrappedPdfiumModule, objPtr: number): Affine {
// FS_MATRIX: { a, b, c, d, e, f } as floats.
- const buf = m.pdfium.wasmExports.malloc(6 * 4);
- try {
- const ok = m.FPDFPageObj_GetMatrix(objPtr, buf);
- if (!ok) return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
- return {
- a: m.pdfium.getValue(buf, "float"),
- b: m.pdfium.getValue(buf + 4, "float"),
- c: m.pdfium.getValue(buf + 8, "float"),
- d: m.pdfium.getValue(buf + 12, "float"),
- e: m.pdfium.getValue(buf + 16, "float"),
- f: m.pdfium.getValue(buf + 20, "float"),
- };
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.imageMatrix, 6 * 4);
+ const ok = m.FPDFPageObj_GetMatrix(objPtr, buf);
+ if (!ok) return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+ return {
+ a: m.pdfium.getValue(buf, "float"),
+ b: m.pdfium.getValue(buf + 4, "float"),
+ c: m.pdfium.getValue(buf + 8, "float"),
+ d: m.pdfium.getValue(buf + 12, "float"),
+ e: m.pdfium.getValue(buf + 16, "float"),
+ f: m.pdfium.getValue(buf + 20, "float"),
+ };
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
index b2cc639239..12ea0c75b3 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
@@ -9,6 +9,7 @@ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { readUtf16 } from "@app/services/pdfiumService";
import { rotationFromMatrix } from "@app/tools/pdfTextEditor/commands/editTextHelpers";
import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
import {
endsWithSpace,
groupWords,
@@ -515,36 +516,28 @@ function readObjBounds(
m: WrappedPdfiumModule,
ptr: number,
): { x: number; right: number } | null {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
+ const buf = scratchPtr(m, SCRATCH.reflowBbox, 16);
try {
- if (!m.FPDFPageObj_GetBounds(ptr, l, b, r, t)) return null;
+ if (!m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) {
+ return null;
+ }
return {
- x: m.pdfium.getValue(l, "float"),
- right: m.pdfium.getValue(r, "float"),
+ x: m.pdfium.getValue(buf, "float"),
+ right: m.pdfium.getValue(buf + 8, "float"),
};
} catch {
return null;
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
}
}
/** The text-matrix baseline (translation `f`) - consistent across a line. */
function readObjBaseline(m: WrappedPdfiumModule, ptr: number): number {
- const buf = m.pdfium.wasmExports.malloc(6 * 4);
+ const buf = scratchPtr(m, SCRATCH.reflowMatrix, 6 * 4);
try {
if (!m.FPDFPageObj_GetMatrix(ptr, buf)) return 0;
return m.pdfium.getValue(buf + 20, "float");
} catch {
return 0;
- } finally {
- m.pdfium.wasmExports.free(buf);
}
}
@@ -556,13 +549,9 @@ function readObjText(
try {
const len = m.FPDFTextObj_GetText(ptr, textPage, 0, 0);
if (len <= 2) return "";
- const buf = m.pdfium.wasmExports.malloc(len);
- try {
- m.FPDFTextObj_GetText(ptr, textPage, buf, len);
- return readUtf16(m, buf, len);
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.reflowText, len);
+ m.FPDFTextObj_GetText(ptr, textPage, buf, len);
+ return readUtf16(m, buf, len);
} catch {
return "";
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts
index be778e6870..be71a9142b 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts
@@ -9,6 +9,7 @@ import {
embedBitmapImageOnPage,
embedJpegImageOnPage,
} from "@app/utils/pdfiumBitmapUtils";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
interface ZOrderModule {
FPDFPage_InsertObjectAtIndex?: (
@@ -29,13 +30,6 @@ interface MatrixModule {
f: number,
) => boolean;
FPDFPageObj_SetMatrix?: (obj: number, matrix: number) => boolean;
- pdfium?: {
- setValue?: (ptr: number, value: number, type: string) => void;
- wasmExports?: {
- malloc?: (size: number) => number;
- free?: (ptr: number) => void;
- };
- };
}
/** Swap an image's pixels but keep its matrix, so it fills the same box. */
@@ -239,27 +233,24 @@ function setImageMatrix(
/* fall through to the struct setter */
}
}
- writeMatrixStruct(mod, objPtr, matrix);
+ writeMatrixStruct(m, objPtr, matrix);
}
/** FS_MATRIX fallback for builds without the scalar `FPDFImageObj_SetMatrix`. */
function writeMatrixStruct(
- mod: MatrixModule,
+ m: WrappedPdfiumModule,
objPtr: number,
matrix: Affine,
): void {
- const setter = mod.FPDFPageObj_SetMatrix;
- const rt = mod.pdfium;
- if (!setter || !rt?.setValue || !rt.wasmExports?.malloc) return;
- const ptr = rt.wasmExports.malloc(6 * 4);
+ const setter = (m as unknown as MatrixModule).FPDFPageObj_SetMatrix;
+ if (!setter || !m.pdfium.setValue) return;
+ const ptr = scratchPtr(m, SCRATCH.imageMatrix, 6 * 4);
if (!ptr) return;
const values = [matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f];
try {
- values.forEach((v, i) => rt.setValue?.(ptr + i * 4, v, "float"));
+ values.forEach((v, i) => m.pdfium.setValue(ptr + i * 4, v, "float"));
setter(objPtr, ptr);
} catch {
/* best-effort */
- } finally {
- rt.wasmExports.free?.(ptr);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
index c7bfcc36d8..5fc2449e51 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
@@ -4,6 +4,7 @@ import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocume
import type { RGBA } from "@app/tools/pdfTextEditor/types";
import { PdfiumTextWriter } from "@app/tools/pdfTextEditor/pdfium/PdfiumTextWriter";
import { collectMemberPtrs } from "@app/tools/pdfTextEditor/commands/editTextHelpers";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
import {
setScanOverride,
type ScanOverride,
@@ -115,11 +116,10 @@ export function readObjFill(
m: import("@embedpdf/pdfium").WrappedPdfiumModule,
objPtr: number,
): RGBA | null {
- const exports = m.pdfium.wasmExports;
- const r = exports.malloc(4);
- const g = exports.malloc(4);
- const b = exports.malloc(4);
- const a = exports.malloc(4);
+ const r = scratchPtr(m, SCRATCH.colourR, 4);
+ const g = scratchPtr(m, SCRATCH.colourG, 4);
+ const b = scratchPtr(m, SCRATCH.colourB, 4);
+ const a = scratchPtr(m, SCRATCH.colourA, 4);
try {
if (!m.FPDFPageObj_GetFillColor(objPtr, r, g, b, a)) return null;
return {
@@ -130,10 +130,5 @@ export function readObjFill(
};
} catch {
return null;
- } finally {
- exports.free(r);
- exports.free(g);
- exports.free(b);
- exports.free(a);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
index b2afe4a1b6..aa673cbed9 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
@@ -6,6 +6,7 @@ import {
applyInkState,
collectMemberPtrs,
} from "@app/tools/pdfTextEditor/commands/editTextHelpers";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Render modes that paint an outline; 0 is fill-only, 3 is invisible. */
const FILL_ONLY = 0;
@@ -180,12 +181,11 @@ function readMemberInk(
} catch {
/* keep the run-level value */
}
- const exports = m.pdfium.wasmExports;
- const r = exports.malloc(4);
- const g = exports.malloc(4);
- const b = exports.malloc(4);
- const a = exports.malloc(4);
- const w = exports.malloc(4);
+ const r = scratchPtr(m, SCRATCH.outlineR, 4);
+ const g = scratchPtr(m, SCRATCH.outlineG, 4);
+ const b = scratchPtr(m, SCRATCH.outlineB, 4);
+ const a = scratchPtr(m, SCRATCH.outlineA, 4);
+ const w = scratchPtr(m, SCRATCH.outlineW, 4);
try {
let stroke: RGBA | null = null;
if (mod.FPDFPageObj_GetStrokeColor?.(ptr, r, g, b, a)) {
@@ -204,12 +204,6 @@ function readMemberInk(
return { ptr, renderMode, stroke, strokeWidth };
} catch {
return { ptr, renderMode, stroke: null, strokeWidth: 0 };
- } finally {
- exports.free(r);
- exports.free(g);
- exports.free(b);
- exports.free(a);
- exports.free(w);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
index 0edffabec1..a9b0e4eeef 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
@@ -1,4 +1,4 @@
-import { readUtf16, writeUtf16 } from "@app/services/pdfiumService";
+import { readUtf16 } from "@app/services/pdfiumService";
import type {
ParagraphLineSlot,
TextRun,
@@ -19,6 +19,7 @@ import { getActiveCharcodeStrategy } from "@app/tools/pdfTextEditor/charcode/Cha
import { emitFallbackTextObject } from "@app/tools/pdfTextEditor/util/fallbackFont";
import { emitDeviceFontTextObject } from "@app/tools/pdfTextEditor/util/deviceFontEmbed";
import { nearestStandardFont } from "@app/tools/pdfTextEditor/util/fontFamily";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
// Remove a PAGE-level object and FREE its PDFium allocation.
// `FPDFPage_RemoveObject` only detaches the object.
@@ -356,7 +357,7 @@ function charOriginPt(
const mod = m as unknown as LooseBoxModule;
if (!mod.FPDFText_GetCharOrigin) return null;
// FPDFText_GetCharOrigin takes two double* out-params.
- const buf = m.pdfium.wasmExports.malloc(16);
+ const buf = scratchPtr(m, SCRATCH.editOrigin, 16);
try {
if (!mod.FPDFText_GetCharOrigin(tp, idx, buf, buf + 8)) return null;
return {
@@ -365,8 +366,6 @@ function charOriginPt(
};
} catch {
return null;
- } finally {
- m.pdfium.wasmExports.free(buf);
}
}
@@ -377,12 +376,7 @@ function looseBoxAdvancePt(
): number | null {
const mod = m as unknown as LooseBoxModule;
if (!mod.FPDFText_GetLooseCharBox) return null;
- const wasm = (
- m.pdfium as unknown as {
- wasmExports: { malloc: (n: number) => number; free: (p: number) => void };
- }
- ).wasmExports;
- const buf = wasm.malloc(16); // FS_RECT = 4 floats {left, top, right, bottom}
+ const buf = scratchPtr(m, SCRATCH.editLoose, 16);
try {
if (!mod.FPDFText_GetLooseCharBox(tp, idx, buf)) return null;
const heap = (m.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;
@@ -391,8 +385,6 @@ function looseBoxAdvancePt(
return width > 0 ? width : null;
} catch {
return null;
- } finally {
- wasm.free(buf);
}
}
@@ -401,7 +393,7 @@ function objMatrixScale(
m: import("@embedpdf/pdfium").WrappedPdfiumModule,
objPtr: number,
): number {
- const buf = m.pdfium.wasmExports.malloc(6 * 4);
+ const buf = scratchPtr(m, SCRATCH.editMatrix, 6 * 4);
try {
if (!m.FPDFPageObj_GetMatrix(objPtr, buf)) return 1;
const a = m.pdfium.getValue(buf, "float");
@@ -410,8 +402,6 @@ function objMatrixScale(
return s > 0 ? s : 1;
} catch {
return 1;
- } finally {
- m.pdfium.wasmExports.free(buf);
}
}
@@ -1229,13 +1219,9 @@ export function readObjTexts(
out[i] = "";
continue;
}
- const buf = m.pdfium.wasmExports.malloc(len);
- try {
- mod.FPDFTextObj_GetText(objPtr, tp, buf, len);
- out[i] = readUtf16(m, buf, len);
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.editRunText, len);
+ mod.FPDFTextObj_GetText(objPtr, tp, buf, len);
+ out[i] = readUtf16(m, buf, len);
} catch {
out[i] = null;
}
@@ -1268,13 +1254,9 @@ function readBackTextObj(
try {
const len = mod.FPDFTextObj_GetText(objPtr, tp, 0, 0);
if (len <= 2) return "";
- const buf = m.pdfium.wasmExports.malloc(len);
- try {
- mod.FPDFTextObj_GetText(objPtr, tp, buf, len);
- return readUtf16(m, buf, len);
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.editObjText, len);
+ mod.FPDFTextObj_GetText(objPtr, tp, buf, len);
+ return readUtf16(m, buf, len);
} catch {
return null;
} finally {
@@ -1290,19 +1272,11 @@ export function measureObjRightEdgePt(
m: WrappedPdfiumModule,
objPtr: number,
): number {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetBounds(objPtr, l, b, r, t)) return 0;
- return m.pdfium.getValue(r, "float");
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
+ const buf = scratchPtr(m, SCRATCH.editBoxA, 16);
+ if (!m.FPDFPageObj_GetBounds(objPtr, buf, buf + 4, buf + 8, buf + 12)) {
+ return 0;
}
+ return m.pdfium.getValue(buf + 8, "float");
}
/**
@@ -1356,42 +1330,33 @@ export function measureObjSpanPt(
m: WrappedPdfiumModule,
ptrs: number[],
): { left: number; right: number } | null {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
- try {
- let left = Infinity;
- let right = -Infinity;
- for (const ptr of ptrs) {
- if (!ptr) continue;
- try {
- if (!m.FPDFPageObj_GetBounds(ptr, l, b, r, t)) continue;
- } catch {
+ const buf = scratchPtr(m, SCRATCH.editBoxB, 16);
+ let left = Infinity;
+ let right = -Infinity;
+ for (const ptr of ptrs) {
+ if (!ptr) continue;
+ try {
+ if (!m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) {
continue;
}
- const lo = m.pdfium.getValue(l, "float");
- const hi = m.pdfium.getValue(r, "float");
- if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;
- if (lo < left) left = lo;
- if (hi > right) right = hi;
+ } catch {
+ continue;
}
- return right > left ? { left, right } : null;
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
+ const lo = m.pdfium.getValue(buf, "float");
+ const hi = m.pdfium.getValue(buf + 8, "float");
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;
+ if (lo < left) left = lo;
+ if (hi > right) right = hi;
}
+ return right > left ? { left, right } : null;
}
function setTextOn(m: WrappedPdfiumModule, ptr: number, text: string): void {
- const textPtr = writeUtf16(m, text);
- try {
- m.FPDFText_SetText(ptr, textPtr);
- } finally {
- m.pdfium.wasmExports.free(textPtr);
- }
+ // FPDFText_SetText copies, so a pooled buffer is safe to overwrite next call.
+ const byteLen = (text.length + 1) * 2;
+ const textPtr = scratchPtr(m, SCRATCH.editSetText, byteLen);
+ m.pdfium.stringToUTF16(text, textPtr, byteLen);
+ m.FPDFText_SetText(ptr, textPtr);
}
interface InkState {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts
index 9fa46d4751..9b05fdb6c3 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/partialEdit.ts
@@ -17,6 +17,7 @@ import {
} from "@app/tools/pdfTextEditor/util/fontCapability";
import { writeUtf16 } from "@app/services/pdfiumService";
import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Set the text of an EXISTING PDFium text object, preserving its font. */
export function setObjText(
@@ -41,24 +42,14 @@ function objBoundsLR(
ptr: number,
fallbackX: number,
): { x: number; right: number } {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetBounds(ptr, l, b, r, t)) {
- return { x: fallbackX, right: fallbackX };
- }
- return {
- x: m.pdfium.getValue(l, "float"),
- right: m.pdfium.getValue(r, "float"),
- };
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
+ const buf = scratchPtr(m, SCRATCH.partialBbox, 16);
+ if (!m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) {
+ return { x: fallbackX, right: fallbackX };
}
+ return {
+ x: m.pdfium.getValue(buf, "float"),
+ right: m.pdfium.getValue(buf + 8, "float"),
+ };
}
// Map freshly-emitted line objects back to the text they carry, building the
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts
index 63b573f701..0da6c7a1a6 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/DisplayTransform.ts
@@ -1,4 +1,5 @@
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Maps a page's raw PDF object coordinates to "display-PDF" space. */
export interface DisplayTransformData {
@@ -322,33 +323,28 @@ function readBox(
mod: CropBoxModule,
pagePtr: number,
): PageBox | null {
- const exports = m.pdfium.wasmExports;
- const buf = exports.malloc(16);
+ const buf = scratchPtr(m, SCRATCH.displayRect, 16);
if (!buf) return null;
- try {
- const slot = (i: number): number => m.pdfium.getValue(buf + i * 4, "float");
- const bounding = mod.FPDF_GetPageBoundingBox;
- if (bounding) {
- const ok = callSafely(() => !!bounding(pagePtr, buf), false);
- const effective = ok
- ? normaliseBox(slot(0), slot(3), slot(2), slot(1))
- : null;
- if (effective) return effective;
- }
- const readRect = (fn?: BoxReader): PageBox | null => {
- if (!fn) return null;
- const ok = callSafely(
- () => !!fn(pagePtr, buf, buf + 4, buf + 8, buf + 12),
- false,
- );
- if (!ok) return null;
- return normaliseBox(slot(0), slot(1), slot(2), slot(3));
- };
- const crop = readRect(mod.FPDFPage_GetCropBox);
- const media = readRect(mod.FPDFPage_GetMediaBox);
- if (crop && media) return intersectBoxes(crop, media) ?? media;
- return crop ?? media;
- } finally {
- exports.free(buf);
+ const slot = (i: number): number => m.pdfium.getValue(buf + i * 4, "float");
+ const bounding = mod.FPDF_GetPageBoundingBox;
+ if (bounding) {
+ const ok = callSafely(() => !!bounding(pagePtr, buf), false);
+ const effective = ok
+ ? normaliseBox(slot(0), slot(3), slot(2), slot(1))
+ : null;
+ if (effective) return effective;
}
+ const readRect = (fn?: BoxReader): PageBox | null => {
+ if (!fn) return null;
+ const ok = callSafely(
+ () => !!fn(pagePtr, buf, buf + 4, buf + 8, buf + 12),
+ false,
+ );
+ if (!ok) return null;
+ return normaliseBox(slot(0), slot(1), slot(2), slot(3));
+ };
+ const crop = readRect(mod.FPDFPage_GetCropBox);
+ const media = readRect(mod.FPDFPage_GetMediaBox);
+ if (crop && media) return intersectBoxes(crop, media) ?? media;
+ return crop ?? media;
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts
index 240e2dd7b8..d3fa6e5e94 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -8,6 +8,7 @@ import { Page } from "@app/tools/pdfTextEditor/model/Page";
import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
import { FontRef } from "@app/tools/pdfTextEditor/model/FontRef";
import { prepareForEditing } from "@app/tools/pdfTextEditor/pdfdoc/prepareForEditing";
+import { releaseScratch } from "@app/tools/pdfTextEditor/util/wasmScratch";
// Lifetime-managed PDFium document wrapper for the PDF text editor. - Opens a
// raw PDFium document pointer from bytes.
@@ -184,5 +185,6 @@ export class EditorDocument {
}
this.ownedFonts.clear();
closeDocAndFreeBuffer(this.module, this.docPtr);
+ releaseScratch(this.module);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts
index 9e87b5d51b..223598a4ec 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts
@@ -4,6 +4,7 @@ import {
annotationKindFor,
} from "@app/tools/pdfTextEditor/model/AnnotationBox";
import type { Page } from "@app/tools/pdfTextEditor/model/Page";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
// The canvas renders with FPDF_ANNOT, but the editor model walks page objects
// only - so FreeText/widget/stamp text is visible and completely uneditable.
@@ -48,44 +49,40 @@ export class PdfiumAnnotationReader {
}
const out: AnnotationBox[] = [];
- const rectBuf = m.pdfium.wasmExports.malloc(4 * 4);
- try {
- for (let i = 0; i < Math.min(count, MAX_ANNOTS); i++) {
- const annot = mod.FPDFPage_GetAnnot(page.pagePtr, i);
- if (!annot) continue;
- try {
- const kind = annotationKindFor(mod.FPDFAnnot_GetSubtype(annot));
- if (!kind) continue;
- if (!getRect(annot, rectBuf)) continue;
- const left = m.pdfium.getValue(rectBuf, "float");
- const top = m.pdfium.getValue(rectBuf + 4, "float");
- const right = m.pdfium.getValue(rectBuf + 8, "float");
- const bottom = m.pdfium.getValue(rectBuf + 12, "float");
- const x = Math.min(left, right);
- const y = Math.min(top, bottom);
- const width = Math.abs(right - left);
- const height = Math.abs(top - bottom);
- // Degenerate rects (hidden widgets) would draw a dot over the page.
- if (!(width > 1 && height > 1)) continue;
- if (
- !Number.isFinite(x) ||
- !Number.isFinite(y) ||
- !Number.isFinite(width) ||
- !Number.isFinite(height)
- ) {
- continue;
- }
- out.push({
- id: `p${page.index}-annot-${i}`,
- kind,
- rect: { x, y, width, height },
- });
- } finally {
- mod.FPDFPage_CloseAnnot(annot);
+ const rectBuf = scratchPtr(m, SCRATCH.annotRect, 16);
+ for (let i = 0; i < Math.min(count, MAX_ANNOTS); i++) {
+ const annot = mod.FPDFPage_GetAnnot(page.pagePtr, i);
+ if (!annot) continue;
+ try {
+ const kind = annotationKindFor(mod.FPDFAnnot_GetSubtype(annot));
+ if (!kind) continue;
+ if (!getRect(annot, rectBuf)) continue;
+ const left = m.pdfium.getValue(rectBuf, "float");
+ const top = m.pdfium.getValue(rectBuf + 4, "float");
+ const right = m.pdfium.getValue(rectBuf + 8, "float");
+ const bottom = m.pdfium.getValue(rectBuf + 12, "float");
+ const x = Math.min(left, right);
+ const y = Math.min(top, bottom);
+ const width = Math.abs(right - left);
+ const height = Math.abs(top - bottom);
+ // Degenerate rects (hidden widgets) would draw a dot over the page.
+ if (!(width > 1 && height > 1)) continue;
+ if (
+ !Number.isFinite(x) ||
+ !Number.isFinite(y) ||
+ !Number.isFinite(width) ||
+ !Number.isFinite(height)
+ ) {
+ continue;
}
+ out.push({
+ id: `p${page.index}-annot-${i}`,
+ kind,
+ rect: { x, y, width, height },
+ });
+ } finally {
+ mod.FPDFPage_CloseAnnot(annot);
}
- } finally {
- m.pdfium.wasmExports.free(rectBuf);
}
page.setAnnotations(out);
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index 49e4822da9..c4574a88b3 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -17,6 +17,7 @@ import type {
} from "@app/tools/pdfTextEditor/types";
import { readUtf16 } from "@app/services/pdfiumService";
import { registerEmbeddedFace } from "@app/tools/pdfTextEditor/util/embeddedFace";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** PDFium page-object type constants - mirrors `public/fpdf_edit.h`. */
const FPDF_PAGEOBJ_TEXT = 1;
@@ -168,37 +169,30 @@ function collectCharGeometry(
if (charCount <= 1) return null;
const ptrToRun = indexRunsByObjectPtr(page.runs);
- const wasm = m.pdfium.wasmExports;
- const rectBuf = wasm.malloc(16); // FS_RECT: 4 floats {l, t, r, b}
- const xPtr = wasm.malloc(8);
- const yPtr = wasm.malloc(8);
+ const rectBuf = scratchPtr(m, SCRATCH.readerCharRect, 16);
+ const xPtr = scratchPtr(m, SCRATCH.readerCharX, 8);
+ const yPtr = scratchPtr(m, SCRATCH.readerCharY, 8);
const out: CharGeometry[] = [];
- try {
- for (let i = 0; i < charCount; i += 1) {
- const cp = m.FPDFText_GetUnicode(textPagePtr, i);
- const objPtr = m.FPDFText_GetTextObject(textPagePtr, i);
- const run = objPtr ? (ptrToRun.get(objPtr) ?? null) : null;
- const boxed = probe.FPDFText_GetLooseCharBox(textPagePtr, i, rectBuf);
- const heap = (m.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;
- const f = new Float32Array(heap.buffer, rectBuf, 4);
- let originX = Number.NaN;
- if (probe.FPDFText_GetCharOrigin?.(textPagePtr, i, xPtr, yPtr)) {
- originX = m.pdfium.getValue(xPtr, "double");
- }
- out.push({
- cp,
- run,
- ok: boxed,
- left: boxed ? f[0] : Number.NaN,
- right: boxed ? f[2] : Number.NaN,
- bottom: boxed ? f[3] : Number.NaN,
- originX,
- });
+ for (let i = 0; i < charCount; i += 1) {
+ const cp = m.FPDFText_GetUnicode(textPagePtr, i);
+ const objPtr = m.FPDFText_GetTextObject(textPagePtr, i);
+ const run = objPtr ? (ptrToRun.get(objPtr) ?? null) : null;
+ const boxed = probe.FPDFText_GetLooseCharBox(textPagePtr, i, rectBuf);
+ const heap = (m.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;
+ const f = new Float32Array(heap.buffer, rectBuf, 4);
+ let originX = Number.NaN;
+ if (probe.FPDFText_GetCharOrigin?.(textPagePtr, i, xPtr, yPtr)) {
+ originX = m.pdfium.getValue(xPtr, "double");
}
- } finally {
- wasm.free(rectBuf);
- wasm.free(xPtr);
- wasm.free(yPtr);
+ out.push({
+ cp,
+ run,
+ ok: boxed,
+ left: boxed ? f[0] : Number.NaN,
+ right: boxed ? f[2] : Number.NaN,
+ bottom: boxed ? f[3] : Number.NaN,
+ originX,
+ });
}
return out;
}
@@ -758,69 +752,53 @@ function pushEdge(
}
function readBounds(m: WrappedPdfiumModule, objPtr: number): PageRect | null {
- const lPtr = m.pdfium.wasmExports.malloc(4);
- const bPtr = m.pdfium.wasmExports.malloc(4);
- const rPtr = m.pdfium.wasmExports.malloc(4);
- const tPtr = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetBounds(objPtr, lPtr, bPtr, rPtr, tPtr)) return null;
- const left = m.pdfium.getValue(lPtr, "float");
- const bottom = m.pdfium.getValue(bPtr, "float");
- const right = m.pdfium.getValue(rPtr, "float");
- const top = m.pdfium.getValue(tPtr, "float");
- return {
- x: Math.min(left, right),
- y: Math.min(bottom, top),
- width: Math.abs(right - left),
- height: Math.abs(top - bottom),
- };
- } finally {
- m.pdfium.wasmExports.free(lPtr);
- m.pdfium.wasmExports.free(bPtr);
- m.pdfium.wasmExports.free(rPtr);
- m.pdfium.wasmExports.free(tPtr);
+ const buf = scratchPtr(m, SCRATCH.readerBounds, 16);
+ if (!m.FPDFPageObj_GetBounds(objPtr, buf, buf + 4, buf + 8, buf + 12)) {
+ return null;
}
+ const left = m.pdfium.getValue(buf, "float");
+ const bottom = m.pdfium.getValue(buf + 4, "float");
+ const right = m.pdfium.getValue(buf + 8, "float");
+ const top = m.pdfium.getValue(buf + 12, "float");
+ return {
+ x: Math.min(left, right),
+ y: Math.min(bottom, top),
+ width: Math.abs(right - left),
+ height: Math.abs(top - bottom),
+ };
}
function readMatrix(m: WrappedPdfiumModule, objPtr: number): Affine {
// FS_MATRIX: { a, b, c, d, e, f } as floats.
- const buf = m.pdfium.wasmExports.malloc(6 * 4);
- try {
- const ok = m.FPDFPageObj_GetMatrix(objPtr, buf);
- if (!ok) return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
- return {
- a: m.pdfium.getValue(buf, "float"),
- b: m.pdfium.getValue(buf + 4, "float"),
- c: m.pdfium.getValue(buf + 8, "float"),
- d: m.pdfium.getValue(buf + 12, "float"),
- e: m.pdfium.getValue(buf + 16, "float"),
- f: m.pdfium.getValue(buf + 20, "float"),
- };
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.readerMatrix, 6 * 4);
+ const ok = m.FPDFPageObj_GetMatrix(objPtr, buf);
+ if (!ok) return { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+ return {
+ a: m.pdfium.getValue(buf, "float"),
+ b: m.pdfium.getValue(buf + 4, "float"),
+ c: m.pdfium.getValue(buf + 8, "float"),
+ d: m.pdfium.getValue(buf + 12, "float"),
+ e: m.pdfium.getValue(buf + 16, "float"),
+ f: m.pdfium.getValue(buf + 20, "float"),
+ };
}
function readFill(m: WrappedPdfiumModule, objPtr: number): RGBA {
- const r = m.pdfium.wasmExports.malloc(4);
- const g = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const a = m.pdfium.wasmExports.malloc(4);
- try {
- const ok = m.FPDFPageObj_GetFillColor(objPtr, r, g, b, a);
- if (!ok) return { r: 0, g: 0, b: 0, a: 255 };
- return {
- r: m.pdfium.getValue(r, "i32") & 0xff,
- g: m.pdfium.getValue(g, "i32") & 0xff,
- b: m.pdfium.getValue(b, "i32") & 0xff,
- a: m.pdfium.getValue(a, "i32") & 0xff,
- };
- } finally {
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(g);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(a);
- }
+ const buf = scratchPtr(m, SCRATCH.readerFill, 16);
+ const ok = m.FPDFPageObj_GetFillColor(
+ objPtr,
+ buf,
+ buf + 4,
+ buf + 8,
+ buf + 12,
+ );
+ if (!ok) return { r: 0, g: 0, b: 0, a: 255 };
+ return {
+ r: m.pdfium.getValue(buf, "i32") & 0xff,
+ g: m.pdfium.getValue(buf + 4, "i32") & 0xff,
+ b: m.pdfium.getValue(buf + 8, "i32") & 0xff,
+ a: m.pdfium.getValue(buf + 12, "i32") & 0xff,
+ };
}
interface StrokeReaderModule {
@@ -849,36 +827,29 @@ function readStroke(
const getColor = mod.FPDFPageObj_GetStrokeColor;
const getWidth = mod.FPDFPageObj_GetStrokeWidth;
if (!getColor) return { stroke: null, strokeWidth: 0 };
- const r = m.pdfium.wasmExports.malloc(4);
- const g = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const a = m.pdfium.wasmExports.malloc(4);
- const w = m.pdfium.wasmExports.malloc(4);
try {
- if (!getColor(objPtr, r, g, b, a)) return { stroke: null, strokeWidth: 0 };
- const alpha = m.pdfium.getValue(a, "i32") & 0xff;
+ const buf = scratchPtr(m, SCRATCH.readerStroke, 20);
+ if (!getColor(objPtr, buf, buf + 4, buf + 8, buf + 12)) {
+ return { stroke: null, strokeWidth: 0 };
+ }
+ const alpha = m.pdfium.getValue(buf + 12, "i32") & 0xff;
let strokeWidth = 0;
- if (getWidth && getWidth(objPtr, w)) {
- const raw = m.pdfium.getValue(w, "float");
+ if (getWidth && getWidth(objPtr, buf + 16)) {
+ const raw = m.pdfium.getValue(buf + 16, "float");
if (Number.isFinite(raw) && raw > 0) strokeWidth = raw;
}
return {
stroke: {
- r: m.pdfium.getValue(r, "i32") & 0xff,
- g: m.pdfium.getValue(g, "i32") & 0xff,
- b: m.pdfium.getValue(b, "i32") & 0xff,
+ r: m.pdfium.getValue(buf, "i32") & 0xff,
+ g: m.pdfium.getValue(buf + 4, "i32") & 0xff,
+ b: m.pdfium.getValue(buf + 8, "i32") & 0xff,
a: alpha,
},
strokeWidth,
};
} catch {
+ // A throwing stroke accessor must not abort the rest of the page.
return { stroke: null, strokeWidth: 0 };
- } finally {
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(g);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(a);
- m.pdfium.wasmExports.free(w);
}
}
@@ -890,13 +861,9 @@ function readTextObjString(
// First call returns size in bytes for the UTF-16 buffer (including NUL).
const len = m.FPDFTextObj_GetText(objPtr, textPagePtr, 0, 0);
if (len <= 2) return "";
- const buf = m.pdfium.wasmExports.malloc(len);
- try {
- m.FPDFTextObj_GetText(objPtr, textPagePtr, buf, len);
- return readUtf16(m, buf, len);
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.readerReadTextA, len);
+ m.FPDFTextObj_GetText(objPtr, textPagePtr, buf, len);
+ return readUtf16(m, buf, len);
}
/** 6-letter "ABCDEF+" subset tag PDFium prefixes onto subset font names. */
@@ -910,13 +877,9 @@ function readFontNameVia(
): string | null {
const len = getName(fontPtr, 0, 0);
if (len <= 1) return null;
- const buf = m.pdfium.wasmExports.malloc(len);
- try {
- getName(fontPtr, buf, len);
- return m.pdfium.UTF8ToString(buf);
- } finally {
- m.pdfium.wasmExports.free(buf);
- }
+ const buf = scratchPtr(m, SCRATCH.readerReadTextB, len);
+ getName(fontPtr, buf, len);
+ return m.pdfium.UTF8ToString(buf);
}
function readFontFamily(
@@ -967,14 +930,10 @@ function readTextRun(
const bounds = ident ? localBounds : transformRect(transform, localBounds);
const matrix = ident ? localMatrix : composeAffine(transform, localMatrix);
- const sizePtr = m.pdfium.wasmExports.malloc(4);
+ const sizePtr = scratchPtr(m, SCRATCH.readerSize, 4);
let rawFontSize = 12;
- try {
- if (m.FPDFTextObj_GetFontSize(objPtr, sizePtr)) {
- rawFontSize = m.pdfium.getValue(sizePtr, "float");
- }
- } finally {
- m.pdfium.wasmExports.free(sizePtr);
+ if (m.FPDFTextObj_GetFontSize(objPtr, sizePtr)) {
+ rawFontSize = m.pdfium.getValue(sizePtr, "float");
}
// The on-page visible font size is `rawFontSize * |matrix scale|`.
const matrixScale =
@@ -1065,36 +1024,22 @@ function readShape(
/** True when a path fills or strokes with any opacity; clip-only paths draw nothing. */
function isPainted(m: WrappedPdfiumModule, objPtr: number): boolean {
- const fillModePtr = m.pdfium.wasmExports.malloc(4);
- const strokePtr = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPath_GetDrawMode(objPtr, fillModePtr, strokePtr)) return false;
- const fills = m.pdfium.getValue(fillModePtr, "i32") !== 0;
- const strokes = m.pdfium.getValue(strokePtr, "i32") !== 0;
- return (
- (fills && readFill(m, objPtr).a > 0) ||
- (strokes && readStrokeAlpha(m, objPtr) > 0)
- );
- } finally {
- m.pdfium.wasmExports.free(fillModePtr);
- m.pdfium.wasmExports.free(strokePtr);
- }
+ const buf = scratchPtr(m, SCRATCH.shapeDrawMode, 8);
+ if (!m.FPDFPath_GetDrawMode(objPtr, buf, buf + 4)) return false;
+ const fills = m.pdfium.getValue(buf, "i32") !== 0;
+ const strokes = m.pdfium.getValue(buf + 4, "i32") !== 0;
+ return (
+ (fills && readFill(m, objPtr).a > 0) ||
+ (strokes && readStrokeAlpha(m, objPtr) > 0)
+ );
}
function readStrokeAlpha(m: WrappedPdfiumModule, objPtr: number): number {
- const r = m.pdfium.wasmExports.malloc(4);
- const g = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const a = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetStrokeColor(objPtr, r, g, b, a)) return 0;
- return m.pdfium.getValue(a, "i32") & 0xff;
- } finally {
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(g);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(a);
+ const buf = scratchPtr(m, SCRATCH.shapeStrokeAlpha, 16);
+ if (!m.FPDFPageObj_GetStrokeColor(objPtr, buf, buf + 4, buf + 8, buf + 12)) {
+ return 0;
}
+ return m.pdfium.getValue(buf + 12, "i32") & 0xff;
}
function readImage(
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextWriter.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextWriter.ts
index aaf73af28f..053f6371d4 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextWriter.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextWriter.ts
@@ -4,6 +4,7 @@ import type { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
import { writeUtf16 } from "@app/services/pdfiumService";
import { collectMemberPtrs } from "@app/tools/pdfTextEditor/commands/editTextHelpers";
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
// Narrowest base-14 glyph ("i") is ~0.22em, so ink well under ~0.15em per
// visible char means the font produced .notdef / zero-width filler.
@@ -85,20 +86,11 @@ function measureObjBboxPt(
m: WrappedPdfiumModule,
objPtr: number,
): { left: number; right: number } | null {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetBounds(objPtr, l, b, r, t)) return null;
- return {
- left: m.pdfium.getValue(l, "float"),
- right: m.pdfium.getValue(r, "float"),
- };
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
- }
+ const buf = scratchPtr(m, SCRATCH.writerBbox, 16);
+ if (!m.FPDFPageObj_GetBounds(objPtr, buf, buf + 4, buf + 8, buf + 12))
+ return null;
+ return {
+ left: m.pdfium.getValue(buf, "float"),
+ right: m.pdfium.getValue(buf + 8, "float"),
+ };
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/deviceFontEmbed.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
index 5a09a6d35c..1869698131 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
@@ -12,6 +12,7 @@ import {
isBoldFamily,
isItalicFamily,
} from "@app/tools/pdfTextEditor/util/fontFamily";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
// Embed the fonts installed on the user's device instead of substituting the
// nearest standard face. Reading the file is async, so the emit uses the cache.
@@ -223,20 +224,14 @@ export function loadDeviceFontInto(
function measureRightEdge(m: EditorDocument["module"], ptr: number): number {
const mod = m as unknown as DeviceFontModule;
if (typeof mod.FPDFPageObj_GetBounds !== "function") return 0;
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
+ const buf = scratchPtr(m, SCRATCH.editBoxA, 16);
try {
- if (!mod.FPDFPageObj_GetBounds(ptr, l, b, r, t)) return 0;
- return m.pdfium.getValue(r, "float");
+ if (!mod.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) {
+ return 0;
+ }
+ return m.pdfium.getValue(buf + 8, "float");
} catch {
return 0;
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/embeddedFace.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/embeddedFace.ts
index 09cb4cfcaa..42882b930e 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/embeddedFace.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/embeddedFace.ts
@@ -1,4 +1,5 @@
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
// The overlay used to collapse every document font to one of three generic CSS
// stacks, so editing text visibly changed its shape. PDFium will hand back the
@@ -93,20 +94,20 @@ function readFontData(
fontPtr: number,
): Uint8Array<ArrayBuffer> | null {
const w = m.pdfium.wasmExports;
- const lenPtr = w.malloc(4);
+ const lenPtr = scratchPtr(m, SCRATCH.faceLen, 4);
let size = 0;
try {
if (!m.FPDFFont_GetFontData(fontPtr, 0, 0, lenPtr)) return null;
size = m.pdfium.getValue(lenPtr, "i32");
} catch {
return null;
- } finally {
- w.free(lenPtr);
}
if (size <= 0 || size > MAX_FACE_BYTES) return null;
+ // scratchPtr throws when the arena cannot grow: allocate it before the
+ // font-data buffer so a throw cannot orphan an allocation outside try.
+ const out = scratchPtr(m, SCRATCH.faceOut, 4);
const buf = w.malloc(size);
- const out = w.malloc(4);
try {
if (!m.FPDFFont_GetFontData(fontPtr, buf, size, out)) return null;
const heap = new Uint8Array(
@@ -125,7 +126,6 @@ function readFontData(
return null;
} finally {
w.free(buf);
- w.free(out);
}
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/fallbackFont.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/fallbackFont.ts
index 46055622e2..af6439b8b3 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/fallbackFont.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/fallbackFont.ts
@@ -5,6 +5,7 @@ import { FontRef } from "@app/tools/pdfTextEditor/model/FontRef";
import { parseTrueTypeCmap } from "@app/tools/pdfTextEditor/charcode/CmapResolver";
import { writeUtf16 } from "@app/services/pdfiumService";
import { BASE_PATH } from "@app/constants/app";
+import { SCRATCH, scratchPtr } from "@app/tools/pdfTextEditor/util/wasmScratch";
/** Client-side Unicode fallback font. */
// BASE_PATH-prefixed: a bare "/fonts/..." 404s on subpath deployments
@@ -136,19 +137,9 @@ export function loadFallbackFontInto(doc: EditorDocument): number {
/** Right edge (PDF points) of an object's visible bbox, or 0 if unmeasurable. */
function measureRightEdge(m: EditorDocument["module"], ptr: number): number {
- const l = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const r = m.pdfium.wasmExports.malloc(4);
- const t = m.pdfium.wasmExports.malloc(4);
- try {
- if (!m.FPDFPageObj_GetBounds(ptr, l, b, r, t)) return 0;
- return m.pdfium.getValue(r, "float");
- } finally {
- m.pdfium.wasmExports.free(l);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(t);
- }
+ const buf = scratchPtr(m, SCRATCH.fallbackL, 16);
+ if (!m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) return 0;
+ return m.pdfium.getValue(buf + 8, "float");
}
interface CreateTextObjModule {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.test.ts
new file mode 100644
index 0000000000..2f545ab1dd
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.test.ts
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi } from "vitest";
+import {
+ SCRATCH,
+ releaseScratch,
+ scratchPtr,
+} from "@app/tools/pdfTextEditor/util/wasmScratch";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+
+function fakeModule() {
+ let next = 1024;
+ const malloc = vi.fn((n: number) => {
+ const p = next;
+ next += n + 16;
+ return p;
+ });
+ const free = vi.fn();
+ const m = {
+ pdfium: { wasmExports: { malloc, free } },
+ } as unknown as WrappedPdfiumModule;
+ return { m, malloc, free };
+}
+
+describe("scratchPtr", () => {
+ it("reuses the same buffer for the same purpose", () => {
+ const { m, malloc } = fakeModule();
+ const a = scratchPtr(m, SCRATCH.readerCharRect, 16);
+ const b = scratchPtr(m, SCRATCH.readerCharRect, 16);
+ expect(b).toBe(a);
+ expect(malloc).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps different purposes apart", () => {
+ const { m, malloc } = fakeModule();
+ const rect = scratchPtr(m, SCRATCH.readerCharRect, 16);
+ const origin = scratchPtr(m, SCRATCH.readerCharX, 16);
+ expect(origin).not.toBe(rect);
+ expect(malloc).toHaveBeenCalledTimes(2);
+ });
+
+ it("grows a slot and frees the old buffer", () => {
+ const { m, malloc, free } = fakeModule();
+ const small = scratchPtr(m, SCRATCH.readerBounds, 8);
+ const big = scratchPtr(m, SCRATCH.readerBounds, 64);
+ expect(big).not.toBe(small);
+ expect(free).toHaveBeenCalledWith(small);
+ expect(malloc).toHaveBeenLastCalledWith(64);
+ expect(scratchPtr(m, SCRATCH.readerBounds, 32)).toBe(big);
+ expect(malloc).toHaveBeenCalledTimes(2);
+ });
+
+ it("never allocates less than four bytes", () => {
+ const { m, malloc } = fakeModule();
+ scratchPtr(m, SCRATCH.readerFill, 1);
+ expect(malloc).toHaveBeenCalledWith(4);
+ });
+
+ it("grows geometrically so a growing text buffer stops re-allocating", () => {
+ const { m, malloc } = fakeModule();
+ for (let bytes = 4; bytes <= 4096; bytes += 4) {
+ scratchPtr(m, SCRATCH.editRunText, bytes);
+ }
+ // Doubling from 4 to 4096 is 11 allocations; fitting exactly would be 1024.
+ expect(malloc.mock.calls.length).toBeLessThanOrEqual(12);
+ });
+
+ it("keeps arenas per module", () => {
+ const a = fakeModule();
+ const b = fakeModule();
+ scratchPtr(a.m, SCRATCH.readerCharRect, 16);
+ scratchPtr(b.m, SCRATCH.readerCharRect, 16);
+ expect(a.malloc).toHaveBeenCalledTimes(1);
+ expect(b.malloc).toHaveBeenCalledTimes(1);
+ });
+
+ it("releases every slot and re-allocates on next use", () => {
+ const { m, malloc, free } = fakeModule();
+ const rect = scratchPtr(m, SCRATCH.readerCharRect, 16);
+ const fill = scratchPtr(m, SCRATCH.readerFill, 16);
+ releaseScratch(m);
+ expect(free).toHaveBeenCalledWith(rect);
+ expect(free).toHaveBeenCalledWith(fill);
+ expect(free).toHaveBeenCalledTimes(2);
+ scratchPtr(m, SCRATCH.readerCharRect, 16);
+ expect(malloc).toHaveBeenCalledTimes(3);
+ });
+
+ it("releases an untouched module without calling free", () => {
+ const { m, free } = fakeModule();
+ releaseScratch(m);
+ expect(free).not.toHaveBeenCalled();
+ });
+
+ it("does not cache a zero allocation and retries on the next call", () => {
+ let calls = 0;
+ const malloc = vi.fn((n: number) => {
+ calls += 1;
+ return calls === 1 ? 0 : 4096 + n;
+ });
+ const free = vi.fn();
+ const m = {
+ pdfium: { wasmExports: { malloc, free } },
+ } as unknown as WrappedPdfiumModule;
+
+ expect(() => scratchPtr(m, SCRATCH.readerCharRect, 16)).toThrow(
+ /scratch allocation failed/,
+ );
+ expect(scratchPtr(m, SCRATCH.readerCharRect, 16)).toBe(4112);
+ expect(malloc).toHaveBeenCalledTimes(2);
+ expect(free).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.ts
new file mode 100644
index 0000000000..4ed39852c4
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/wasmScratch.ts
@@ -0,0 +1,145 @@
+/**
+ * One reusable wasm buffer per (module, purpose). PDFium calls take out-params
+ * as pointers, and a fresh 4-24 byte allocation per call put malloc/free
+ * traffic on the typing path. Slots are keyed by purpose, so a function that
+ * calls another never aliases its buffer.
+ *
+ * A slot keeps its high-water mark for as long as the module lives, so a
+ * variable-sized slot (text reads, charcodes) can pin the largest request made
+ * against it. `releaseScratch` drops every slot and `EditorDocument.dispose`
+ * calls it, so that retention ends with the document.
+ */
+interface Slot {
+ ptr: number;
+ size: number;
+}
+
+/** Interned slot identity: two calls share a buffer only when keys are equal. */
+export interface ScratchKey {
+ readonly id: number;
+}
+
+interface Arena {
+ slots: Array<Slot | undefined>;
+ exports: {
+ malloc: (n: number) => number;
+ free: (p: number) => void;
+ };
+}
+
+const arenas = new WeakMap<object, Arena>();
+let nextKeyId = 0;
+
+function key(): ScratchKey {
+ return { id: nextKeyId++ };
+}
+
+/** Every scratch buffer in the editor, one slot per purpose. */
+export const SCRATCH = {
+ readerCharRect: key(),
+ readerCharX: key(),
+ readerCharY: key(),
+ readerBounds: key(),
+ readerFill: key(),
+ readerMatrix: key(),
+ readerStroke: key(),
+ writerBbox: key(),
+ editBbox: key(),
+ reflowBbox: key(),
+ reflowMatrix: key(),
+ partialBbox: key(),
+ imageMatrix: key(),
+ annotRect: key(),
+ shapeDrawMode: key(),
+ shapeStrokeAlpha: key(),
+ colourR: key(),
+ colourG: key(),
+ colourB: key(),
+ colourA: key(),
+ outlineR: key(),
+ outlineG: key(),
+ outlineB: key(),
+ outlineA: key(),
+ outlineW: key(),
+ faceL: key(),
+ faceB: key(),
+ faceR: key(),
+ faceT: key(),
+ faceLen: key(),
+ faceOut: key(),
+ fallbackL: key(),
+ fallbackB: key(),
+ fallbackR: key(),
+ fallbackT: key(),
+ cmapSize: key(),
+ backendOut: key(),
+ displayRect: key(),
+ editOrigin: key(),
+ editLoose: key(),
+ editMatrix: key(),
+ editRunText: key(),
+ editObjText: key(),
+ editSetText: key(),
+ editBoxA: key(),
+ editBoxB: key(),
+ readerReadTextA: key(),
+ readerReadTextB: key(),
+ readerSize: key(),
+ reflowText: key(),
+ charcodes: key(),
+} as const;
+
+/** Structural minimum: any wrapper that exposes PDFium's wasm allocator. */
+export interface ScratchHost {
+ pdfium: {
+ wasmExports: {
+ malloc: (n: number) => number;
+ free: (p: number) => void;
+ };
+ };
+}
+
+function arenaFor(m: ScratchHost): Arena {
+ let arena = arenas.get(m);
+ if (!arena) {
+ arena = { slots: [], exports: m.pdfium.wasmExports };
+ arenas.set(m, arena);
+ }
+ return arena;
+}
+
+export function scratchPtr(
+ m: ScratchHost,
+ key: ScratchKey,
+ bytes: number,
+): number {
+ const arena = arenaFor(m);
+ const slot = arena.slots[key.id];
+ if (slot && slot.size >= bytes) return slot.ptr;
+ if (slot) arena.exports.free(slot.ptr);
+ // Double rather than fit exactly: text buffers grow a character at a time,
+ // and refitting would put a malloc/free pair back on every keystroke.
+ const size = Math.max(4, bytes, slot ? slot.size * 2 : 0);
+ const ptr = arena.exports.malloc(size);
+ // malloc only returns 0 when memory.grow failed, so a retry cannot help. A
+ // cached 0 would be handed to PDFium as a null out-param and never retried.
+ if (!ptr) {
+ arena.slots[key.id] = undefined;
+ throw new Error(`WASM scratch allocation failed (${size} bytes)`);
+ }
+ arena.slots[key.id] = { ptr, size };
+ return ptr;
+}
+
+/**
+ * Free every slot. Buffers never outlive a synchronous call, so any point
+ * between calls is safe; `EditorDocument.dispose` is where the retention ends.
+ */
+export function releaseScratch(m: ScratchHost): void {
+ const arena = arenas.get(m);
+ if (!arena) return;
+ for (const slot of arena.slots) {
+ if (slot) arena.exports.free(slot.ptr);
+ }
+ arena.slots = [];
+}